1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "x86-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62 "x86-experimental-vector-widening-legalization", cl::init(false),
63 cl::desc("Enable an experimental vector type legalization through widening "
64 "rather than promotion."),
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68 "x86-experimental-vector-shuffle-lowering", cl::init(false),
69 cl::desc("Enable an experimental vector shuffle lowering code path."),
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77 SelectionDAG &DAG, SDLoc dl,
78 unsigned vectorWidth) {
79 assert((vectorWidth == 128 || vectorWidth == 256) &&
80 "Unsupported vector width");
81 EVT VT = Vec.getValueType();
82 EVT ElVT = VT.getVectorElementType();
83 unsigned Factor = VT.getSizeInBits()/vectorWidth;
84 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85 VT.getVectorNumElements()/Factor);
87 // Extract from UNDEF is UNDEF.
88 if (Vec.getOpcode() == ISD::UNDEF)
89 return DAG.getUNDEF(ResultVT);
91 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
92 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
94 // This is the index of the first element of the vectorWidth-bit chunk
96 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
99 // If the input is a buildvector just emit a smaller one.
100 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
105 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
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 bounday. 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,
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 bounday. That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163 unsigned IdxVal, SelectionDAG &DAG,
165 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170 unsigned IdxVal, SelectionDAG &DAG,
172 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181 unsigned NumElems, SelectionDAG &DAG,
183 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188 unsigned NumElems, SelectionDAG &DAG,
190 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195 if (TT.isOSBinFormatMachO()) {
196 if (TT.getArch() == Triple::x86_64)
197 return new X86_64MachoTargetObjectFile();
198 return new TargetLoweringObjectFileMachO();
202 return new X86LinuxTargetObjectFile();
203 if (TT.isOSBinFormatELF())
204 return new TargetLoweringObjectFileELF();
205 if (TT.isKnownWindowsMSVCEnvironment())
206 return new X86WindowsTargetObjectFile();
207 if (TT.isOSBinFormatCOFF())
208 return new TargetLoweringObjectFileCOFF();
209 llvm_unreachable("unknown subtarget type");
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216 Subtarget = &TM.getSubtarget<X86Subtarget>();
217 X86ScalarSSEf64 = Subtarget->hasSSE2();
218 X86ScalarSSEf32 = Subtarget->hasSSE1();
219 TD = getDataLayout();
221 resetOperationActions();
224 void X86TargetLowering::resetOperationActions() {
225 const TargetMachine &TM = getTargetMachine();
226 static bool FirstTimeThrough = true;
228 // If none of the target options have changed, then we don't need to reset the
229 // operation actions.
230 if (!FirstTimeThrough && TO == TM.Options) return;
232 if (!FirstTimeThrough) {
233 // Reinitialize the actions.
235 FirstTimeThrough = false;
240 // Set up the TargetLowering object.
241 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
243 // X86 is weird, it always uses i8 for shift amounts and setcc results.
244 setBooleanContents(ZeroOrOneBooleanContent);
245 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
248 // For 64-bit since we have so many registers use the ILP scheduler, for
249 // 32-bit code use the register pressure specific scheduling.
250 // For Atom, always use ILP scheduling.
251 if (Subtarget->isAtom())
252 setSchedulingPreference(Sched::ILP);
253 else if (Subtarget->is64Bit())
254 setSchedulingPreference(Sched::ILP);
256 setSchedulingPreference(Sched::RegPressure);
257 const X86RegisterInfo *RegInfo =
258 TM.getSubtarget<X86Subtarget>().getRegisterInfo();
259 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
261 // Bypass expensive divides on Atom when compiling with O2
262 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263 addBypassSlowDiv(32, 8);
264 if (Subtarget->is64Bit())
265 addBypassSlowDiv(64, 16);
268 if (Subtarget->isTargetKnownWindowsMSVC()) {
269 // Setup Windows compiler runtime calls.
270 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272 setLibcallName(RTLIB::SREM_I64, "_allrem");
273 setLibcallName(RTLIB::UREM_I64, "_aullrem");
274 setLibcallName(RTLIB::MUL_I64, "_allmul");
275 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
281 // The _ftol2 runtime function has an unusual calling conv, which
282 // is modeled by a special pseudo-instruction.
283 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
289 if (Subtarget->isTargetDarwin()) {
290 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291 setUseUnderscoreSetJmp(false);
292 setUseUnderscoreLongJmp(false);
293 } else if (Subtarget->isTargetWindowsGNU()) {
294 // MS runtime is weird: it exports _setjmp, but longjmp!
295 setUseUnderscoreSetJmp(true);
296 setUseUnderscoreLongJmp(false);
298 setUseUnderscoreSetJmp(true);
299 setUseUnderscoreLongJmp(true);
302 // Set up the register classes.
303 addRegisterClass(MVT::i8, &X86::GR8RegClass);
304 addRegisterClass(MVT::i16, &X86::GR16RegClass);
305 addRegisterClass(MVT::i32, &X86::GR32RegClass);
306 if (Subtarget->is64Bit())
307 addRegisterClass(MVT::i64, &X86::GR64RegClass);
309 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
311 // We don't accept any truncstore of integer registers.
312 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
319 // SETOEQ and SETUNE require checking two conditions.
320 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
327 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
329 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
330 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
331 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
335 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
336 } else if (!TM.Options.UseSoftFloat) {
337 // We have an algorithm for SSE2->double, and we turn this into a
338 // 64-bit FILD followed by conditional FADD for other targets.
339 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
340 // We have an algorithm for SSE2, and we turn this into a 64-bit
341 // FILD for other targets.
342 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
345 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
347 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
350 if (!TM.Options.UseSoftFloat) {
351 // SSE has no i16 to fp conversion, only i32
352 if (X86ScalarSSEf32) {
353 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
354 // f32 and f64 cases are Legal, f80 case is not
355 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
357 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
358 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
361 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
362 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
365 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
366 // are Legal, f80 is custom lowered.
367 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
368 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
370 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
372 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
373 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
375 if (X86ScalarSSEf32) {
376 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
377 // f32 and f64 cases are Legal, f80 case is not
378 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
380 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
381 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
384 // Handle FP_TO_UINT by promoting the destination to a larger signed
386 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
387 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
388 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
390 if (Subtarget->is64Bit()) {
391 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
392 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
393 } else if (!TM.Options.UseSoftFloat) {
394 // Since AVX is a superset of SSE3, only check for SSE here.
395 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396 // Expand FP_TO_UINT into a select.
397 // FIXME: We would like to use a Custom expander here eventually to do
398 // the optimal thing for SSE vs. the default expansion in the legalizer.
399 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
401 // With SSE3 we can use fisttpll to convert to a signed i64; without
402 // SSE, we're stuck with a fistpll.
403 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
406 if (isTargetFTOL()) {
407 // Use the _ftol2 runtime function, which has a pseudo-instruction
408 // to handle its weird calling convention.
409 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
412 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413 if (!X86ScalarSSEf64) {
414 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
415 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
416 if (Subtarget->is64Bit()) {
417 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
418 // Without SSE, i64->f64 goes through memory.
419 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
423 // Scalar integer divide and remainder are lowered to use operations that
424 // produce two results, to match the available instructions. This exposes
425 // the two-result form to trivial CSE, which is able to combine x/y and x%y
426 // into a single instruction.
428 // Scalar integer multiply-high is also lowered to use two-result
429 // operations, to match the available instructions. However, plain multiply
430 // (low) operations are left as Legal, as there are single-result
431 // instructions for this in x86. Using the two-result multiply instructions
432 // when both high and low results are needed must be arranged by dagcombine.
433 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
435 setOperationAction(ISD::MULHS, VT, Expand);
436 setOperationAction(ISD::MULHU, VT, Expand);
437 setOperationAction(ISD::SDIV, VT, Expand);
438 setOperationAction(ISD::UDIV, VT, Expand);
439 setOperationAction(ISD::SREM, VT, Expand);
440 setOperationAction(ISD::UREM, VT, Expand);
442 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443 setOperationAction(ISD::ADDC, VT, Custom);
444 setOperationAction(ISD::ADDE, VT, Custom);
445 setOperationAction(ISD::SUBC, VT, Custom);
446 setOperationAction(ISD::SUBE, VT, Custom);
449 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
450 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
451 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
452 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
453 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
454 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
455 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
456 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
457 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
458 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
459 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
460 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
461 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
462 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
463 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
464 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
468 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
469 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
470 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
471 setOperationAction(ISD::FREM , MVT::f32 , Expand);
472 setOperationAction(ISD::FREM , MVT::f64 , Expand);
473 setOperationAction(ISD::FREM , MVT::f80 , Expand);
474 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
476 // Promote the i8 variants and force them on up to i32 which has a shorter
478 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
481 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
482 if (Subtarget->hasBMI()) {
483 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
484 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
485 if (Subtarget->is64Bit())
486 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
488 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
489 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
490 if (Subtarget->is64Bit())
491 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
494 if (Subtarget->hasLZCNT()) {
495 // When promoting the i8 variants, force them to i32 for a shorter
497 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
498 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
499 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
500 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
501 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
502 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
506 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
507 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
508 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
509 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
510 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
511 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
512 if (Subtarget->is64Bit()) {
513 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
514 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
518 // Special handling for half-precision floating point conversions.
519 // If we don't have F16C support, then lower half float conversions
520 // into library calls.
521 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
526 // There's never any support for operations beyond MVT::f32.
527 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
532 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
537 if (Subtarget->hasPOPCNT()) {
538 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
540 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
541 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
542 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
543 if (Subtarget->is64Bit())
544 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
547 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
549 if (!Subtarget->hasMOVBE())
550 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
552 // These should be promoted to a larger select which is supported.
553 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
554 // X86 wants to expand cmov itself.
555 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
556 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
557 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
558 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
559 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
560 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
561 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
562 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
563 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
564 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
565 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
566 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
567 if (Subtarget->is64Bit()) {
568 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
569 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
571 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
572 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574 // support continuation, user-level threading, and etc.. As a result, no
575 // other SjLj exception interfaces are implemented and please don't build
576 // your own exception handling based on them.
577 // LLVM/Clang supports zero-cost DWARF exception handling.
578 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
582 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
583 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
584 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
585 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
586 if (Subtarget->is64Bit())
587 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
589 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
590 if (Subtarget->is64Bit()) {
591 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
592 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
593 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
594 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
595 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
597 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
599 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
600 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
601 if (Subtarget->is64Bit()) {
602 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
603 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
604 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
607 if (Subtarget->hasSSE1())
608 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
610 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
612 // Expand certain atomics
613 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
615 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
620 if (Subtarget->hasCmpxchg16b()) {
621 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
624 // FIXME - use subtarget debug flags
625 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
630 if (Subtarget->is64Bit()) {
631 setExceptionPointerRegister(X86::RAX);
632 setExceptionSelectorRegister(X86::RDX);
634 setExceptionPointerRegister(X86::EAX);
635 setExceptionSelectorRegister(X86::EDX);
637 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
640 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
643 setOperationAction(ISD::TRAP, MVT::Other, Legal);
644 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
646 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647 setOperationAction(ISD::VASTART , MVT::Other, Custom);
648 setOperationAction(ISD::VAEND , MVT::Other, Expand);
649 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650 // TargetInfo::X86_64ABIBuiltinVaList
651 setOperationAction(ISD::VAARG , MVT::Other, Custom);
652 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
654 // TargetInfo::CharPtrBuiltinVaList
655 setOperationAction(ISD::VAARG , MVT::Other, Expand);
656 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
659 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
660 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
662 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
663 MVT::i64 : MVT::i32, Custom);
665 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666 // f32 and f64 use SSE.
667 // Set up the FP register classes.
668 addRegisterClass(MVT::f32, &X86::FR32RegClass);
669 addRegisterClass(MVT::f64, &X86::FR64RegClass);
671 // Use ANDPD to simulate FABS.
672 setOperationAction(ISD::FABS , MVT::f64, Custom);
673 setOperationAction(ISD::FABS , MVT::f32, Custom);
675 // Use XORP to simulate FNEG.
676 setOperationAction(ISD::FNEG , MVT::f64, Custom);
677 setOperationAction(ISD::FNEG , MVT::f32, Custom);
679 // Use ANDPD and ORPD to simulate FCOPYSIGN.
680 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
683 // Lower this to FGETSIGNx86 plus an AND.
684 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
687 // We don't support sin/cos/fmod
688 setOperationAction(ISD::FSIN , MVT::f64, Expand);
689 setOperationAction(ISD::FCOS , MVT::f64, Expand);
690 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691 setOperationAction(ISD::FSIN , MVT::f32, Expand);
692 setOperationAction(ISD::FCOS , MVT::f32, Expand);
693 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
695 // Expand FP immediates into loads from the stack, except for the special
697 addLegalFPImmediate(APFloat(+0.0)); // xorpd
698 addLegalFPImmediate(APFloat(+0.0f)); // xorps
699 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700 // Use SSE for f32, x87 for f64.
701 // Set up the FP register classes.
702 addRegisterClass(MVT::f32, &X86::FR32RegClass);
703 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
705 // Use ANDPS to simulate FABS.
706 setOperationAction(ISD::FABS , MVT::f32, Custom);
708 // Use XORP to simulate FNEG.
709 setOperationAction(ISD::FNEG , MVT::f32, Custom);
711 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
713 // Use ANDPS and ORPS to simulate FCOPYSIGN.
714 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
717 // We don't support sin/cos/fmod
718 setOperationAction(ISD::FSIN , MVT::f32, Expand);
719 setOperationAction(ISD::FCOS , MVT::f32, Expand);
720 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
722 // Special cases we handle for FP constants.
723 addLegalFPImmediate(APFloat(+0.0f)); // xorps
724 addLegalFPImmediate(APFloat(+0.0)); // FLD0
725 addLegalFPImmediate(APFloat(+1.0)); // FLD1
726 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
729 if (!TM.Options.UnsafeFPMath) {
730 setOperationAction(ISD::FSIN , MVT::f64, Expand);
731 setOperationAction(ISD::FCOS , MVT::f64, Expand);
732 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
734 } else if (!TM.Options.UseSoftFloat) {
735 // f32 and f64 in x87.
736 // Set up the FP register classes.
737 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
740 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
741 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
742 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
745 if (!TM.Options.UnsafeFPMath) {
746 setOperationAction(ISD::FSIN , MVT::f64, Expand);
747 setOperationAction(ISD::FSIN , MVT::f32, Expand);
748 setOperationAction(ISD::FCOS , MVT::f64, Expand);
749 setOperationAction(ISD::FCOS , MVT::f32, Expand);
750 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
753 addLegalFPImmediate(APFloat(+0.0)); // FLD0
754 addLegalFPImmediate(APFloat(+1.0)); // FLD1
755 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
763 // We don't support FMA.
764 setOperationAction(ISD::FMA, MVT::f64, Expand);
765 setOperationAction(ISD::FMA, MVT::f32, Expand);
767 // Long double always uses X87.
768 if (!TM.Options.UseSoftFloat) {
769 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
771 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
773 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774 addLegalFPImmediate(TmpFlt); // FLD0
776 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
779 APFloat TmpFlt2(+1.0);
780 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
782 addLegalFPImmediate(TmpFlt2); // FLD1
783 TmpFlt2.changeSign();
784 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
787 if (!TM.Options.UnsafeFPMath) {
788 setOperationAction(ISD::FSIN , MVT::f80, Expand);
789 setOperationAction(ISD::FCOS , MVT::f80, Expand);
790 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
793 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
795 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796 setOperationAction(ISD::FRINT, MVT::f80, Expand);
797 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798 setOperationAction(ISD::FMA, MVT::f80, Expand);
801 // Always use a library call for pow.
802 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
803 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
804 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
806 setOperationAction(ISD::FLOG, MVT::f80, Expand);
807 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809 setOperationAction(ISD::FEXP, MVT::f80, Expand);
810 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
812 // First set operation action for all vector types to either promote
813 // (for widening) or expand (for scalarization). Then we will selectively
814 // turn on ones that can be effectively codegen'd.
815 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817 MVT VT = (MVT::SimpleValueType)i;
818 setOperationAction(ISD::ADD , VT, Expand);
819 setOperationAction(ISD::SUB , VT, Expand);
820 setOperationAction(ISD::FADD, VT, Expand);
821 setOperationAction(ISD::FNEG, VT, Expand);
822 setOperationAction(ISD::FSUB, VT, Expand);
823 setOperationAction(ISD::MUL , VT, Expand);
824 setOperationAction(ISD::FMUL, VT, Expand);
825 setOperationAction(ISD::SDIV, VT, Expand);
826 setOperationAction(ISD::UDIV, VT, Expand);
827 setOperationAction(ISD::FDIV, VT, Expand);
828 setOperationAction(ISD::SREM, VT, Expand);
829 setOperationAction(ISD::UREM, VT, Expand);
830 setOperationAction(ISD::LOAD, VT, Expand);
831 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836 setOperationAction(ISD::FABS, VT, Expand);
837 setOperationAction(ISD::FSIN, VT, Expand);
838 setOperationAction(ISD::FSINCOS, VT, Expand);
839 setOperationAction(ISD::FCOS, VT, Expand);
840 setOperationAction(ISD::FSINCOS, VT, Expand);
841 setOperationAction(ISD::FREM, VT, Expand);
842 setOperationAction(ISD::FMA, VT, Expand);
843 setOperationAction(ISD::FPOWI, VT, Expand);
844 setOperationAction(ISD::FSQRT, VT, Expand);
845 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846 setOperationAction(ISD::FFLOOR, VT, Expand);
847 setOperationAction(ISD::FCEIL, VT, Expand);
848 setOperationAction(ISD::FTRUNC, VT, Expand);
849 setOperationAction(ISD::FRINT, VT, Expand);
850 setOperationAction(ISD::FNEARBYINT, VT, Expand);
851 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852 setOperationAction(ISD::MULHS, VT, Expand);
853 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854 setOperationAction(ISD::MULHU, VT, Expand);
855 setOperationAction(ISD::SDIVREM, VT, Expand);
856 setOperationAction(ISD::UDIVREM, VT, Expand);
857 setOperationAction(ISD::FPOW, VT, Expand);
858 setOperationAction(ISD::CTPOP, VT, Expand);
859 setOperationAction(ISD::CTTZ, VT, Expand);
860 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861 setOperationAction(ISD::CTLZ, VT, Expand);
862 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863 setOperationAction(ISD::SHL, VT, Expand);
864 setOperationAction(ISD::SRA, VT, Expand);
865 setOperationAction(ISD::SRL, VT, Expand);
866 setOperationAction(ISD::ROTL, VT, Expand);
867 setOperationAction(ISD::ROTR, VT, Expand);
868 setOperationAction(ISD::BSWAP, VT, Expand);
869 setOperationAction(ISD::SETCC, VT, Expand);
870 setOperationAction(ISD::FLOG, VT, Expand);
871 setOperationAction(ISD::FLOG2, VT, Expand);
872 setOperationAction(ISD::FLOG10, VT, Expand);
873 setOperationAction(ISD::FEXP, VT, Expand);
874 setOperationAction(ISD::FEXP2, VT, Expand);
875 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880 setOperationAction(ISD::TRUNCATE, VT, Expand);
881 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884 setOperationAction(ISD::VSELECT, VT, Expand);
885 setOperationAction(ISD::SELECT_CC, VT, Expand);
886 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888 setTruncStoreAction(VT,
889 (MVT::SimpleValueType)InnerVT, Expand);
890 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
893 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894 // we have to deal with them whether we ask for Expansion or not. Setting
895 // Expand causes its own optimisation problems though, so leave them legal.
896 if (VT.getVectorElementType() == MVT::i1)
897 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
900 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901 // with -msoft-float, disable use of MMX as well.
902 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904 // No operations on x86mmx supported, everything uses intrinsics.
907 // MMX-sized vectors (other than x86mmx) are expected to be expanded
908 // into smaller operations.
909 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
910 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
911 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
912 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
913 setOperationAction(ISD::AND, MVT::v8i8, Expand);
914 setOperationAction(ISD::AND, MVT::v4i16, Expand);
915 setOperationAction(ISD::AND, MVT::v2i32, Expand);
916 setOperationAction(ISD::AND, MVT::v1i64, Expand);
917 setOperationAction(ISD::OR, MVT::v8i8, Expand);
918 setOperationAction(ISD::OR, MVT::v4i16, Expand);
919 setOperationAction(ISD::OR, MVT::v2i32, Expand);
920 setOperationAction(ISD::OR, MVT::v1i64, Expand);
921 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
922 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
923 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
924 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
925 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
926 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
927 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
928 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
930 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
931 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
932 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
933 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
934 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
935 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
936 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
937 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
939 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
942 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
943 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
944 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
945 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
946 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
947 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
948 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
949 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
950 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
951 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
952 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
956 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
959 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960 // registers cannot be used even for integer operations.
961 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
966 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
967 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
968 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
969 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
970 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
971 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
972 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
973 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
974 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
975 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
976 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
977 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
978 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
979 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
980 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
981 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
982 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
983 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
984 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
985 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
986 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
987 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
989 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
990 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
991 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
992 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
994 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
995 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1000 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002 MVT VT = (MVT::SimpleValueType)i;
1003 // Do not attempt to custom lower non-power-of-2 vectors
1004 if (!isPowerOf2_32(VT.getVectorNumElements()))
1006 // Do not attempt to custom lower non-128-bit vectors
1007 if (!VT.is128BitVector())
1009 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1010 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1014 // We support custom legalizing of sext and anyext loads for specific
1015 // memory vector types which we can load as a scalar (or sequence of
1016 // scalars) and extend in-register to a legal 128-bit vector type. For sext
1017 // loads these must work with a single scalar load.
1018 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1019 if (Subtarget->is64Bit()) {
1020 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1021 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1023 setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024 setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025 setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026 setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027 setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028 setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1030 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1031 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1032 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1033 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1034 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1035 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1037 if (Subtarget->is64Bit()) {
1038 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1039 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1042 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044 MVT VT = (MVT::SimpleValueType)i;
1046 // Do not attempt to promote non-128-bit vectors
1047 if (!VT.is128BitVector())
1050 setOperationAction(ISD::AND, VT, Promote);
1051 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1052 setOperationAction(ISD::OR, VT, Promote);
1053 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1054 setOperationAction(ISD::XOR, VT, Promote);
1055 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1056 setOperationAction(ISD::LOAD, VT, Promote);
1057 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1058 setOperationAction(ISD::SELECT, VT, Promote);
1059 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1062 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1064 // Custom lower v2i64 and v2f64 selects.
1065 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1066 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1067 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1068 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1070 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1071 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1073 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1074 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1075 // As there is no 64-bit GPR available, we need build a special custom
1076 // sequence to convert from v2i32 to v2f32.
1077 if (!Subtarget->is64Bit())
1078 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1080 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1081 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1083 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1085 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1086 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1087 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1090 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1091 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1092 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1093 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1094 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1095 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1096 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1097 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1098 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1099 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1100 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1102 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1103 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1104 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1105 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1106 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1107 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1108 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1109 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1110 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1111 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1113 // FIXME: Do we need to handle scalar-to-vector here?
1114 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1116 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1117 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1118 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1119 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1120 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1121 // There is no BLENDI for byte vectors. We don't need to custom lower
1122 // some vselects for now.
1123 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1125 // SSE41 brings specific instructions for doing vector sign extend even in
1126 // cases where we don't have SRA.
1127 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1128 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1129 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1131 // i8 and i16 vectors are custom , because the source register and source
1132 // source memory operand types are not the same width. f32 vectors are
1133 // custom since the immediate controlling the insert encodes additional
1135 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1136 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1137 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1138 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1140 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1141 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1142 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1143 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1145 // FIXME: these should be Legal but thats only for the case where
1146 // the index is constant. For now custom expand to deal with that.
1147 if (Subtarget->is64Bit()) {
1148 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1149 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1153 if (Subtarget->hasSSE2()) {
1154 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1155 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1157 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1158 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1160 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1161 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1163 // In the customized shift lowering, the legal cases in AVX2 will be
1165 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1166 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1168 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1169 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1171 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1174 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1175 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1176 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1177 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1178 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1179 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1180 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1182 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1183 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1184 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1186 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1187 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1188 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1189 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1190 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1191 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1192 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1193 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1194 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1195 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1196 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1197 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1199 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1200 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1201 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1202 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1203 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1204 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1205 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1206 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1207 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1208 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1209 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1210 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1212 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1213 // even though v8i16 is a legal type.
1214 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1215 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1216 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1218 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1219 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1220 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1222 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1223 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1225 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1227 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1228 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1230 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1231 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1233 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1234 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1236 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1237 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1238 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1239 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1241 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1242 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1243 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1245 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1246 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1247 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1248 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1250 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1251 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1252 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1253 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1254 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1255 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1256 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1257 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1258 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1259 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1260 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1261 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1263 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1264 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1265 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1266 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1267 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1268 setOperationAction(ISD::FMA, MVT::f32, Legal);
1269 setOperationAction(ISD::FMA, MVT::f64, Legal);
1272 if (Subtarget->hasInt256()) {
1273 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1274 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1275 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1276 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1278 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1279 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1280 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1281 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1283 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1284 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1285 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1286 // Don't lower v32i8 because there is no 128-bit byte mul
1288 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1289 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1290 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1291 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1293 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1294 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1296 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1297 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1298 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1299 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1301 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1302 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1303 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1304 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1306 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1307 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1308 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1309 // Don't lower v32i8 because there is no 128-bit byte mul
1312 // In the customized shift lowering, the legal cases in AVX2 will be
1314 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1315 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1317 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1318 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1320 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1322 // Custom lower several nodes for 256-bit types.
1323 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1324 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1325 MVT VT = (MVT::SimpleValueType)i;
1327 // Extract subvector is special because the value type
1328 // (result) is 128-bit but the source is 256-bit wide.
1329 if (VT.is128BitVector())
1330 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1332 // Do not attempt to custom lower other non-256-bit vectors
1333 if (!VT.is256BitVector())
1336 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1337 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1338 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1339 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1340 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1341 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1342 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1345 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1346 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1347 MVT VT = (MVT::SimpleValueType)i;
1349 // Do not attempt to promote non-256-bit vectors
1350 if (!VT.is256BitVector())
1353 setOperationAction(ISD::AND, VT, Promote);
1354 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1355 setOperationAction(ISD::OR, VT, Promote);
1356 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1357 setOperationAction(ISD::XOR, VT, Promote);
1358 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1359 setOperationAction(ISD::LOAD, VT, Promote);
1360 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1361 setOperationAction(ISD::SELECT, VT, Promote);
1362 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1366 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1367 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1368 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1369 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1370 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1372 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1373 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1374 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1376 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1377 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1378 setOperationAction(ISD::XOR, MVT::i1, Legal);
1379 setOperationAction(ISD::OR, MVT::i1, Legal);
1380 setOperationAction(ISD::AND, MVT::i1, Legal);
1381 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1382 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1383 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1384 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1385 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1386 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1388 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1389 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1390 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1391 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1392 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1393 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1395 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1396 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1397 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1398 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1399 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1400 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1401 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1402 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1404 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1405 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1406 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1407 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1408 if (Subtarget->is64Bit()) {
1409 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1410 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1411 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1412 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1414 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1415 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1416 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1417 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1418 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1419 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1420 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1421 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1422 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1423 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1425 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1426 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1427 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1428 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1429 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1430 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1431 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1432 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1433 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1434 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1435 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1436 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1437 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1439 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1440 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1441 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1442 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1443 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1444 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1446 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1447 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1449 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1451 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1452 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1454 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1455 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1456 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1457 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1458 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1459 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1461 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1462 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1464 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1465 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1467 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1469 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1470 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1472 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1473 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1475 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1476 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1478 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1479 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1480 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1481 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1482 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1483 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1485 if (Subtarget->hasCDI()) {
1486 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1487 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1490 // Custom lower several nodes.
1491 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1492 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1493 MVT VT = (MVT::SimpleValueType)i;
1495 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496 // Extract subvector is special because the value type
1497 // (result) is 256/128-bit but the source is 512-bit wide.
1498 if (VT.is128BitVector() || VT.is256BitVector())
1499 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1501 if (VT.getVectorElementType() == MVT::i1)
1502 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1504 // Do not attempt to custom lower other non-512-bit vectors
1505 if (!VT.is512BitVector())
1508 if ( EltSize >= 32) {
1509 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1510 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1511 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1512 setOperationAction(ISD::VSELECT, VT, Legal);
1513 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1514 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1515 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1518 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1519 MVT VT = (MVT::SimpleValueType)i;
1521 // Do not attempt to promote non-256-bit vectors
1522 if (!VT.is512BitVector())
1525 setOperationAction(ISD::SELECT, VT, Promote);
1526 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1530 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1531 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1532 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1535 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1536 // of this type with custom code.
1537 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1538 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1539 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1543 // We want to custom lower some of our intrinsics.
1544 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1545 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1546 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1547 if (!Subtarget->is64Bit())
1548 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1550 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1551 // handle type legalization for these operations here.
1553 // FIXME: We really should do custom legalization for addition and
1554 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1555 // than generic legalization for 64-bit multiplication-with-overflow, though.
1556 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1557 // Add/Sub/Mul with overflow operations are custom lowered.
1559 setOperationAction(ISD::SADDO, VT, Custom);
1560 setOperationAction(ISD::UADDO, VT, Custom);
1561 setOperationAction(ISD::SSUBO, VT, Custom);
1562 setOperationAction(ISD::USUBO, VT, Custom);
1563 setOperationAction(ISD::SMULO, VT, Custom);
1564 setOperationAction(ISD::UMULO, VT, Custom);
1567 // There are no 8-bit 3-address imul/mul instructions
1568 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1569 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1571 if (!Subtarget->is64Bit()) {
1572 // These libcalls are not available in 32-bit.
1573 setLibcallName(RTLIB::SHL_I128, nullptr);
1574 setLibcallName(RTLIB::SRL_I128, nullptr);
1575 setLibcallName(RTLIB::SRA_I128, nullptr);
1578 // Combine sin / cos into one node or libcall if possible.
1579 if (Subtarget->hasSinCos()) {
1580 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1581 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1582 if (Subtarget->isTargetDarwin()) {
1583 // For MacOSX, we don't want to the normal expansion of a libcall to
1584 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1586 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1587 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1591 if (Subtarget->isTargetWin64()) {
1592 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1593 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1594 setOperationAction(ISD::SREM, MVT::i128, Custom);
1595 setOperationAction(ISD::UREM, MVT::i128, Custom);
1596 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1597 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1600 // We have target-specific dag combine patterns for the following nodes:
1601 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1602 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1603 setTargetDAGCombine(ISD::VSELECT);
1604 setTargetDAGCombine(ISD::SELECT);
1605 setTargetDAGCombine(ISD::SHL);
1606 setTargetDAGCombine(ISD::SRA);
1607 setTargetDAGCombine(ISD::SRL);
1608 setTargetDAGCombine(ISD::OR);
1609 setTargetDAGCombine(ISD::AND);
1610 setTargetDAGCombine(ISD::ADD);
1611 setTargetDAGCombine(ISD::FADD);
1612 setTargetDAGCombine(ISD::FSUB);
1613 setTargetDAGCombine(ISD::FMA);
1614 setTargetDAGCombine(ISD::SUB);
1615 setTargetDAGCombine(ISD::LOAD);
1616 setTargetDAGCombine(ISD::STORE);
1617 setTargetDAGCombine(ISD::ZERO_EXTEND);
1618 setTargetDAGCombine(ISD::ANY_EXTEND);
1619 setTargetDAGCombine(ISD::SIGN_EXTEND);
1620 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1621 setTargetDAGCombine(ISD::TRUNCATE);
1622 setTargetDAGCombine(ISD::SINT_TO_FP);
1623 setTargetDAGCombine(ISD::SETCC);
1624 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1625 setTargetDAGCombine(ISD::BUILD_VECTOR);
1626 if (Subtarget->is64Bit())
1627 setTargetDAGCombine(ISD::MUL);
1628 setTargetDAGCombine(ISD::XOR);
1630 computeRegisterProperties();
1632 // On Darwin, -Os means optimize for size without hurting performance,
1633 // do not reduce the limit.
1634 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1635 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1636 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1637 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1638 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1639 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640 setPrefLoopAlignment(4); // 2^4 bytes.
1642 // Predictable cmov don't hurt on atom because it's in-order.
1643 PredictableSelectIsExpensive = !Subtarget->isAtom();
1645 setPrefFunctionAlignment(4); // 2^4 bytes.
1648 // This has so far only been implemented for 64-bit MachO.
1649 bool X86TargetLowering::useLoadStackGuardNode() const {
1650 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1651 Subtarget->is64Bit();
1654 TargetLoweringBase::LegalizeTypeAction
1655 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1656 if (ExperimentalVectorWideningLegalization &&
1657 VT.getVectorNumElements() != 1 &&
1658 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1659 return TypeWidenVector;
1661 return TargetLoweringBase::getPreferredVectorAction(VT);
1664 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1666 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1668 if (Subtarget->hasAVX512())
1669 switch(VT.getVectorNumElements()) {
1670 case 8: return MVT::v8i1;
1671 case 16: return MVT::v16i1;
1674 return VT.changeVectorElementTypeToInteger();
1677 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1678 /// the desired ByVal argument alignment.
1679 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1682 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1683 if (VTy->getBitWidth() == 128)
1685 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1686 unsigned EltAlign = 0;
1687 getMaxByValAlign(ATy->getElementType(), EltAlign);
1688 if (EltAlign > MaxAlign)
1689 MaxAlign = EltAlign;
1690 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1691 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1692 unsigned EltAlign = 0;
1693 getMaxByValAlign(STy->getElementType(i), EltAlign);
1694 if (EltAlign > MaxAlign)
1695 MaxAlign = EltAlign;
1702 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1703 /// function arguments in the caller parameter area. For X86, aggregates
1704 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1705 /// are at 4-byte boundaries.
1706 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1707 if (Subtarget->is64Bit()) {
1708 // Max of 8 and alignment of type.
1709 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1716 if (Subtarget->hasSSE1())
1717 getMaxByValAlign(Ty, Align);
1721 /// getOptimalMemOpType - Returns the target specific optimal type for load
1722 /// and store operations as a result of memset, memcpy, and memmove
1723 /// lowering. If DstAlign is zero that means it's safe to destination
1724 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1725 /// means there isn't a need to check it against alignment requirement,
1726 /// probably because the source does not need to be loaded. If 'IsMemset' is
1727 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1728 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1729 /// source is constant so it does not need to be loaded.
1730 /// It returns EVT::Other if the type should be determined using generic
1731 /// target-independent logic.
1733 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1734 unsigned DstAlign, unsigned SrcAlign,
1735 bool IsMemset, bool ZeroMemset,
1737 MachineFunction &MF) const {
1738 const Function *F = MF.getFunction();
1739 if ((!IsMemset || ZeroMemset) &&
1740 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1741 Attribute::NoImplicitFloat)) {
1743 (Subtarget->isUnalignedMemAccessFast() ||
1744 ((DstAlign == 0 || DstAlign >= 16) &&
1745 (SrcAlign == 0 || SrcAlign >= 16)))) {
1747 if (Subtarget->hasInt256())
1749 if (Subtarget->hasFp256())
1752 if (Subtarget->hasSSE2())
1754 if (Subtarget->hasSSE1())
1756 } else if (!MemcpyStrSrc && Size >= 8 &&
1757 !Subtarget->is64Bit() &&
1758 Subtarget->hasSSE2()) {
1759 // Do not use f64 to lower memcpy if source is string constant. It's
1760 // better to use i32 to avoid the loads.
1764 if (Subtarget->is64Bit() && Size >= 8)
1769 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1771 return X86ScalarSSEf32;
1772 else if (VT == MVT::f64)
1773 return X86ScalarSSEf64;
1778 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1783 *Fast = Subtarget->isUnalignedMemAccessFast();
1787 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1788 /// current function. The returned value is a member of the
1789 /// MachineJumpTableInfo::JTEntryKind enum.
1790 unsigned X86TargetLowering::getJumpTableEncoding() const {
1791 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1793 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1794 Subtarget->isPICStyleGOT())
1795 return MachineJumpTableInfo::EK_Custom32;
1797 // Otherwise, use the normal jump table encoding heuristics.
1798 return TargetLowering::getJumpTableEncoding();
1802 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1803 const MachineBasicBlock *MBB,
1804 unsigned uid,MCContext &Ctx) const{
1805 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1806 Subtarget->isPICStyleGOT());
1807 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1809 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1810 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1813 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1815 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1816 SelectionDAG &DAG) const {
1817 if (!Subtarget->is64Bit())
1818 // This doesn't have SDLoc associated with it, but is not really the
1819 // same as a Register.
1820 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1824 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1825 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1827 const MCExpr *X86TargetLowering::
1828 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1829 MCContext &Ctx) const {
1830 // X86-64 uses RIP relative addressing based on the jump table label.
1831 if (Subtarget->isPICStyleRIPRel())
1832 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1834 // Otherwise, the reference is relative to the PIC base.
1835 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1838 // FIXME: Why this routine is here? Move to RegInfo!
1839 std::pair<const TargetRegisterClass*, uint8_t>
1840 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1841 const TargetRegisterClass *RRC = nullptr;
1843 switch (VT.SimpleTy) {
1845 return TargetLowering::findRepresentativeClass(VT);
1846 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1847 RRC = Subtarget->is64Bit() ?
1848 (const TargetRegisterClass*)&X86::GR64RegClass :
1849 (const TargetRegisterClass*)&X86::GR32RegClass;
1852 RRC = &X86::VR64RegClass;
1854 case MVT::f32: case MVT::f64:
1855 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1856 case MVT::v4f32: case MVT::v2f64:
1857 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1859 RRC = &X86::VR128RegClass;
1862 return std::make_pair(RRC, Cost);
1865 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1866 unsigned &Offset) const {
1867 if (!Subtarget->isTargetLinux())
1870 if (Subtarget->is64Bit()) {
1871 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1873 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1885 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1886 unsigned DestAS) const {
1887 assert(SrcAS != DestAS && "Expected different address spaces!");
1889 return SrcAS < 256 && DestAS < 256;
1892 //===----------------------------------------------------------------------===//
1893 // Return Value Calling Convention Implementation
1894 //===----------------------------------------------------------------------===//
1896 #include "X86GenCallingConv.inc"
1899 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1900 MachineFunction &MF, bool isVarArg,
1901 const SmallVectorImpl<ISD::OutputArg> &Outs,
1902 LLVMContext &Context) const {
1903 SmallVector<CCValAssign, 16> RVLocs;
1904 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1906 return CCInfo.CheckReturn(Outs, RetCC_X86);
1909 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1910 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1915 X86TargetLowering::LowerReturn(SDValue Chain,
1916 CallingConv::ID CallConv, bool isVarArg,
1917 const SmallVectorImpl<ISD::OutputArg> &Outs,
1918 const SmallVectorImpl<SDValue> &OutVals,
1919 SDLoc dl, SelectionDAG &DAG) const {
1920 MachineFunction &MF = DAG.getMachineFunction();
1921 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1923 SmallVector<CCValAssign, 16> RVLocs;
1924 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1925 RVLocs, *DAG.getContext());
1926 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1929 SmallVector<SDValue, 6> RetOps;
1930 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1931 // Operand #1 = Bytes To Pop
1932 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1935 // Copy the result values into the output registers.
1936 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1937 CCValAssign &VA = RVLocs[i];
1938 assert(VA.isRegLoc() && "Can only return in registers!");
1939 SDValue ValToCopy = OutVals[i];
1940 EVT ValVT = ValToCopy.getValueType();
1942 // Promote values to the appropriate types
1943 if (VA.getLocInfo() == CCValAssign::SExt)
1944 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1945 else if (VA.getLocInfo() == CCValAssign::ZExt)
1946 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947 else if (VA.getLocInfo() == CCValAssign::AExt)
1948 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1949 else if (VA.getLocInfo() == CCValAssign::BCvt)
1950 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1952 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1953 "Unexpected FP-extend for return value.");
1955 // If this is x86-64, and we disabled SSE, we can't return FP values,
1956 // or SSE or MMX vectors.
1957 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1958 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1959 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1960 report_fatal_error("SSE register return with SSE disabled");
1962 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1963 // llvm-gcc has never done it right and no one has noticed, so this
1964 // should be OK for now.
1965 if (ValVT == MVT::f64 &&
1966 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1967 report_fatal_error("SSE2 register return with SSE2 disabled");
1969 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1970 // the RET instruction and handled by the FP Stackifier.
1971 if (VA.getLocReg() == X86::FP0 ||
1972 VA.getLocReg() == X86::FP1) {
1973 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1974 // change the value to the FP stack register class.
1975 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1976 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1977 RetOps.push_back(ValToCopy);
1978 // Don't emit a copytoreg.
1982 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1983 // which is returned in RAX / RDX.
1984 if (Subtarget->is64Bit()) {
1985 if (ValVT == MVT::x86mmx) {
1986 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1987 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1988 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1990 // If we don't have SSE2 available, convert to v4f32 so the generated
1991 // register is legal.
1992 if (!Subtarget->hasSSE2())
1993 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1998 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1999 Flag = Chain.getValue(1);
2000 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2003 // The x86-64 ABIs require that for returning structs by value we copy
2004 // the sret argument into %rax/%eax (depending on ABI) for the return.
2005 // Win32 requires us to put the sret argument to %eax as well.
2006 // We saved the argument into a virtual register in the entry block,
2007 // so now we copy the value out and into %rax/%eax.
2008 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2009 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2010 MachineFunction &MF = DAG.getMachineFunction();
2011 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2012 unsigned Reg = FuncInfo->getSRetReturnReg();
2014 "SRetReturnReg should have been set in LowerFormalArguments().");
2015 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2018 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2019 X86::RAX : X86::EAX;
2020 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2021 Flag = Chain.getValue(1);
2023 // RAX/EAX now acts like a return value.
2024 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2027 RetOps[0] = Chain; // Update chain.
2029 // Add the flag if we have it.
2031 RetOps.push_back(Flag);
2033 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2036 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2037 if (N->getNumValues() != 1)
2039 if (!N->hasNUsesOfValue(1, 0))
2042 SDValue TCChain = Chain;
2043 SDNode *Copy = *N->use_begin();
2044 if (Copy->getOpcode() == ISD::CopyToReg) {
2045 // If the copy has a glue operand, we conservatively assume it isn't safe to
2046 // perform a tail call.
2047 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2049 TCChain = Copy->getOperand(0);
2050 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2053 bool HasRet = false;
2054 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2056 if (UI->getOpcode() != X86ISD::RET_FLAG)
2069 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2070 ISD::NodeType ExtendKind) const {
2072 // TODO: Is this also valid on 32-bit?
2073 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2074 ReturnMVT = MVT::i8;
2076 ReturnMVT = MVT::i32;
2078 MVT MinVT = getRegisterType(ReturnMVT);
2079 return VT.bitsLT(MinVT) ? MinVT : VT;
2082 /// LowerCallResult - Lower the result values of a call into the
2083 /// appropriate copies out of appropriate physical registers.
2086 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2087 CallingConv::ID CallConv, bool isVarArg,
2088 const SmallVectorImpl<ISD::InputArg> &Ins,
2089 SDLoc dl, SelectionDAG &DAG,
2090 SmallVectorImpl<SDValue> &InVals) const {
2092 // Assign locations to each value returned by this call.
2093 SmallVector<CCValAssign, 16> RVLocs;
2094 bool Is64Bit = Subtarget->is64Bit();
2095 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2096 DAG.getTarget(), RVLocs, *DAG.getContext());
2097 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2099 // Copy all of the result registers out of their specified physreg.
2100 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2101 CCValAssign &VA = RVLocs[i];
2102 EVT CopyVT = VA.getValVT();
2104 // If this is x86-64, and we disabled SSE, we can't return FP values
2105 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2106 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2107 report_fatal_error("SSE register return with SSE disabled");
2110 // If we prefer to use the value in xmm registers, copy it out as f80 and
2111 // use a truncate to move it from fp stack reg to xmm reg.
2112 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2113 isScalarFPTypeInSSEReg(VA.getValVT()))
2116 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2117 CopyVT, InFlag).getValue(1);
2118 SDValue Val = Chain.getValue(0);
2120 if (CopyVT != VA.getValVT())
2121 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2122 // This truncation won't change the value.
2123 DAG.getIntPtrConstant(1));
2125 InFlag = Chain.getValue(2);
2126 InVals.push_back(Val);
2132 //===----------------------------------------------------------------------===//
2133 // C & StdCall & Fast Calling Convention implementation
2134 //===----------------------------------------------------------------------===//
2135 // StdCall calling convention seems to be standard for many Windows' API
2136 // routines and around. It differs from C calling convention just a little:
2137 // callee should clean up the stack, not caller. Symbols should be also
2138 // decorated in some fancy way :) It doesn't support any vector arguments.
2139 // For info on fast calling convention see Fast Calling Convention (tail call)
2140 // implementation LowerX86_32FastCCCallTo.
2142 /// CallIsStructReturn - Determines whether a call uses struct return
2144 enum StructReturnType {
2149 static StructReturnType
2150 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2152 return NotStructReturn;
2154 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2155 if (!Flags.isSRet())
2156 return NotStructReturn;
2157 if (Flags.isInReg())
2158 return RegStructReturn;
2159 return StackStructReturn;
2162 /// ArgsAreStructReturn - Determines whether a function uses struct
2163 /// return semantics.
2164 static StructReturnType
2165 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2167 return NotStructReturn;
2169 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2170 if (!Flags.isSRet())
2171 return NotStructReturn;
2172 if (Flags.isInReg())
2173 return RegStructReturn;
2174 return StackStructReturn;
2177 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2178 /// by "Src" to address "Dst" with size and alignment information specified by
2179 /// the specific parameter attribute. The copy will be passed as a byval
2180 /// function parameter.
2182 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2183 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2185 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2187 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2188 /*isVolatile*/false, /*AlwaysInline=*/true,
2189 MachinePointerInfo(), MachinePointerInfo());
2192 /// IsTailCallConvention - Return true if the calling convention is one that
2193 /// supports tail call optimization.
2194 static bool IsTailCallConvention(CallingConv::ID CC) {
2195 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2196 CC == CallingConv::HiPE);
2199 /// \brief Return true if the calling convention is a C calling convention.
2200 static bool IsCCallConvention(CallingConv::ID CC) {
2201 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2202 CC == CallingConv::X86_64_SysV);
2205 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2206 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2210 CallingConv::ID CalleeCC = CS.getCallingConv();
2211 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2217 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2218 /// a tailcall target by changing its ABI.
2219 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2220 bool GuaranteedTailCallOpt) {
2221 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2225 X86TargetLowering::LowerMemArgument(SDValue Chain,
2226 CallingConv::ID CallConv,
2227 const SmallVectorImpl<ISD::InputArg> &Ins,
2228 SDLoc dl, SelectionDAG &DAG,
2229 const CCValAssign &VA,
2230 MachineFrameInfo *MFI,
2232 // Create the nodes corresponding to a load from this parameter slot.
2233 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2234 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2235 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2236 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2239 // If value is passed by pointer we have address passed instead of the value
2241 if (VA.getLocInfo() == CCValAssign::Indirect)
2242 ValVT = VA.getLocVT();
2244 ValVT = VA.getValVT();
2246 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2247 // changed with more analysis.
2248 // In case of tail call optimization mark all arguments mutable. Since they
2249 // could be overwritten by lowering of arguments in case of a tail call.
2250 if (Flags.isByVal()) {
2251 unsigned Bytes = Flags.getByValSize();
2252 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2253 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2254 return DAG.getFrameIndex(FI, getPointerTy());
2256 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2257 VA.getLocMemOffset(), isImmutable);
2258 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2259 return DAG.getLoad(ValVT, dl, Chain, FIN,
2260 MachinePointerInfo::getFixedStack(FI),
2261 false, false, false, 0);
2266 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2267 CallingConv::ID CallConv,
2269 const SmallVectorImpl<ISD::InputArg> &Ins,
2272 SmallVectorImpl<SDValue> &InVals)
2274 MachineFunction &MF = DAG.getMachineFunction();
2275 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2277 const Function* Fn = MF.getFunction();
2278 if (Fn->hasExternalLinkage() &&
2279 Subtarget->isTargetCygMing() &&
2280 Fn->getName() == "main")
2281 FuncInfo->setForceFramePointer(true);
2283 MachineFrameInfo *MFI = MF.getFrameInfo();
2284 bool Is64Bit = Subtarget->is64Bit();
2285 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2287 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2288 "Var args not supported with calling convention fastcc, ghc or hipe");
2290 // Assign locations to all of the incoming arguments.
2291 SmallVector<CCValAssign, 16> ArgLocs;
2292 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2293 ArgLocs, *DAG.getContext());
2295 // Allocate shadow area for Win64
2297 CCInfo.AllocateStack(32, 8);
2299 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2301 unsigned LastVal = ~0U;
2303 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2304 CCValAssign &VA = ArgLocs[i];
2305 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2307 assert(VA.getValNo() != LastVal &&
2308 "Don't support value assigned to multiple locs yet");
2310 LastVal = VA.getValNo();
2312 if (VA.isRegLoc()) {
2313 EVT RegVT = VA.getLocVT();
2314 const TargetRegisterClass *RC;
2315 if (RegVT == MVT::i32)
2316 RC = &X86::GR32RegClass;
2317 else if (Is64Bit && RegVT == MVT::i64)
2318 RC = &X86::GR64RegClass;
2319 else if (RegVT == MVT::f32)
2320 RC = &X86::FR32RegClass;
2321 else if (RegVT == MVT::f64)
2322 RC = &X86::FR64RegClass;
2323 else if (RegVT.is512BitVector())
2324 RC = &X86::VR512RegClass;
2325 else if (RegVT.is256BitVector())
2326 RC = &X86::VR256RegClass;
2327 else if (RegVT.is128BitVector())
2328 RC = &X86::VR128RegClass;
2329 else if (RegVT == MVT::x86mmx)
2330 RC = &X86::VR64RegClass;
2331 else if (RegVT == MVT::i1)
2332 RC = &X86::VK1RegClass;
2333 else if (RegVT == MVT::v8i1)
2334 RC = &X86::VK8RegClass;
2335 else if (RegVT == MVT::v16i1)
2336 RC = &X86::VK16RegClass;
2337 else if (RegVT == MVT::v32i1)
2338 RC = &X86::VK32RegClass;
2339 else if (RegVT == MVT::v64i1)
2340 RC = &X86::VK64RegClass;
2342 llvm_unreachable("Unknown argument type!");
2344 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2345 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2347 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2348 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2350 if (VA.getLocInfo() == CCValAssign::SExt)
2351 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2352 DAG.getValueType(VA.getValVT()));
2353 else if (VA.getLocInfo() == CCValAssign::ZExt)
2354 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2355 DAG.getValueType(VA.getValVT()));
2356 else if (VA.getLocInfo() == CCValAssign::BCvt)
2357 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2359 if (VA.isExtInLoc()) {
2360 // Handle MMX values passed in XMM regs.
2361 if (RegVT.isVector())
2362 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2364 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2367 assert(VA.isMemLoc());
2368 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2371 // If value is passed via pointer - do a load.
2372 if (VA.getLocInfo() == CCValAssign::Indirect)
2373 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2374 MachinePointerInfo(), false, false, false, 0);
2376 InVals.push_back(ArgValue);
2379 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2380 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2381 // The x86-64 ABIs require that for returning structs by value we copy
2382 // the sret argument into %rax/%eax (depending on ABI) for the return.
2383 // Win32 requires us to put the sret argument to %eax as well.
2384 // Save the argument into a virtual register so that we can access it
2385 // from the return points.
2386 if (Ins[i].Flags.isSRet()) {
2387 unsigned Reg = FuncInfo->getSRetReturnReg();
2389 MVT PtrTy = getPointerTy();
2390 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2391 FuncInfo->setSRetReturnReg(Reg);
2393 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2394 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2400 unsigned StackSize = CCInfo.getNextStackOffset();
2401 // Align stack specially for tail calls.
2402 if (FuncIsMadeTailCallSafe(CallConv,
2403 MF.getTarget().Options.GuaranteedTailCallOpt))
2404 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2406 // If the function takes variable number of arguments, make a frame index for
2407 // the start of the first vararg value... for expansion of llvm.va_start.
2409 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2410 CallConv != CallingConv::X86_ThisCall)) {
2411 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2414 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2416 // FIXME: We should really autogenerate these arrays
2417 static const MCPhysReg GPR64ArgRegsWin64[] = {
2418 X86::RCX, X86::RDX, X86::R8, X86::R9
2420 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2421 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2423 static const MCPhysReg XMMArgRegs64Bit[] = {
2424 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2425 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2427 const MCPhysReg *GPR64ArgRegs;
2428 unsigned NumXMMRegs = 0;
2431 // The XMM registers which might contain var arg parameters are shadowed
2432 // in their paired GPR. So we only need to save the GPR to their home
2434 TotalNumIntRegs = 4;
2435 GPR64ArgRegs = GPR64ArgRegsWin64;
2437 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2438 GPR64ArgRegs = GPR64ArgRegs64Bit;
2440 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2443 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2446 bool NoImplicitFloatOps = Fn->getAttributes().
2447 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2448 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2449 "SSE register cannot be used when SSE is disabled!");
2450 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2451 NoImplicitFloatOps) &&
2452 "SSE register cannot be used when SSE is disabled!");
2453 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2454 !Subtarget->hasSSE1())
2455 // Kernel mode asks for SSE to be disabled, so don't push them
2457 TotalNumXMMRegs = 0;
2460 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2461 // Get to the caller-allocated home save location. Add 8 to account
2462 // for the return address.
2463 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2464 FuncInfo->setRegSaveFrameIndex(
2465 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2466 // Fixup to set vararg frame on shadow area (4 x i64).
2468 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2470 // For X86-64, if there are vararg parameters that are passed via
2471 // registers, then we must store them to their spots on the stack so
2472 // they may be loaded by deferencing the result of va_next.
2473 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2474 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2475 FuncInfo->setRegSaveFrameIndex(
2476 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2480 // Store the integer parameter registers.
2481 SmallVector<SDValue, 8> MemOps;
2482 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2484 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2485 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2486 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2487 DAG.getIntPtrConstant(Offset));
2488 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2489 &X86::GR64RegClass);
2490 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2492 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2493 MachinePointerInfo::getFixedStack(
2494 FuncInfo->getRegSaveFrameIndex(), Offset),
2496 MemOps.push_back(Store);
2500 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2501 // Now store the XMM (fp + vector) parameter registers.
2502 SmallVector<SDValue, 11> SaveXMMOps;
2503 SaveXMMOps.push_back(Chain);
2505 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2506 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2507 SaveXMMOps.push_back(ALVal);
2509 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2510 FuncInfo->getRegSaveFrameIndex()));
2511 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2512 FuncInfo->getVarArgsFPOffset()));
2514 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2515 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2516 &X86::VR128RegClass);
2517 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2518 SaveXMMOps.push_back(Val);
2520 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2521 MVT::Other, SaveXMMOps));
2524 if (!MemOps.empty())
2525 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2529 // Some CCs need callee pop.
2530 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2531 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2532 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2534 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2535 // If this is an sret function, the return should pop the hidden pointer.
2536 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2537 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2538 argsAreStructReturn(Ins) == StackStructReturn)
2539 FuncInfo->setBytesToPopOnReturn(4);
2543 // RegSaveFrameIndex is X86-64 only.
2544 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2545 if (CallConv == CallingConv::X86_FastCall ||
2546 CallConv == CallingConv::X86_ThisCall)
2547 // fastcc functions can't have varargs.
2548 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2551 FuncInfo->setArgumentStackSize(StackSize);
2557 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2558 SDValue StackPtr, SDValue Arg,
2559 SDLoc dl, SelectionDAG &DAG,
2560 const CCValAssign &VA,
2561 ISD::ArgFlagsTy Flags) const {
2562 unsigned LocMemOffset = VA.getLocMemOffset();
2563 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2564 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2565 if (Flags.isByVal())
2566 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2568 return DAG.getStore(Chain, dl, Arg, PtrOff,
2569 MachinePointerInfo::getStack(LocMemOffset),
2573 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2574 /// optimization is performed and it is required.
2576 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2577 SDValue &OutRetAddr, SDValue Chain,
2578 bool IsTailCall, bool Is64Bit,
2579 int FPDiff, SDLoc dl) const {
2580 // Adjust the Return address stack slot.
2581 EVT VT = getPointerTy();
2582 OutRetAddr = getReturnAddressFrameIndex(DAG);
2584 // Load the "old" Return address.
2585 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2586 false, false, false, 0);
2587 return SDValue(OutRetAddr.getNode(), 1);
2590 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2591 /// optimization is performed and it is required (FPDiff!=0).
2592 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2593 SDValue Chain, SDValue RetAddrFrIdx,
2594 EVT PtrVT, unsigned SlotSize,
2595 int FPDiff, SDLoc dl) {
2596 // Store the return address to the appropriate stack slot.
2597 if (!FPDiff) return Chain;
2598 // Calculate the new stack slot for the return address.
2599 int NewReturnAddrFI =
2600 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2602 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2603 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2604 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2610 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2611 SmallVectorImpl<SDValue> &InVals) const {
2612 SelectionDAG &DAG = CLI.DAG;
2614 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2615 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2616 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2617 SDValue Chain = CLI.Chain;
2618 SDValue Callee = CLI.Callee;
2619 CallingConv::ID CallConv = CLI.CallConv;
2620 bool &isTailCall = CLI.IsTailCall;
2621 bool isVarArg = CLI.IsVarArg;
2623 MachineFunction &MF = DAG.getMachineFunction();
2624 bool Is64Bit = Subtarget->is64Bit();
2625 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2626 StructReturnType SR = callIsStructReturn(Outs);
2627 bool IsSibcall = false;
2629 if (MF.getTarget().Options.DisableTailCalls)
2632 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2634 // Force this to be a tail call. The verifier rules are enough to ensure
2635 // that we can lower this successfully without moving the return address
2638 } else if (isTailCall) {
2639 // Check if it's really possible to do a tail call.
2640 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2641 isVarArg, SR != NotStructReturn,
2642 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2643 Outs, OutVals, Ins, DAG);
2645 // Sibcalls are automatically detected tailcalls which do not require
2647 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2654 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2655 "Var args not supported with calling convention fastcc, ghc or hipe");
2657 // Analyze operands of the call, assigning locations to each operand.
2658 SmallVector<CCValAssign, 16> ArgLocs;
2659 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2660 ArgLocs, *DAG.getContext());
2662 // Allocate shadow area for Win64
2664 CCInfo.AllocateStack(32, 8);
2666 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2668 // Get a count of how many bytes are to be pushed on the stack.
2669 unsigned NumBytes = CCInfo.getNextStackOffset();
2671 // This is a sibcall. The memory operands are available in caller's
2672 // own caller's stack.
2674 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2675 IsTailCallConvention(CallConv))
2676 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2679 if (isTailCall && !IsSibcall && !IsMustTail) {
2680 // Lower arguments at fp - stackoffset + fpdiff.
2681 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2682 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2684 FPDiff = NumBytesCallerPushed - NumBytes;
2686 // Set the delta of movement of the returnaddr stackslot.
2687 // But only set if delta is greater than previous delta.
2688 if (FPDiff < X86Info->getTCReturnAddrDelta())
2689 X86Info->setTCReturnAddrDelta(FPDiff);
2692 unsigned NumBytesToPush = NumBytes;
2693 unsigned NumBytesToPop = NumBytes;
2695 // If we have an inalloca argument, all stack space has already been allocated
2696 // for us and be right at the top of the stack. We don't support multiple
2697 // arguments passed in memory when using inalloca.
2698 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2700 if (!ArgLocs.back().isMemLoc())
2701 report_fatal_error("cannot use inalloca attribute on a register "
2703 if (ArgLocs.back().getLocMemOffset() != 0)
2704 report_fatal_error("any parameter with the inalloca attribute must be "
2705 "the only memory argument");
2709 Chain = DAG.getCALLSEQ_START(
2710 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2712 SDValue RetAddrFrIdx;
2713 // Load return address for tail calls.
2714 if (isTailCall && FPDiff)
2715 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2716 Is64Bit, FPDiff, dl);
2718 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2719 SmallVector<SDValue, 8> MemOpChains;
2722 // Walk the register/memloc assignments, inserting copies/loads. In the case
2723 // of tail call optimization arguments are handle later.
2724 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2725 DAG.getSubtarget().getRegisterInfo());
2726 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2727 // Skip inalloca arguments, they have already been written.
2728 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2729 if (Flags.isInAlloca())
2732 CCValAssign &VA = ArgLocs[i];
2733 EVT RegVT = VA.getLocVT();
2734 SDValue Arg = OutVals[i];
2735 bool isByVal = Flags.isByVal();
2737 // Promote the value if needed.
2738 switch (VA.getLocInfo()) {
2739 default: llvm_unreachable("Unknown loc info!");
2740 case CCValAssign::Full: break;
2741 case CCValAssign::SExt:
2742 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2744 case CCValAssign::ZExt:
2745 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2747 case CCValAssign::AExt:
2748 if (RegVT.is128BitVector()) {
2749 // Special case: passing MMX values in XMM registers.
2750 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2751 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2752 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2754 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2756 case CCValAssign::BCvt:
2757 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2759 case CCValAssign::Indirect: {
2760 // Store the argument.
2761 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2762 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2763 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2764 MachinePointerInfo::getFixedStack(FI),
2771 if (VA.isRegLoc()) {
2772 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2773 if (isVarArg && IsWin64) {
2774 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2775 // shadow reg if callee is a varargs function.
2776 unsigned ShadowReg = 0;
2777 switch (VA.getLocReg()) {
2778 case X86::XMM0: ShadowReg = X86::RCX; break;
2779 case X86::XMM1: ShadowReg = X86::RDX; break;
2780 case X86::XMM2: ShadowReg = X86::R8; break;
2781 case X86::XMM3: ShadowReg = X86::R9; break;
2784 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2786 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2787 assert(VA.isMemLoc());
2788 if (!StackPtr.getNode())
2789 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2791 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2792 dl, DAG, VA, Flags));
2796 if (!MemOpChains.empty())
2797 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2799 if (Subtarget->isPICStyleGOT()) {
2800 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2803 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2804 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2806 // If we are tail calling and generating PIC/GOT style code load the
2807 // address of the callee into ECX. The value in ecx is used as target of
2808 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2809 // for tail calls on PIC/GOT architectures. Normally we would just put the
2810 // address of GOT into ebx and then call target@PLT. But for tail calls
2811 // ebx would be restored (since ebx is callee saved) before jumping to the
2814 // Note: The actual moving to ECX is done further down.
2815 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2816 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2817 !G->getGlobal()->hasProtectedVisibility())
2818 Callee = LowerGlobalAddress(Callee, DAG);
2819 else if (isa<ExternalSymbolSDNode>(Callee))
2820 Callee = LowerExternalSymbol(Callee, DAG);
2824 if (Is64Bit && isVarArg && !IsWin64) {
2825 // From AMD64 ABI document:
2826 // For calls that may call functions that use varargs or stdargs
2827 // (prototype-less calls or calls to functions containing ellipsis (...) in
2828 // the declaration) %al is used as hidden argument to specify the number
2829 // of SSE registers used. The contents of %al do not need to match exactly
2830 // the number of registers, but must be an ubound on the number of SSE
2831 // registers used and is in the range 0 - 8 inclusive.
2833 // Count the number of XMM registers allocated.
2834 static const MCPhysReg XMMArgRegs[] = {
2835 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2836 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2838 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2839 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2840 && "SSE registers cannot be used when SSE is disabled");
2842 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2843 DAG.getConstant(NumXMMRegs, MVT::i8)));
2846 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2847 // don't need this because the eligibility check rejects calls that require
2848 // shuffling arguments passed in memory.
2849 if (!IsSibcall && isTailCall) {
2850 // Force all the incoming stack arguments to be loaded from the stack
2851 // before any new outgoing arguments are stored to the stack, because the
2852 // outgoing stack slots may alias the incoming argument stack slots, and
2853 // the alias isn't otherwise explicit. This is slightly more conservative
2854 // than necessary, because it means that each store effectively depends
2855 // on every argument instead of just those arguments it would clobber.
2856 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2858 SmallVector<SDValue, 8> MemOpChains2;
2861 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2862 CCValAssign &VA = ArgLocs[i];
2865 assert(VA.isMemLoc());
2866 SDValue Arg = OutVals[i];
2867 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2868 // Skip inalloca arguments. They don't require any work.
2869 if (Flags.isInAlloca())
2871 // Create frame index.
2872 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2873 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2874 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2875 FIN = DAG.getFrameIndex(FI, getPointerTy());
2877 if (Flags.isByVal()) {
2878 // Copy relative to framepointer.
2879 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2880 if (!StackPtr.getNode())
2881 StackPtr = DAG.getCopyFromReg(Chain, dl,
2882 RegInfo->getStackRegister(),
2884 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2886 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2890 // Store relative to framepointer.
2891 MemOpChains2.push_back(
2892 DAG.getStore(ArgChain, dl, Arg, FIN,
2893 MachinePointerInfo::getFixedStack(FI),
2898 if (!MemOpChains2.empty())
2899 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2901 // Store the return address to the appropriate stack slot.
2902 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2903 getPointerTy(), RegInfo->getSlotSize(),
2907 // Build a sequence of copy-to-reg nodes chained together with token chain
2908 // and flag operands which copy the outgoing args into registers.
2910 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2911 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2912 RegsToPass[i].second, InFlag);
2913 InFlag = Chain.getValue(1);
2916 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2917 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2918 // In the 64-bit large code model, we have to make all calls
2919 // through a register, since the call instruction's 32-bit
2920 // pc-relative offset may not be large enough to hold the whole
2922 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2923 // If the callee is a GlobalAddress node (quite common, every direct call
2924 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2927 // We should use extra load for direct calls to dllimported functions in
2929 const GlobalValue *GV = G->getGlobal();
2930 if (!GV->hasDLLImportStorageClass()) {
2931 unsigned char OpFlags = 0;
2932 bool ExtraLoad = false;
2933 unsigned WrapperKind = ISD::DELETED_NODE;
2935 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2936 // external symbols most go through the PLT in PIC mode. If the symbol
2937 // has hidden or protected visibility, or if it is static or local, then
2938 // we don't need to use the PLT - we can directly call it.
2939 if (Subtarget->isTargetELF() &&
2940 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2941 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2942 OpFlags = X86II::MO_PLT;
2943 } else if (Subtarget->isPICStyleStubAny() &&
2944 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2945 (!Subtarget->getTargetTriple().isMacOSX() ||
2946 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2947 // PC-relative references to external symbols should go through $stub,
2948 // unless we're building with the leopard linker or later, which
2949 // automatically synthesizes these stubs.
2950 OpFlags = X86II::MO_DARWIN_STUB;
2951 } else if (Subtarget->isPICStyleRIPRel() &&
2952 isa<Function>(GV) &&
2953 cast<Function>(GV)->getAttributes().
2954 hasAttribute(AttributeSet::FunctionIndex,
2955 Attribute::NonLazyBind)) {
2956 // If the function is marked as non-lazy, generate an indirect call
2957 // which loads from the GOT directly. This avoids runtime overhead
2958 // at the cost of eager binding (and one extra byte of encoding).
2959 OpFlags = X86II::MO_GOTPCREL;
2960 WrapperKind = X86ISD::WrapperRIP;
2964 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2965 G->getOffset(), OpFlags);
2967 // Add a wrapper if needed.
2968 if (WrapperKind != ISD::DELETED_NODE)
2969 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2970 // Add extra indirection if needed.
2972 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2973 MachinePointerInfo::getGOT(),
2974 false, false, false, 0);
2976 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2977 unsigned char OpFlags = 0;
2979 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2980 // external symbols should go through the PLT.
2981 if (Subtarget->isTargetELF() &&
2982 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2983 OpFlags = X86II::MO_PLT;
2984 } else if (Subtarget->isPICStyleStubAny() &&
2985 (!Subtarget->getTargetTriple().isMacOSX() ||
2986 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2987 // PC-relative references to external symbols should go through $stub,
2988 // unless we're building with the leopard linker or later, which
2989 // automatically synthesizes these stubs.
2990 OpFlags = X86II::MO_DARWIN_STUB;
2993 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2997 // Returns a chain & a flag for retval copy to use.
2998 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2999 SmallVector<SDValue, 8> Ops;
3001 if (!IsSibcall && isTailCall) {
3002 Chain = DAG.getCALLSEQ_END(Chain,
3003 DAG.getIntPtrConstant(NumBytesToPop, true),
3004 DAG.getIntPtrConstant(0, true), InFlag, dl);
3005 InFlag = Chain.getValue(1);
3008 Ops.push_back(Chain);
3009 Ops.push_back(Callee);
3012 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3014 // Add argument registers to the end of the list so that they are known live
3016 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3017 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3018 RegsToPass[i].second.getValueType()));
3020 // Add a register mask operand representing the call-preserved registers.
3021 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3022 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3023 assert(Mask && "Missing call preserved mask for calling convention");
3024 Ops.push_back(DAG.getRegisterMask(Mask));
3026 if (InFlag.getNode())
3027 Ops.push_back(InFlag);
3031 //// If this is the first return lowered for this function, add the regs
3032 //// to the liveout set for the function.
3033 // This isn't right, although it's probably harmless on x86; liveouts
3034 // should be computed from returns not tail calls. Consider a void
3035 // function making a tail call to a function returning int.
3036 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3039 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3040 InFlag = Chain.getValue(1);
3042 // Create the CALLSEQ_END node.
3043 unsigned NumBytesForCalleeToPop;
3044 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3045 DAG.getTarget().Options.GuaranteedTailCallOpt))
3046 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3047 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3048 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3049 SR == StackStructReturn)
3050 // If this is a call to a struct-return function, the callee
3051 // pops the hidden struct pointer, so we have to push it back.
3052 // This is common for Darwin/X86, Linux & Mingw32 targets.
3053 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3054 NumBytesForCalleeToPop = 4;
3056 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3058 // Returns a flag for retval copy to use.
3060 Chain = DAG.getCALLSEQ_END(Chain,
3061 DAG.getIntPtrConstant(NumBytesToPop, true),
3062 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3065 InFlag = Chain.getValue(1);
3068 // Handle result values, copying them out of physregs into vregs that we
3070 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3071 Ins, dl, DAG, InVals);
3074 //===----------------------------------------------------------------------===//
3075 // Fast Calling Convention (tail call) implementation
3076 //===----------------------------------------------------------------------===//
3078 // Like std call, callee cleans arguments, convention except that ECX is
3079 // reserved for storing the tail called function address. Only 2 registers are
3080 // free for argument passing (inreg). Tail call optimization is performed
3082 // * tailcallopt is enabled
3083 // * caller/callee are fastcc
3084 // On X86_64 architecture with GOT-style position independent code only local
3085 // (within module) calls are supported at the moment.
3086 // To keep the stack aligned according to platform abi the function
3087 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3088 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3089 // If a tail called function callee has more arguments than the caller the
3090 // caller needs to make sure that there is room to move the RETADDR to. This is
3091 // achieved by reserving an area the size of the argument delta right after the
3092 // original RETADDR, but before the saved framepointer or the spilled registers
3093 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3105 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3106 /// for a 16 byte align requirement.
3108 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3109 SelectionDAG& DAG) const {
3110 MachineFunction &MF = DAG.getMachineFunction();
3111 const TargetMachine &TM = MF.getTarget();
3112 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3113 TM.getSubtargetImpl()->getRegisterInfo());
3114 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3115 unsigned StackAlignment = TFI.getStackAlignment();
3116 uint64_t AlignMask = StackAlignment - 1;
3117 int64_t Offset = StackSize;
3118 unsigned SlotSize = RegInfo->getSlotSize();
3119 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3120 // Number smaller than 12 so just add the difference.
3121 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3123 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3124 Offset = ((~AlignMask) & Offset) + StackAlignment +
3125 (StackAlignment-SlotSize);
3130 /// MatchingStackOffset - Return true if the given stack call argument is
3131 /// already available in the same position (relatively) of the caller's
3132 /// incoming argument stack.
3134 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3135 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3136 const X86InstrInfo *TII) {
3137 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3139 if (Arg.getOpcode() == ISD::CopyFromReg) {
3140 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3141 if (!TargetRegisterInfo::isVirtualRegister(VR))
3143 MachineInstr *Def = MRI->getVRegDef(VR);
3146 if (!Flags.isByVal()) {
3147 if (!TII->isLoadFromStackSlot(Def, FI))
3150 unsigned Opcode = Def->getOpcode();
3151 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3152 Def->getOperand(1).isFI()) {
3153 FI = Def->getOperand(1).getIndex();
3154 Bytes = Flags.getByValSize();
3158 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3159 if (Flags.isByVal())
3160 // ByVal argument is passed in as a pointer but it's now being
3161 // dereferenced. e.g.
3162 // define @foo(%struct.X* %A) {
3163 // tail call @bar(%struct.X* byval %A)
3166 SDValue Ptr = Ld->getBasePtr();
3167 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3170 FI = FINode->getIndex();
3171 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3172 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3173 FI = FINode->getIndex();
3174 Bytes = Flags.getByValSize();
3178 assert(FI != INT_MAX);
3179 if (!MFI->isFixedObjectIndex(FI))
3181 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3184 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3185 /// for tail call optimization. Targets which want to do tail call
3186 /// optimization should implement this function.
3188 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3189 CallingConv::ID CalleeCC,
3191 bool isCalleeStructRet,
3192 bool isCallerStructRet,
3194 const SmallVectorImpl<ISD::OutputArg> &Outs,
3195 const SmallVectorImpl<SDValue> &OutVals,
3196 const SmallVectorImpl<ISD::InputArg> &Ins,
3197 SelectionDAG &DAG) const {
3198 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3201 // If -tailcallopt is specified, make fastcc functions tail-callable.
3202 const MachineFunction &MF = DAG.getMachineFunction();
3203 const Function *CallerF = MF.getFunction();
3205 // If the function return type is x86_fp80 and the callee return type is not,
3206 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3207 // perform a tailcall optimization here.
3208 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3211 CallingConv::ID CallerCC = CallerF->getCallingConv();
3212 bool CCMatch = CallerCC == CalleeCC;
3213 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3214 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3216 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3217 if (IsTailCallConvention(CalleeCC) && CCMatch)
3222 // Look for obvious safe cases to perform tail call optimization that do not
3223 // require ABI changes. This is what gcc calls sibcall.
3225 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3226 // emit a special epilogue.
3227 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3228 DAG.getSubtarget().getRegisterInfo());
3229 if (RegInfo->needsStackRealignment(MF))
3232 // Also avoid sibcall optimization if either caller or callee uses struct
3233 // return semantics.
3234 if (isCalleeStructRet || isCallerStructRet)
3237 // An stdcall/thiscall caller is expected to clean up its arguments; the
3238 // callee isn't going to do that.
3239 // FIXME: this is more restrictive than needed. We could produce a tailcall
3240 // when the stack adjustment matches. For example, with a thiscall that takes
3241 // only one argument.
3242 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3243 CallerCC == CallingConv::X86_ThisCall))
3246 // Do not sibcall optimize vararg calls unless all arguments are passed via
3248 if (isVarArg && !Outs.empty()) {
3250 // Optimizing for varargs on Win64 is unlikely to be safe without
3251 // additional testing.
3252 if (IsCalleeWin64 || IsCallerWin64)
3255 SmallVector<CCValAssign, 16> ArgLocs;
3256 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3257 DAG.getTarget(), ArgLocs, *DAG.getContext());
3259 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3260 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3261 if (!ArgLocs[i].isRegLoc())
3265 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3266 // stack. Therefore, if it's not used by the call it is not safe to optimize
3267 // this into a sibcall.
3268 bool Unused = false;
3269 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3276 SmallVector<CCValAssign, 16> RVLocs;
3277 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3278 DAG.getTarget(), RVLocs, *DAG.getContext());
3279 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3280 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3281 CCValAssign &VA = RVLocs[i];
3282 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3287 // If the calling conventions do not match, then we'd better make sure the
3288 // results are returned in the same way as what the caller expects.
3290 SmallVector<CCValAssign, 16> RVLocs1;
3291 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3292 DAG.getTarget(), RVLocs1, *DAG.getContext());
3293 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3295 SmallVector<CCValAssign, 16> RVLocs2;
3296 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3297 DAG.getTarget(), RVLocs2, *DAG.getContext());
3298 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3300 if (RVLocs1.size() != RVLocs2.size())
3302 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3303 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3305 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3307 if (RVLocs1[i].isRegLoc()) {
3308 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3311 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3317 // If the callee takes no arguments then go on to check the results of the
3319 if (!Outs.empty()) {
3320 // Check if stack adjustment is needed. For now, do not do this if any
3321 // argument is passed on the stack.
3322 SmallVector<CCValAssign, 16> ArgLocs;
3323 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3324 DAG.getTarget(), ArgLocs, *DAG.getContext());
3326 // Allocate shadow area for Win64
3328 CCInfo.AllocateStack(32, 8);
3330 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3331 if (CCInfo.getNextStackOffset()) {
3332 MachineFunction &MF = DAG.getMachineFunction();
3333 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3336 // Check if the arguments are already laid out in the right way as
3337 // the caller's fixed stack objects.
3338 MachineFrameInfo *MFI = MF.getFrameInfo();
3339 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3340 const X86InstrInfo *TII =
3341 static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3342 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3343 CCValAssign &VA = ArgLocs[i];
3344 SDValue Arg = OutVals[i];
3345 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3346 if (VA.getLocInfo() == CCValAssign::Indirect)
3348 if (!VA.isRegLoc()) {
3349 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3356 // If the tailcall address may be in a register, then make sure it's
3357 // possible to register allocate for it. In 32-bit, the call address can
3358 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3359 // callee-saved registers are restored. These happen to be the same
3360 // registers used to pass 'inreg' arguments so watch out for those.
3361 if (!Subtarget->is64Bit() &&
3362 ((!isa<GlobalAddressSDNode>(Callee) &&
3363 !isa<ExternalSymbolSDNode>(Callee)) ||
3364 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3365 unsigned NumInRegs = 0;
3366 // In PIC we need an extra register to formulate the address computation
3368 unsigned MaxInRegs =
3369 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3371 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3372 CCValAssign &VA = ArgLocs[i];
3375 unsigned Reg = VA.getLocReg();
3378 case X86::EAX: case X86::EDX: case X86::ECX:
3379 if (++NumInRegs == MaxInRegs)
3391 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3392 const TargetLibraryInfo *libInfo) const {
3393 return X86::createFastISel(funcInfo, libInfo);
3396 //===----------------------------------------------------------------------===//
3397 // Other Lowering Hooks
3398 //===----------------------------------------------------------------------===//
3400 static bool MayFoldLoad(SDValue Op) {
3401 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3404 static bool MayFoldIntoStore(SDValue Op) {
3405 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3408 static bool isTargetShuffle(unsigned Opcode) {
3410 default: return false;
3411 case X86ISD::PSHUFB:
3412 case X86ISD::PSHUFD:
3413 case X86ISD::PSHUFHW:
3414 case X86ISD::PSHUFLW:
3416 case X86ISD::PALIGNR:
3417 case X86ISD::MOVLHPS:
3418 case X86ISD::MOVLHPD:
3419 case X86ISD::MOVHLPS:
3420 case X86ISD::MOVLPS:
3421 case X86ISD::MOVLPD:
3422 case X86ISD::MOVSHDUP:
3423 case X86ISD::MOVSLDUP:
3424 case X86ISD::MOVDDUP:
3427 case X86ISD::UNPCKL:
3428 case X86ISD::UNPCKH:
3429 case X86ISD::VPERMILP:
3430 case X86ISD::VPERM2X128:
3431 case X86ISD::VPERMI:
3436 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3437 SDValue V1, SelectionDAG &DAG) {
3439 default: llvm_unreachable("Unknown x86 shuffle node");
3440 case X86ISD::MOVSHDUP:
3441 case X86ISD::MOVSLDUP:
3442 case X86ISD::MOVDDUP:
3443 return DAG.getNode(Opc, dl, VT, V1);
3447 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3448 SDValue V1, unsigned TargetMask,
3449 SelectionDAG &DAG) {
3451 default: llvm_unreachable("Unknown x86 shuffle node");
3452 case X86ISD::PSHUFD:
3453 case X86ISD::PSHUFHW:
3454 case X86ISD::PSHUFLW:
3455 case X86ISD::VPERMILP:
3456 case X86ISD::VPERMI:
3457 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3461 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3462 SDValue V1, SDValue V2, unsigned TargetMask,
3463 SelectionDAG &DAG) {
3465 default: llvm_unreachable("Unknown x86 shuffle node");
3466 case X86ISD::PALIGNR:
3467 case X86ISD::VALIGN:
3469 case X86ISD::VPERM2X128:
3470 return DAG.getNode(Opc, dl, VT, V1, V2,
3471 DAG.getConstant(TargetMask, MVT::i8));
3475 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3476 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3478 default: llvm_unreachable("Unknown x86 shuffle node");
3479 case X86ISD::MOVLHPS:
3480 case X86ISD::MOVLHPD:
3481 case X86ISD::MOVHLPS:
3482 case X86ISD::MOVLPS:
3483 case X86ISD::MOVLPD:
3486 case X86ISD::UNPCKL:
3487 case X86ISD::UNPCKH:
3488 return DAG.getNode(Opc, dl, VT, V1, V2);
3492 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3493 MachineFunction &MF = DAG.getMachineFunction();
3494 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3495 DAG.getSubtarget().getRegisterInfo());
3496 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3497 int ReturnAddrIndex = FuncInfo->getRAIndex();
3499 if (ReturnAddrIndex == 0) {
3500 // Set up a frame object for the return address.
3501 unsigned SlotSize = RegInfo->getSlotSize();
3502 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3505 FuncInfo->setRAIndex(ReturnAddrIndex);
3508 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3511 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3512 bool hasSymbolicDisplacement) {
3513 // Offset should fit into 32 bit immediate field.
3514 if (!isInt<32>(Offset))
3517 // If we don't have a symbolic displacement - we don't have any extra
3519 if (!hasSymbolicDisplacement)
3522 // FIXME: Some tweaks might be needed for medium code model.
3523 if (M != CodeModel::Small && M != CodeModel::Kernel)
3526 // For small code model we assume that latest object is 16MB before end of 31
3527 // bits boundary. We may also accept pretty large negative constants knowing
3528 // that all objects are in the positive half of address space.
3529 if (M == CodeModel::Small && Offset < 16*1024*1024)
3532 // For kernel code model we know that all object resist in the negative half
3533 // of 32bits address space. We may not accept negative offsets, since they may
3534 // be just off and we may accept pretty large positive ones.
3535 if (M == CodeModel::Kernel && Offset > 0)
3541 /// isCalleePop - Determines whether the callee is required to pop its
3542 /// own arguments. Callee pop is necessary to support tail calls.
3543 bool X86::isCalleePop(CallingConv::ID CallingConv,
3544 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3548 switch (CallingConv) {
3551 case CallingConv::X86_StdCall:
3553 case CallingConv::X86_FastCall:
3555 case CallingConv::X86_ThisCall:
3557 case CallingConv::Fast:
3559 case CallingConv::GHC:
3561 case CallingConv::HiPE:
3566 /// \brief Return true if the condition is an unsigned comparison operation.
3567 static bool isX86CCUnsigned(unsigned X86CC) {
3569 default: llvm_unreachable("Invalid integer condition!");
3570 case X86::COND_E: return true;
3571 case X86::COND_G: return false;
3572 case X86::COND_GE: return false;
3573 case X86::COND_L: return false;
3574 case X86::COND_LE: return false;
3575 case X86::COND_NE: return true;
3576 case X86::COND_B: return true;
3577 case X86::COND_A: return true;
3578 case X86::COND_BE: return true;
3579 case X86::COND_AE: return true;
3581 llvm_unreachable("covered switch fell through?!");
3584 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3585 /// specific condition code, returning the condition code and the LHS/RHS of the
3586 /// comparison to make.
3587 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3588 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3590 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3591 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3592 // X > -1 -> X == 0, jump !sign.
3593 RHS = DAG.getConstant(0, RHS.getValueType());
3594 return X86::COND_NS;
3596 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3597 // X < 0 -> X == 0, jump on sign.
3600 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3602 RHS = DAG.getConstant(0, RHS.getValueType());
3603 return X86::COND_LE;
3607 switch (SetCCOpcode) {
3608 default: llvm_unreachable("Invalid integer condition!");
3609 case ISD::SETEQ: return X86::COND_E;
3610 case ISD::SETGT: return X86::COND_G;
3611 case ISD::SETGE: return X86::COND_GE;
3612 case ISD::SETLT: return X86::COND_L;
3613 case ISD::SETLE: return X86::COND_LE;
3614 case ISD::SETNE: return X86::COND_NE;
3615 case ISD::SETULT: return X86::COND_B;
3616 case ISD::SETUGT: return X86::COND_A;
3617 case ISD::SETULE: return X86::COND_BE;
3618 case ISD::SETUGE: return X86::COND_AE;
3622 // First determine if it is required or is profitable to flip the operands.
3624 // If LHS is a foldable load, but RHS is not, flip the condition.
3625 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3626 !ISD::isNON_EXTLoad(RHS.getNode())) {
3627 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3628 std::swap(LHS, RHS);
3631 switch (SetCCOpcode) {
3637 std::swap(LHS, RHS);
3641 // On a floating point condition, the flags are set as follows:
3643 // 0 | 0 | 0 | X > Y
3644 // 0 | 0 | 1 | X < Y
3645 // 1 | 0 | 0 | X == Y
3646 // 1 | 1 | 1 | unordered
3647 switch (SetCCOpcode) {
3648 default: llvm_unreachable("Condcode should be pre-legalized away");
3650 case ISD::SETEQ: return X86::COND_E;
3651 case ISD::SETOLT: // flipped
3653 case ISD::SETGT: return X86::COND_A;
3654 case ISD::SETOLE: // flipped
3656 case ISD::SETGE: return X86::COND_AE;
3657 case ISD::SETUGT: // flipped
3659 case ISD::SETLT: return X86::COND_B;
3660 case ISD::SETUGE: // flipped
3662 case ISD::SETLE: return X86::COND_BE;
3664 case ISD::SETNE: return X86::COND_NE;
3665 case ISD::SETUO: return X86::COND_P;
3666 case ISD::SETO: return X86::COND_NP;
3668 case ISD::SETUNE: return X86::COND_INVALID;
3672 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3673 /// code. Current x86 isa includes the following FP cmov instructions:
3674 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3675 static bool hasFPCMov(unsigned X86CC) {
3691 /// isFPImmLegal - Returns true if the target can instruction select the
3692 /// specified FP immediate natively. If false, the legalizer will
3693 /// materialize the FP immediate as a load from a constant pool.
3694 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3695 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3696 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3702 /// \brief Returns true if it is beneficial to convert a load of a constant
3703 /// to just the constant itself.
3704 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3706 assert(Ty->isIntegerTy());
3708 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3709 if (BitSize == 0 || BitSize > 64)
3714 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3715 /// the specified range (L, H].
3716 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3717 return (Val < 0) || (Val >= Low && Val < Hi);
3720 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3721 /// specified value.
3722 static bool isUndefOrEqual(int Val, int CmpVal) {
3723 return (Val < 0 || Val == CmpVal);
3726 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3727 /// from position Pos and ending in Pos+Size, falls within the specified
3728 /// sequential range (L, L+Pos]. or is undef.
3729 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3730 unsigned Pos, unsigned Size, int Low) {
3731 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3732 if (!isUndefOrEqual(Mask[i], Low))
3737 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3738 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3739 /// the second operand.
3740 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3741 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3742 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3743 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3744 return (Mask[0] < 2 && Mask[1] < 2);
3748 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3749 /// is suitable for input to PSHUFHW.
3750 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3751 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3754 // Lower quadword copied in order or undef.
3755 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3758 // Upper quadword shuffled.
3759 for (unsigned i = 4; i != 8; ++i)
3760 if (!isUndefOrInRange(Mask[i], 4, 8))
3763 if (VT == MVT::v16i16) {
3764 // Lower quadword copied in order or undef.
3765 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3768 // Upper quadword shuffled.
3769 for (unsigned i = 12; i != 16; ++i)
3770 if (!isUndefOrInRange(Mask[i], 12, 16))
3777 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3778 /// is suitable for input to PSHUFLW.
3779 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3780 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3783 // Upper quadword copied in order.
3784 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3787 // Lower quadword shuffled.
3788 for (unsigned i = 0; i != 4; ++i)
3789 if (!isUndefOrInRange(Mask[i], 0, 4))
3792 if (VT == MVT::v16i16) {
3793 // Upper quadword copied in order.
3794 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3797 // Lower quadword shuffled.
3798 for (unsigned i = 8; i != 12; ++i)
3799 if (!isUndefOrInRange(Mask[i], 8, 12))
3806 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3807 unsigned NumElts = VT.getVectorNumElements();
3808 unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3809 unsigned NumLaneElts = NumElts/NumLanes;
3811 // Do not handle 64-bit element shuffles with palignr.
3812 if (NumLaneElts == 2)
3815 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3817 for (i = 0; i != NumLaneElts; ++i) {
3822 // Lane is all undef, go to next lane
3823 if (i == NumLaneElts)
3826 int Start = Mask[i+l];
3828 // Make sure its in this lane in one of the sources
3829 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3830 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3833 // If not lane 0, then we must match lane 0
3834 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3837 // Correct second source to be contiguous with first source
3838 if (Start >= (int)NumElts)
3839 Start -= NumElts - NumLaneElts;
3841 // Make sure we're shifting in the right direction.
3842 if (Start <= (int)(i+l))
3847 // Check the rest of the elements to see if they are consecutive.
3848 for (++i; i != NumLaneElts; ++i) {
3849 int Idx = Mask[i+l];
3851 // Make sure its in this lane
3852 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3853 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3856 // If not lane 0, then we must match lane 0
3857 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3860 if (Idx >= (int)NumElts)
3861 Idx -= NumElts - NumLaneElts;
3863 if (!isUndefOrEqual(Idx, Start+i))
3872 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3873 /// is suitable for input to PALIGNR.
3874 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3875 const X86Subtarget *Subtarget) {
3876 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3877 (VT.is256BitVector() && !Subtarget->hasInt256()))
3878 // FIXME: Add AVX512BW.
3881 return isAlignrMask(Mask, VT, false);
3884 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3885 /// is suitable for input to PALIGNR.
3886 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
3887 const X86Subtarget *Subtarget) {
3888 // FIXME: Add AVX512VL.
3889 if (!VT.is512BitVector() || !Subtarget->hasAVX512())
3891 return isAlignrMask(Mask, VT, true);
3894 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3895 /// the two vector operands have swapped position.
3896 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3897 unsigned NumElems) {
3898 for (unsigned i = 0; i != NumElems; ++i) {
3902 else if (idx < (int)NumElems)
3903 Mask[i] = idx + NumElems;
3905 Mask[i] = idx - NumElems;
3909 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3910 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3911 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3912 /// reverse of what x86 shuffles want.
3913 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3915 unsigned NumElems = VT.getVectorNumElements();
3916 unsigned NumLanes = VT.getSizeInBits()/128;
3917 unsigned NumLaneElems = NumElems/NumLanes;
3919 if (NumLaneElems != 2 && NumLaneElems != 4)
3922 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3923 bool symetricMaskRequired =
3924 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3926 // VSHUFPSY divides the resulting vector into 4 chunks.
3927 // The sources are also splitted into 4 chunks, and each destination
3928 // chunk must come from a different source chunk.
3930 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3931 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3933 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3934 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3936 // VSHUFPDY divides the resulting vector into 4 chunks.
3937 // The sources are also splitted into 4 chunks, and each destination
3938 // chunk must come from a different source chunk.
3940 // SRC1 => X3 X2 X1 X0
3941 // SRC2 => Y3 Y2 Y1 Y0
3943 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3945 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3946 unsigned HalfLaneElems = NumLaneElems/2;
3947 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3948 for (unsigned i = 0; i != NumLaneElems; ++i) {
3949 int Idx = Mask[i+l];
3950 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3951 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3953 // For VSHUFPSY, the mask of the second half must be the same as the
3954 // first but with the appropriate offsets. This works in the same way as
3955 // VPERMILPS works with masks.
3956 if (!symetricMaskRequired || Idx < 0)
3958 if (MaskVal[i] < 0) {
3959 MaskVal[i] = Idx - l;
3962 if ((signed)(Idx - l) != MaskVal[i])
3970 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3971 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3972 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3973 if (!VT.is128BitVector())
3976 unsigned NumElems = VT.getVectorNumElements();
3981 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3982 return isUndefOrEqual(Mask[0], 6) &&
3983 isUndefOrEqual(Mask[1], 7) &&
3984 isUndefOrEqual(Mask[2], 2) &&
3985 isUndefOrEqual(Mask[3], 3);
3988 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3989 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3991 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3992 if (!VT.is128BitVector())
3995 unsigned NumElems = VT.getVectorNumElements();
4000 return isUndefOrEqual(Mask[0], 2) &&
4001 isUndefOrEqual(Mask[1], 3) &&
4002 isUndefOrEqual(Mask[2], 2) &&
4003 isUndefOrEqual(Mask[3], 3);
4006 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4007 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4008 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4009 if (!VT.is128BitVector())
4012 unsigned NumElems = VT.getVectorNumElements();
4014 if (NumElems != 2 && NumElems != 4)
4017 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4018 if (!isUndefOrEqual(Mask[i], i + NumElems))
4021 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4022 if (!isUndefOrEqual(Mask[i], i))
4028 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4029 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4030 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4031 if (!VT.is128BitVector())
4034 unsigned NumElems = VT.getVectorNumElements();
4036 if (NumElems != 2 && NumElems != 4)
4039 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4040 if (!isUndefOrEqual(Mask[i], i))
4043 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4044 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4050 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4051 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4052 /// i. e: If all but one element come from the same vector.
4053 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4054 // TODO: Deal with AVX's VINSERTPS
4055 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4058 unsigned CorrectPosV1 = 0;
4059 unsigned CorrectPosV2 = 0;
4060 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4061 if (Mask[i] == -1) {
4069 else if (Mask[i] == i + 4)
4073 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4074 // We have 3 elements (undefs count as elements from any vector) from one
4075 // vector, and one from another.
4082 // Some special combinations that can be optimized.
4085 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4086 SelectionDAG &DAG) {
4087 MVT VT = SVOp->getSimpleValueType(0);
4090 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4093 ArrayRef<int> Mask = SVOp->getMask();
4095 // These are the special masks that may be optimized.
4096 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4097 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4098 bool MatchEvenMask = true;
4099 bool MatchOddMask = true;
4100 for (int i=0; i<8; ++i) {
4101 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4102 MatchEvenMask = false;
4103 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4104 MatchOddMask = false;
4107 if (!MatchEvenMask && !MatchOddMask)
4110 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4112 SDValue Op0 = SVOp->getOperand(0);
4113 SDValue Op1 = SVOp->getOperand(1);
4115 if (MatchEvenMask) {
4116 // Shift the second operand right to 32 bits.
4117 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4118 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4120 // Shift the first operand left to 32 bits.
4121 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4122 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4124 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4125 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4128 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4129 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4130 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4131 bool HasInt256, bool V2IsSplat = false) {
4133 assert(VT.getSizeInBits() >= 128 &&
4134 "Unsupported vector type for unpckl");
4136 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4138 unsigned NumOf256BitLanes;
4139 unsigned NumElts = VT.getVectorNumElements();
4140 if (VT.is256BitVector()) {
4141 if (NumElts != 4 && NumElts != 8 &&
4142 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4145 NumOf256BitLanes = 1;
4146 } else if (VT.is512BitVector()) {
4147 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4148 "Unsupported vector type for unpckh");
4150 NumOf256BitLanes = 2;
4153 NumOf256BitLanes = 1;
4156 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4157 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4159 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4160 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4161 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4162 int BitI = Mask[l256*NumEltsInStride+l+i];
4163 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4164 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4166 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4168 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4176 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4177 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4178 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4179 bool HasInt256, bool V2IsSplat = false) {
4180 assert(VT.getSizeInBits() >= 128 &&
4181 "Unsupported vector type for unpckh");
4183 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4185 unsigned NumOf256BitLanes;
4186 unsigned NumElts = VT.getVectorNumElements();
4187 if (VT.is256BitVector()) {
4188 if (NumElts != 4 && NumElts != 8 &&
4189 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4192 NumOf256BitLanes = 1;
4193 } else if (VT.is512BitVector()) {
4194 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4195 "Unsupported vector type for unpckh");
4197 NumOf256BitLanes = 2;
4200 NumOf256BitLanes = 1;
4203 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4204 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4206 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4207 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4208 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4209 int BitI = Mask[l256*NumEltsInStride+l+i];
4210 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4211 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4213 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4215 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4223 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4224 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4226 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4227 unsigned NumElts = VT.getVectorNumElements();
4228 bool Is256BitVec = VT.is256BitVector();
4230 if (VT.is512BitVector())
4232 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4233 "Unsupported vector type for unpckh");
4235 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4236 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4239 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4240 // FIXME: Need a better way to get rid of this, there's no latency difference
4241 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4242 // the former later. We should also remove the "_undef" special mask.
4243 if (NumElts == 4 && Is256BitVec)
4246 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4247 // independently on 128-bit lanes.
4248 unsigned NumLanes = VT.getSizeInBits()/128;
4249 unsigned NumLaneElts = NumElts/NumLanes;
4251 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4252 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4253 int BitI = Mask[l+i];
4254 int BitI1 = Mask[l+i+1];
4256 if (!isUndefOrEqual(BitI, j))
4258 if (!isUndefOrEqual(BitI1, j))
4266 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4267 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4269 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4270 unsigned NumElts = VT.getVectorNumElements();
4272 if (VT.is512BitVector())
4275 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4276 "Unsupported vector type for unpckh");
4278 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4279 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4282 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4283 // independently on 128-bit lanes.
4284 unsigned NumLanes = VT.getSizeInBits()/128;
4285 unsigned NumLaneElts = NumElts/NumLanes;
4287 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4288 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4289 int BitI = Mask[l+i];
4290 int BitI1 = Mask[l+i+1];
4291 if (!isUndefOrEqual(BitI, j))
4293 if (!isUndefOrEqual(BitI1, j))
4300 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4301 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4302 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4303 if (!VT.is512BitVector())
4306 unsigned NumElts = VT.getVectorNumElements();
4307 unsigned HalfSize = NumElts/2;
4308 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4309 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4314 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4315 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4323 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4324 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4325 /// MOVSD, and MOVD, i.e. setting the lowest element.
4326 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4327 if (VT.getVectorElementType().getSizeInBits() < 32)
4329 if (!VT.is128BitVector())
4332 unsigned NumElts = VT.getVectorNumElements();
4334 if (!isUndefOrEqual(Mask[0], NumElts))
4337 for (unsigned i = 1; i != NumElts; ++i)
4338 if (!isUndefOrEqual(Mask[i], i))
4344 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4345 /// as permutations between 128-bit chunks or halves. As an example: this
4347 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4348 /// The first half comes from the second half of V1 and the second half from the
4349 /// the second half of V2.
4350 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4351 if (!HasFp256 || !VT.is256BitVector())
4354 // The shuffle result is divided into half A and half B. In total the two
4355 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4356 // B must come from C, D, E or F.
4357 unsigned HalfSize = VT.getVectorNumElements()/2;
4358 bool MatchA = false, MatchB = false;
4360 // Check if A comes from one of C, D, E, F.
4361 for (unsigned Half = 0; Half != 4; ++Half) {
4362 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4368 // Check if B comes from one of C, D, E, F.
4369 for (unsigned Half = 0; Half != 4; ++Half) {
4370 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4376 return MatchA && MatchB;
4379 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4380 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4381 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4382 MVT VT = SVOp->getSimpleValueType(0);
4384 unsigned HalfSize = VT.getVectorNumElements()/2;
4386 unsigned FstHalf = 0, SndHalf = 0;
4387 for (unsigned i = 0; i < HalfSize; ++i) {
4388 if (SVOp->getMaskElt(i) > 0) {
4389 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4393 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4394 if (SVOp->getMaskElt(i) > 0) {
4395 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4400 return (FstHalf | (SndHalf << 4));
4403 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4404 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4405 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4409 unsigned NumElts = VT.getVectorNumElements();
4411 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4412 for (unsigned i = 0; i != NumElts; ++i) {
4415 Imm8 |= Mask[i] << (i*2);
4420 unsigned LaneSize = 4;
4421 SmallVector<int, 4> MaskVal(LaneSize, -1);
4423 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4424 for (unsigned i = 0; i != LaneSize; ++i) {
4425 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4429 if (MaskVal[i] < 0) {
4430 MaskVal[i] = Mask[i+l] - l;
4431 Imm8 |= MaskVal[i] << (i*2);
4434 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4441 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4442 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4443 /// Note that VPERMIL mask matching is different depending whether theunderlying
4444 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4445 /// to the same elements of the low, but to the higher half of the source.
4446 /// In VPERMILPD the two lanes could be shuffled independently of each other
4447 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4448 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4449 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4450 if (VT.getSizeInBits() < 256 || EltSize < 32)
4452 bool symetricMaskRequired = (EltSize == 32);
4453 unsigned NumElts = VT.getVectorNumElements();
4455 unsigned NumLanes = VT.getSizeInBits()/128;
4456 unsigned LaneSize = NumElts/NumLanes;
4457 // 2 or 4 elements in one lane
4459 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4460 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4461 for (unsigned i = 0; i != LaneSize; ++i) {
4462 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4464 if (symetricMaskRequired) {
4465 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4466 ExpectedMaskVal[i] = Mask[i+l] - l;
4469 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4477 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4478 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4479 /// element of vector 2 and the other elements to come from vector 1 in order.
4480 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4481 bool V2IsSplat = false, bool V2IsUndef = false) {
4482 if (!VT.is128BitVector())
4485 unsigned NumOps = VT.getVectorNumElements();
4486 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4489 if (!isUndefOrEqual(Mask[0], 0))
4492 for (unsigned i = 1; i != NumOps; ++i)
4493 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4494 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4495 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4501 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4502 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4503 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4504 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4505 const X86Subtarget *Subtarget) {
4506 if (!Subtarget->hasSSE3())
4509 unsigned NumElems = VT.getVectorNumElements();
4511 if ((VT.is128BitVector() && NumElems != 4) ||
4512 (VT.is256BitVector() && NumElems != 8) ||
4513 (VT.is512BitVector() && NumElems != 16))
4516 // "i+1" is the value the indexed mask element must have
4517 for (unsigned i = 0; i != NumElems; i += 2)
4518 if (!isUndefOrEqual(Mask[i], i+1) ||
4519 !isUndefOrEqual(Mask[i+1], i+1))
4525 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4526 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4527 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4528 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4529 const X86Subtarget *Subtarget) {
4530 if (!Subtarget->hasSSE3())
4533 unsigned NumElems = VT.getVectorNumElements();
4535 if ((VT.is128BitVector() && NumElems != 4) ||
4536 (VT.is256BitVector() && NumElems != 8) ||
4537 (VT.is512BitVector() && NumElems != 16))
4540 // "i" is the value the indexed mask element must have
4541 for (unsigned i = 0; i != NumElems; i += 2)
4542 if (!isUndefOrEqual(Mask[i], i) ||
4543 !isUndefOrEqual(Mask[i+1], i))
4549 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4550 /// specifies a shuffle of elements that is suitable for input to 256-bit
4551 /// version of MOVDDUP.
4552 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4553 if (!HasFp256 || !VT.is256BitVector())
4556 unsigned NumElts = VT.getVectorNumElements();
4560 for (unsigned i = 0; i != NumElts/2; ++i)
4561 if (!isUndefOrEqual(Mask[i], 0))
4563 for (unsigned i = NumElts/2; i != NumElts; ++i)
4564 if (!isUndefOrEqual(Mask[i], NumElts/2))
4569 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4570 /// specifies a shuffle of elements that is suitable for input to 128-bit
4571 /// version of MOVDDUP.
4572 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4573 if (!VT.is128BitVector())
4576 unsigned e = VT.getVectorNumElements() / 2;
4577 for (unsigned i = 0; i != e; ++i)
4578 if (!isUndefOrEqual(Mask[i], i))
4580 for (unsigned i = 0; i != e; ++i)
4581 if (!isUndefOrEqual(Mask[e+i], i))
4586 /// isVEXTRACTIndex - Return true if the specified
4587 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4588 /// suitable for instruction that extract 128 or 256 bit vectors
4589 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4590 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4591 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4594 // The index should be aligned on a vecWidth-bit boundary.
4596 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4598 MVT VT = N->getSimpleValueType(0);
4599 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4600 bool Result = (Index * ElSize) % vecWidth == 0;
4605 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4606 /// operand specifies a subvector insert that is suitable for input to
4607 /// insertion of 128 or 256-bit subvectors
4608 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4609 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4610 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4612 // The index should be aligned on a vecWidth-bit boundary.
4614 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4616 MVT VT = N->getSimpleValueType(0);
4617 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4618 bool Result = (Index * ElSize) % vecWidth == 0;
4623 bool X86::isVINSERT128Index(SDNode *N) {
4624 return isVINSERTIndex(N, 128);
4627 bool X86::isVINSERT256Index(SDNode *N) {
4628 return isVINSERTIndex(N, 256);
4631 bool X86::isVEXTRACT128Index(SDNode *N) {
4632 return isVEXTRACTIndex(N, 128);
4635 bool X86::isVEXTRACT256Index(SDNode *N) {
4636 return isVEXTRACTIndex(N, 256);
4639 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4640 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4641 /// Handles 128-bit and 256-bit.
4642 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4643 MVT VT = N->getSimpleValueType(0);
4645 assert((VT.getSizeInBits() >= 128) &&
4646 "Unsupported vector type for PSHUF/SHUFP");
4648 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4649 // independently on 128-bit lanes.
4650 unsigned NumElts = VT.getVectorNumElements();
4651 unsigned NumLanes = VT.getSizeInBits()/128;
4652 unsigned NumLaneElts = NumElts/NumLanes;
4654 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4655 "Only supports 2, 4 or 8 elements per lane");
4657 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4659 for (unsigned i = 0; i != NumElts; ++i) {
4660 int Elt = N->getMaskElt(i);
4661 if (Elt < 0) continue;
4662 Elt &= NumLaneElts - 1;
4663 unsigned ShAmt = (i << Shift) % 8;
4664 Mask |= Elt << ShAmt;
4670 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4671 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4672 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4673 MVT VT = N->getSimpleValueType(0);
4675 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4676 "Unsupported vector type for PSHUFHW");
4678 unsigned NumElts = VT.getVectorNumElements();
4681 for (unsigned l = 0; l != NumElts; l += 8) {
4682 // 8 nodes per lane, but we only care about the last 4.
4683 for (unsigned i = 0; i < 4; ++i) {
4684 int Elt = N->getMaskElt(l+i+4);
4685 if (Elt < 0) continue;
4686 Elt &= 0x3; // only 2-bits.
4687 Mask |= Elt << (i * 2);
4694 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4695 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4696 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4697 MVT VT = N->getSimpleValueType(0);
4699 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4700 "Unsupported vector type for PSHUFHW");
4702 unsigned NumElts = VT.getVectorNumElements();
4705 for (unsigned l = 0; l != NumElts; l += 8) {
4706 // 8 nodes per lane, but we only care about the first 4.
4707 for (unsigned i = 0; i < 4; ++i) {
4708 int Elt = N->getMaskElt(l+i);
4709 if (Elt < 0) continue;
4710 Elt &= 0x3; // only 2-bits
4711 Mask |= Elt << (i * 2);
4718 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4719 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4720 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4722 MVT VT = SVOp->getSimpleValueType(0);
4723 unsigned EltSize = InterLane ? 1 :
4724 VT.getVectorElementType().getSizeInBits() >> 3;
4726 unsigned NumElts = VT.getVectorNumElements();
4727 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4728 unsigned NumLaneElts = NumElts/NumLanes;
4732 for (i = 0; i != NumElts; ++i) {
4733 Val = SVOp->getMaskElt(i);
4737 if (Val >= (int)NumElts)
4738 Val -= NumElts - NumLaneElts;
4740 assert(Val - i > 0 && "PALIGNR imm should be positive");
4741 return (Val - i) * EltSize;
4744 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4745 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4746 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4747 return getShuffleAlignrImmediate(SVOp, false);
4750 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4751 return getShuffleAlignrImmediate(SVOp, true);
4755 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4756 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4757 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4758 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4761 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4763 MVT VecVT = N->getOperand(0).getSimpleValueType();
4764 MVT ElVT = VecVT.getVectorElementType();
4766 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4767 return Index / NumElemsPerChunk;
4770 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4771 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4772 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4773 llvm_unreachable("Illegal insert subvector for VINSERT");
4776 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4778 MVT VecVT = N->getSimpleValueType(0);
4779 MVT ElVT = VecVT.getVectorElementType();
4781 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4782 return Index / NumElemsPerChunk;
4785 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4786 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4787 /// and VINSERTI128 instructions.
4788 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4789 return getExtractVEXTRACTImmediate(N, 128);
4792 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4793 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4794 /// and VINSERTI64x4 instructions.
4795 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4796 return getExtractVEXTRACTImmediate(N, 256);
4799 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4800 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4801 /// and VINSERTI128 instructions.
4802 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4803 return getInsertVINSERTImmediate(N, 128);
4806 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4807 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4808 /// and VINSERTI64x4 instructions.
4809 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4810 return getInsertVINSERTImmediate(N, 256);
4813 /// isZero - Returns true if Elt is a constant integer zero
4814 static bool isZero(SDValue V) {
4815 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4816 return C && C->isNullValue();
4819 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4821 bool X86::isZeroNode(SDValue Elt) {
4824 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4825 return CFP->getValueAPF().isPosZero();
4829 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4830 /// match movhlps. The lower half elements should come from upper half of
4831 /// V1 (and in order), and the upper half elements should come from the upper
4832 /// half of V2 (and in order).
4833 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4834 if (!VT.is128BitVector())
4836 if (VT.getVectorNumElements() != 4)
4838 for (unsigned i = 0, e = 2; i != e; ++i)
4839 if (!isUndefOrEqual(Mask[i], i+2))
4841 for (unsigned i = 2; i != 4; ++i)
4842 if (!isUndefOrEqual(Mask[i], i+4))
4847 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4848 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4850 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4851 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4853 N = N->getOperand(0).getNode();
4854 if (!ISD::isNON_EXTLoad(N))
4857 *LD = cast<LoadSDNode>(N);
4861 // Test whether the given value is a vector value which will be legalized
4863 static bool WillBeConstantPoolLoad(SDNode *N) {
4864 if (N->getOpcode() != ISD::BUILD_VECTOR)
4867 // Check for any non-constant elements.
4868 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4869 switch (N->getOperand(i).getNode()->getOpcode()) {
4871 case ISD::ConstantFP:
4878 // Vectors of all-zeros and all-ones are materialized with special
4879 // instructions rather than being loaded.
4880 return !ISD::isBuildVectorAllZeros(N) &&
4881 !ISD::isBuildVectorAllOnes(N);
4884 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4885 /// match movlp{s|d}. The lower half elements should come from lower half of
4886 /// V1 (and in order), and the upper half elements should come from the upper
4887 /// half of V2 (and in order). And since V1 will become the source of the
4888 /// MOVLP, it must be either a vector load or a scalar load to vector.
4889 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4890 ArrayRef<int> Mask, MVT VT) {
4891 if (!VT.is128BitVector())
4894 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4896 // Is V2 is a vector load, don't do this transformation. We will try to use
4897 // load folding shufps op.
4898 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4901 unsigned NumElems = VT.getVectorNumElements();
4903 if (NumElems != 2 && NumElems != 4)
4905 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4906 if (!isUndefOrEqual(Mask[i], i))
4908 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4909 if (!isUndefOrEqual(Mask[i], i+NumElems))
4914 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4915 /// to an zero vector.
4916 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4917 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4918 SDValue V1 = N->getOperand(0);
4919 SDValue V2 = N->getOperand(1);
4920 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4921 for (unsigned i = 0; i != NumElems; ++i) {
4922 int Idx = N->getMaskElt(i);
4923 if (Idx >= (int)NumElems) {
4924 unsigned Opc = V2.getOpcode();
4925 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4927 if (Opc != ISD::BUILD_VECTOR ||
4928 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4930 } else if (Idx >= 0) {
4931 unsigned Opc = V1.getOpcode();
4932 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4934 if (Opc != ISD::BUILD_VECTOR ||
4935 !X86::isZeroNode(V1.getOperand(Idx)))
4942 /// getZeroVector - Returns a vector of specified type with all zero elements.
4944 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4945 SelectionDAG &DAG, SDLoc dl) {
4946 assert(VT.isVector() && "Expected a vector type");
4948 // Always build SSE zero vectors as <4 x i32> bitcasted
4949 // to their dest type. This ensures they get CSE'd.
4951 if (VT.is128BitVector()) { // SSE
4952 if (Subtarget->hasSSE2()) { // SSE2
4953 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4954 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4956 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4957 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4959 } else if (VT.is256BitVector()) { // AVX
4960 if (Subtarget->hasInt256()) { // AVX2
4961 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4962 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4963 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4965 // 256-bit logic and arithmetic instructions in AVX are all
4966 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4967 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4968 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4969 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4971 } else if (VT.is512BitVector()) { // AVX-512
4972 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4973 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4974 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4975 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4976 } else if (VT.getScalarType() == MVT::i1) {
4977 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4978 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4979 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4980 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4982 llvm_unreachable("Unexpected vector type");
4984 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4987 /// getOnesVector - Returns a vector of specified type with all bits set.
4988 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4989 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4990 /// Then bitcast to their original type, ensuring they get CSE'd.
4991 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4993 assert(VT.isVector() && "Expected a vector type");
4995 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4997 if (VT.is256BitVector()) {
4998 if (HasInt256) { // AVX2
4999 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5000 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5002 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5003 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5005 } else if (VT.is128BitVector()) {
5006 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5008 llvm_unreachable("Unexpected vector type");
5010 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5013 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5014 /// that point to V2 points to its first element.
5015 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5016 for (unsigned i = 0; i != NumElems; ++i) {
5017 if (Mask[i] > (int)NumElems) {
5023 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5024 /// operation of specified width.
5025 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5027 unsigned NumElems = VT.getVectorNumElements();
5028 SmallVector<int, 8> Mask;
5029 Mask.push_back(NumElems);
5030 for (unsigned i = 1; i != NumElems; ++i)
5032 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5035 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5036 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5038 unsigned NumElems = VT.getVectorNumElements();
5039 SmallVector<int, 8> Mask;
5040 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5042 Mask.push_back(i + NumElems);
5044 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5047 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5048 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5050 unsigned NumElems = VT.getVectorNumElements();
5051 SmallVector<int, 8> Mask;
5052 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5053 Mask.push_back(i + Half);
5054 Mask.push_back(i + NumElems + Half);
5056 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5059 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5060 // a generic shuffle instruction because the target has no such instructions.
5061 // Generate shuffles which repeat i16 and i8 several times until they can be
5062 // represented by v4f32 and then be manipulated by target suported shuffles.
5063 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5064 MVT VT = V.getSimpleValueType();
5065 int NumElems = VT.getVectorNumElements();
5068 while (NumElems > 4) {
5069 if (EltNo < NumElems/2) {
5070 V = getUnpackl(DAG, dl, VT, V, V);
5072 V = getUnpackh(DAG, dl, VT, V, V);
5073 EltNo -= NumElems/2;
5080 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5081 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5082 MVT VT = V.getSimpleValueType();
5085 if (VT.is128BitVector()) {
5086 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5087 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5088 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5090 } else if (VT.is256BitVector()) {
5091 // To use VPERMILPS to splat scalars, the second half of indicies must
5092 // refer to the higher part, which is a duplication of the lower one,
5093 // because VPERMILPS can only handle in-lane permutations.
5094 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5095 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5097 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5098 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5101 llvm_unreachable("Vector size not supported");
5103 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5106 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5107 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5108 MVT SrcVT = SV->getSimpleValueType(0);
5109 SDValue V1 = SV->getOperand(0);
5112 int EltNo = SV->getSplatIndex();
5113 int NumElems = SrcVT.getVectorNumElements();
5114 bool Is256BitVec = SrcVT.is256BitVector();
5116 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5117 "Unknown how to promote splat for type");
5119 // Extract the 128-bit part containing the splat element and update
5120 // the splat element index when it refers to the higher register.
5122 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5123 if (EltNo >= NumElems/2)
5124 EltNo -= NumElems/2;
5127 // All i16 and i8 vector types can't be used directly by a generic shuffle
5128 // instruction because the target has no such instruction. Generate shuffles
5129 // which repeat i16 and i8 several times until they fit in i32, and then can
5130 // be manipulated by target suported shuffles.
5131 MVT EltVT = SrcVT.getVectorElementType();
5132 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5133 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5135 // Recreate the 256-bit vector and place the same 128-bit vector
5136 // into the low and high part. This is necessary because we want
5137 // to use VPERM* to shuffle the vectors
5139 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5142 return getLegalSplat(DAG, V1, EltNo);
5145 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5146 /// vector of zero or undef vector. This produces a shuffle where the low
5147 /// element of V2 is swizzled into the zero/undef vector, landing at element
5148 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5149 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5151 const X86Subtarget *Subtarget,
5152 SelectionDAG &DAG) {
5153 MVT VT = V2.getSimpleValueType();
5155 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5156 unsigned NumElems = VT.getVectorNumElements();
5157 SmallVector<int, 16> MaskVec;
5158 for (unsigned i = 0; i != NumElems; ++i)
5159 // If this is the insertion idx, put the low elt of V2 here.
5160 MaskVec.push_back(i == Idx ? NumElems : i);
5161 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5164 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5165 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5166 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5167 /// shuffles which use a single input multiple times, and in those cases it will
5168 /// adjust the mask to only have indices within that single input.
5169 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5170 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5171 unsigned NumElems = VT.getVectorNumElements();
5175 bool IsFakeUnary = false;
5176 switch(N->getOpcode()) {
5178 ImmN = N->getOperand(N->getNumOperands()-1);
5179 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5180 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5182 case X86ISD::UNPCKH:
5183 DecodeUNPCKHMask(VT, Mask);
5184 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5186 case X86ISD::UNPCKL:
5187 DecodeUNPCKLMask(VT, Mask);
5188 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5190 case X86ISD::MOVHLPS:
5191 DecodeMOVHLPSMask(NumElems, Mask);
5192 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5194 case X86ISD::MOVLHPS:
5195 DecodeMOVLHPSMask(NumElems, Mask);
5196 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5198 case X86ISD::PALIGNR:
5199 ImmN = N->getOperand(N->getNumOperands()-1);
5200 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5202 case X86ISD::PSHUFD:
5203 case X86ISD::VPERMILP:
5204 ImmN = N->getOperand(N->getNumOperands()-1);
5205 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5208 case X86ISD::PSHUFHW:
5209 ImmN = N->getOperand(N->getNumOperands()-1);
5210 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5213 case X86ISD::PSHUFLW:
5214 ImmN = N->getOperand(N->getNumOperands()-1);
5215 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5218 case X86ISD::PSHUFB: {
5220 SDValue MaskNode = N->getOperand(1);
5221 while (MaskNode->getOpcode() == ISD::BITCAST)
5222 MaskNode = MaskNode->getOperand(0);
5224 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5225 // If we have a build-vector, then things are easy.
5226 EVT VT = MaskNode.getValueType();
5227 assert(VT.isVector() &&
5228 "Can't produce a non-vector with a build_vector!");
5229 if (!VT.isInteger())
5232 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5234 SmallVector<uint64_t, 32> RawMask;
5235 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5236 auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5239 APInt MaskElement = CN->getAPIntValue();
5241 // We now have to decode the element which could be any integer size and
5242 // extract each byte of it.
5243 for (int j = 0; j < NumBytesPerElement; ++j) {
5244 // Note that this is x86 and so always little endian: the low byte is
5245 // the first byte of the mask.
5246 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5247 MaskElement = MaskElement.lshr(8);
5250 DecodePSHUFBMask(RawMask, Mask);
5254 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5258 SDValue Ptr = MaskLoad->getBasePtr();
5259 if (Ptr->getOpcode() == X86ISD::Wrapper)
5260 Ptr = Ptr->getOperand(0);
5262 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5263 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5266 if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5267 // FIXME: Support AVX-512 here.
5268 if (!C->getType()->isVectorTy() ||
5269 (C->getNumElements() != 16 && C->getNumElements() != 32))
5272 assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5273 DecodePSHUFBMask(C, Mask);
5279 case X86ISD::VPERMI:
5280 ImmN = N->getOperand(N->getNumOperands()-1);
5281 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5285 case X86ISD::MOVSD: {
5286 // The index 0 always comes from the first element of the second source,
5287 // this is why MOVSS and MOVSD are used in the first place. The other
5288 // elements come from the other positions of the first source vector
5289 Mask.push_back(NumElems);
5290 for (unsigned i = 1; i != NumElems; ++i) {
5295 case X86ISD::VPERM2X128:
5296 ImmN = N->getOperand(N->getNumOperands()-1);
5297 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5298 if (Mask.empty()) return false;
5300 case X86ISD::MOVDDUP:
5301 case X86ISD::MOVLHPD:
5302 case X86ISD::MOVLPD:
5303 case X86ISD::MOVLPS:
5304 case X86ISD::MOVSHDUP:
5305 case X86ISD::MOVSLDUP:
5306 // Not yet implemented
5308 default: llvm_unreachable("unknown target shuffle node");
5311 // If we have a fake unary shuffle, the shuffle mask is spread across two
5312 // inputs that are actually the same node. Re-map the mask to always point
5313 // into the first input.
5316 if (M >= (int)Mask.size())
5322 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5323 /// element of the result of the vector shuffle.
5324 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5327 return SDValue(); // Limit search depth.
5329 SDValue V = SDValue(N, 0);
5330 EVT VT = V.getValueType();
5331 unsigned Opcode = V.getOpcode();
5333 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5334 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5335 int Elt = SV->getMaskElt(Index);
5338 return DAG.getUNDEF(VT.getVectorElementType());
5340 unsigned NumElems = VT.getVectorNumElements();
5341 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5342 : SV->getOperand(1);
5343 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5346 // Recurse into target specific vector shuffles to find scalars.
5347 if (isTargetShuffle(Opcode)) {
5348 MVT ShufVT = V.getSimpleValueType();
5349 unsigned NumElems = ShufVT.getVectorNumElements();
5350 SmallVector<int, 16> ShuffleMask;
5353 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5356 int Elt = ShuffleMask[Index];
5358 return DAG.getUNDEF(ShufVT.getVectorElementType());
5360 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5362 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5366 // Actual nodes that may contain scalar elements
5367 if (Opcode == ISD::BITCAST) {
5368 V = V.getOperand(0);
5369 EVT SrcVT = V.getValueType();
5370 unsigned NumElems = VT.getVectorNumElements();
5372 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5376 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5377 return (Index == 0) ? V.getOperand(0)
5378 : DAG.getUNDEF(VT.getVectorElementType());
5380 if (V.getOpcode() == ISD::BUILD_VECTOR)
5381 return V.getOperand(Index);
5386 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5387 /// shuffle operation which come from a consecutively from a zero. The
5388 /// search can start in two different directions, from left or right.
5389 /// We count undefs as zeros until PreferredNum is reached.
5390 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5391 unsigned NumElems, bool ZerosFromLeft,
5393 unsigned PreferredNum = -1U) {
5394 unsigned NumZeros = 0;
5395 for (unsigned i = 0; i != NumElems; ++i) {
5396 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5397 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5401 if (X86::isZeroNode(Elt))
5403 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5404 NumZeros = std::min(NumZeros + 1, PreferredNum);
5412 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5413 /// correspond consecutively to elements from one of the vector operands,
5414 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5416 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5417 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5418 unsigned NumElems, unsigned &OpNum) {
5419 bool SeenV1 = false;
5420 bool SeenV2 = false;
5422 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5423 int Idx = SVOp->getMaskElt(i);
5424 // Ignore undef indicies
5428 if (Idx < (int)NumElems)
5433 // Only accept consecutive elements from the same vector
5434 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5438 OpNum = SeenV1 ? 0 : 1;
5442 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5443 /// logical left shift of a vector.
5444 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5445 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5447 SVOp->getSimpleValueType(0).getVectorNumElements();
5448 unsigned NumZeros = getNumOfConsecutiveZeros(
5449 SVOp, NumElems, false /* check zeros from right */, DAG,
5450 SVOp->getMaskElt(0));
5456 // Considering the elements in the mask that are not consecutive zeros,
5457 // check if they consecutively come from only one of the source vectors.
5459 // V1 = {X, A, B, C} 0
5461 // vector_shuffle V1, V2 <1, 2, 3, X>
5463 if (!isShuffleMaskConsecutive(SVOp,
5464 0, // Mask Start Index
5465 NumElems-NumZeros, // Mask End Index(exclusive)
5466 NumZeros, // Where to start looking in the src vector
5467 NumElems, // Number of elements in vector
5468 OpSrc)) // Which source operand ?
5473 ShVal = SVOp->getOperand(OpSrc);
5477 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5478 /// logical left shift of a vector.
5479 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5480 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5482 SVOp->getSimpleValueType(0).getVectorNumElements();
5483 unsigned NumZeros = getNumOfConsecutiveZeros(
5484 SVOp, NumElems, true /* check zeros from left */, DAG,
5485 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5491 // Considering the elements in the mask that are not consecutive zeros,
5492 // check if they consecutively come from only one of the source vectors.
5494 // 0 { A, B, X, X } = V2
5496 // vector_shuffle V1, V2 <X, X, 4, 5>
5498 if (!isShuffleMaskConsecutive(SVOp,
5499 NumZeros, // Mask Start Index
5500 NumElems, // Mask End Index(exclusive)
5501 0, // Where to start looking in the src vector
5502 NumElems, // Number of elements in vector
5503 OpSrc)) // Which source operand ?
5508 ShVal = SVOp->getOperand(OpSrc);
5512 /// isVectorShift - Returns true if the shuffle can be implemented as a
5513 /// logical left or right shift of a vector.
5514 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5515 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5516 // Although the logic below support any bitwidth size, there are no
5517 // shift instructions which handle more than 128-bit vectors.
5518 if (!SVOp->getSimpleValueType(0).is128BitVector())
5521 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5522 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5528 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5530 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5531 unsigned NumNonZero, unsigned NumZero,
5533 const X86Subtarget* Subtarget,
5534 const TargetLowering &TLI) {
5541 for (unsigned i = 0; i < 16; ++i) {
5542 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5543 if (ThisIsNonZero && First) {
5545 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5547 V = DAG.getUNDEF(MVT::v8i16);
5552 SDValue ThisElt, LastElt;
5553 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5554 if (LastIsNonZero) {
5555 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5556 MVT::i16, Op.getOperand(i-1));
5558 if (ThisIsNonZero) {
5559 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5560 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5561 ThisElt, DAG.getConstant(8, MVT::i8));
5563 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5567 if (ThisElt.getNode())
5568 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5569 DAG.getIntPtrConstant(i/2));
5573 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5576 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5578 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5579 unsigned NumNonZero, unsigned NumZero,
5581 const X86Subtarget* Subtarget,
5582 const TargetLowering &TLI) {
5589 for (unsigned i = 0; i < 8; ++i) {
5590 bool isNonZero = (NonZeros & (1 << i)) != 0;
5594 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5596 V = DAG.getUNDEF(MVT::v8i16);
5599 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5600 MVT::v8i16, V, Op.getOperand(i),
5601 DAG.getIntPtrConstant(i));
5608 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5609 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5610 unsigned NonZeros, unsigned NumNonZero,
5611 unsigned NumZero, SelectionDAG &DAG,
5612 const X86Subtarget *Subtarget,
5613 const TargetLowering &TLI) {
5614 // We know there's at least one non-zero element
5615 unsigned FirstNonZeroIdx = 0;
5616 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5617 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5618 X86::isZeroNode(FirstNonZero)) {
5620 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5623 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5624 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5627 SDValue V = FirstNonZero.getOperand(0);
5628 MVT VVT = V.getSimpleValueType();
5629 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5632 unsigned FirstNonZeroDst =
5633 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5634 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5635 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5636 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5638 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5639 SDValue Elem = Op.getOperand(Idx);
5640 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5643 // TODO: What else can be here? Deal with it.
5644 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5647 // TODO: Some optimizations are still possible here
5648 // ex: Getting one element from a vector, and the rest from another.
5649 if (Elem.getOperand(0) != V)
5652 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5655 else if (IncorrectIdx == -1U) {
5659 // There was already one element with an incorrect index.
5660 // We can't optimize this case to an insertps.
5664 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5666 EVT VT = Op.getSimpleValueType();
5667 unsigned ElementMoveMask = 0;
5668 if (IncorrectIdx == -1U)
5669 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5671 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5673 SDValue InsertpsMask =
5674 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5675 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5681 /// getVShift - Return a vector logical shift node.
5683 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5684 unsigned NumBits, SelectionDAG &DAG,
5685 const TargetLowering &TLI, SDLoc dl) {
5686 assert(VT.is128BitVector() && "Unknown type for VShift");
5687 EVT ShVT = MVT::v2i64;
5688 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5689 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5690 return DAG.getNode(ISD::BITCAST, dl, VT,
5691 DAG.getNode(Opc, dl, ShVT, SrcOp,
5692 DAG.getConstant(NumBits,
5693 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5697 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5699 // Check if the scalar load can be widened into a vector load. And if
5700 // the address is "base + cst" see if the cst can be "absorbed" into
5701 // the shuffle mask.
5702 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5703 SDValue Ptr = LD->getBasePtr();
5704 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5706 EVT PVT = LD->getValueType(0);
5707 if (PVT != MVT::i32 && PVT != MVT::f32)
5712 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5713 FI = FINode->getIndex();
5715 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5716 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5717 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5718 Offset = Ptr.getConstantOperandVal(1);
5719 Ptr = Ptr.getOperand(0);
5724 // FIXME: 256-bit vector instructions don't require a strict alignment,
5725 // improve this code to support it better.
5726 unsigned RequiredAlign = VT.getSizeInBits()/8;
5727 SDValue Chain = LD->getChain();
5728 // Make sure the stack object alignment is at least 16 or 32.
5729 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5730 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5731 if (MFI->isFixedObjectIndex(FI)) {
5732 // Can't change the alignment. FIXME: It's possible to compute
5733 // the exact stack offset and reference FI + adjust offset instead.
5734 // If someone *really* cares about this. That's the way to implement it.
5737 MFI->setObjectAlignment(FI, RequiredAlign);
5741 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5742 // Ptr + (Offset & ~15).
5745 if ((Offset % RequiredAlign) & 3)
5747 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5749 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5750 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5752 int EltNo = (Offset - StartOffset) >> 2;
5753 unsigned NumElems = VT.getVectorNumElements();
5755 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5756 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5757 LD->getPointerInfo().getWithOffset(StartOffset),
5758 false, false, false, 0);
5760 SmallVector<int, 8> Mask;
5761 for (unsigned i = 0; i != NumElems; ++i)
5762 Mask.push_back(EltNo);
5764 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5770 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5771 /// vector of type 'VT', see if the elements can be replaced by a single large
5772 /// load which has the same value as a build_vector whose operands are 'elts'.
5774 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5776 /// FIXME: we'd also like to handle the case where the last elements are zero
5777 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5778 /// There's even a handy isZeroNode for that purpose.
5779 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5780 SDLoc &DL, SelectionDAG &DAG,
5781 bool isAfterLegalize) {
5782 EVT EltVT = VT.getVectorElementType();
5783 unsigned NumElems = Elts.size();
5785 LoadSDNode *LDBase = nullptr;
5786 unsigned LastLoadedElt = -1U;
5788 // For each element in the initializer, see if we've found a load or an undef.
5789 // If we don't find an initial load element, or later load elements are
5790 // non-consecutive, bail out.
5791 for (unsigned i = 0; i < NumElems; ++i) {
5792 SDValue Elt = Elts[i];
5794 if (!Elt.getNode() ||
5795 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5798 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5800 LDBase = cast<LoadSDNode>(Elt.getNode());
5804 if (Elt.getOpcode() == ISD::UNDEF)
5807 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5808 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5813 // If we have found an entire vector of loads and undefs, then return a large
5814 // load of the entire vector width starting at the base pointer. If we found
5815 // consecutive loads for the low half, generate a vzext_load node.
5816 if (LastLoadedElt == NumElems - 1) {
5818 if (isAfterLegalize &&
5819 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5822 SDValue NewLd = SDValue();
5824 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5825 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5826 LDBase->getPointerInfo(),
5827 LDBase->isVolatile(), LDBase->isNonTemporal(),
5828 LDBase->isInvariant(), 0);
5829 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5830 LDBase->getPointerInfo(),
5831 LDBase->isVolatile(), LDBase->isNonTemporal(),
5832 LDBase->isInvariant(), LDBase->getAlignment());
5834 if (LDBase->hasAnyUseOfValue(1)) {
5835 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5837 SDValue(NewLd.getNode(), 1));
5838 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5839 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5840 SDValue(NewLd.getNode(), 1));
5845 if (NumElems == 4 && LastLoadedElt == 1 &&
5846 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5847 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5848 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5850 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5851 LDBase->getPointerInfo(),
5852 LDBase->getAlignment(),
5853 false/*isVolatile*/, true/*ReadMem*/,
5856 // Make sure the newly-created LOAD is in the same position as LDBase in
5857 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5858 // update uses of LDBase's output chain to use the TokenFactor.
5859 if (LDBase->hasAnyUseOfValue(1)) {
5860 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5861 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5862 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5863 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5864 SDValue(ResNode.getNode(), 1));
5867 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5872 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5873 /// to generate a splat value for the following cases:
5874 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5875 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5876 /// a scalar load, or a constant.
5877 /// The VBROADCAST node is returned when a pattern is found,
5878 /// or SDValue() otherwise.
5879 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5880 SelectionDAG &DAG) {
5881 if (!Subtarget->hasFp256())
5884 MVT VT = Op.getSimpleValueType();
5887 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5888 "Unsupported vector type for broadcast.");
5893 switch (Op.getOpcode()) {
5895 // Unknown pattern found.
5898 case ISD::BUILD_VECTOR: {
5899 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5900 BitVector UndefElements;
5901 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5903 // We need a splat of a single value to use broadcast, and it doesn't
5904 // make any sense if the value is only in one element of the vector.
5905 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5909 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5910 Ld.getOpcode() == ISD::ConstantFP);
5912 // Make sure that all of the users of a non-constant load are from the
5913 // BUILD_VECTOR node.
5914 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5919 case ISD::VECTOR_SHUFFLE: {
5920 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5922 // Shuffles must have a splat mask where the first element is
5924 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5927 SDValue Sc = Op.getOperand(0);
5928 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5929 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5931 if (!Subtarget->hasInt256())
5934 // Use the register form of the broadcast instruction available on AVX2.
5935 if (VT.getSizeInBits() >= 256)
5936 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5937 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5940 Ld = Sc.getOperand(0);
5941 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5942 Ld.getOpcode() == ISD::ConstantFP);
5944 // The scalar_to_vector node and the suspected
5945 // load node must have exactly one user.
5946 // Constants may have multiple users.
5948 // AVX-512 has register version of the broadcast
5949 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5950 Ld.getValueType().getSizeInBits() >= 32;
5951 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5958 bool IsGE256 = (VT.getSizeInBits() >= 256);
5960 // Handle the broadcasting a single constant scalar from the constant pool
5961 // into a vector. On Sandybridge it is still better to load a constant vector
5962 // from the constant pool and not to broadcast it from a scalar.
5963 if (ConstSplatVal && Subtarget->hasInt256()) {
5964 EVT CVT = Ld.getValueType();
5965 assert(!CVT.isVector() && "Must not broadcast a vector type");
5966 unsigned ScalarSize = CVT.getSizeInBits();
5968 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5969 const Constant *C = nullptr;
5970 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5971 C = CI->getConstantIntValue();
5972 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5973 C = CF->getConstantFPValue();
5975 assert(C && "Invalid constant type");
5977 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5978 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5979 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5980 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5981 MachinePointerInfo::getConstantPool(),
5982 false, false, false, Alignment);
5984 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5988 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5989 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5991 // Handle AVX2 in-register broadcasts.
5992 if (!IsLoad && Subtarget->hasInt256() &&
5993 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5994 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5996 // The scalar source must be a normal load.
6000 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6001 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6003 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6004 // double since there is no vbroadcastsd xmm
6005 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6006 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6007 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6010 // Unsupported broadcast.
6014 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6015 /// underlying vector and index.
6017 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6019 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6021 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6022 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6025 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6027 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6029 // (extract_vector_elt (vector_shuffle<2,u,u,u>
6030 // (extract_subvector (v8f32 %vreg0), Constant<4>),
6033 // In this case the vector is the extract_subvector expression and the index
6034 // is 2, as specified by the shuffle.
6035 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6036 SDValue ShuffleVec = SVOp->getOperand(0);
6037 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6038 assert(ShuffleVecVT.getVectorElementType() ==
6039 ExtractedFromVec.getSimpleValueType().getVectorElementType());
6041 int ShuffleIdx = SVOp->getMaskElt(Idx);
6042 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6043 ExtractedFromVec = ShuffleVec;
6049 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6050 MVT VT = Op.getSimpleValueType();
6052 // Skip if insert_vec_elt is not supported.
6053 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6054 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6058 unsigned NumElems = Op.getNumOperands();
6062 SmallVector<unsigned, 4> InsertIndices;
6063 SmallVector<int, 8> Mask(NumElems, -1);
6065 for (unsigned i = 0; i != NumElems; ++i) {
6066 unsigned Opc = Op.getOperand(i).getOpcode();
6068 if (Opc == ISD::UNDEF)
6071 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6072 // Quit if more than 1 elements need inserting.
6073 if (InsertIndices.size() > 1)
6076 InsertIndices.push_back(i);
6080 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6081 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6082 // Quit if non-constant index.
6083 if (!isa<ConstantSDNode>(ExtIdx))
6085 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6087 // Quit if extracted from vector of different type.
6088 if (ExtractedFromVec.getValueType() != VT)
6091 if (!VecIn1.getNode())
6092 VecIn1 = ExtractedFromVec;
6093 else if (VecIn1 != ExtractedFromVec) {
6094 if (!VecIn2.getNode())
6095 VecIn2 = ExtractedFromVec;
6096 else if (VecIn2 != ExtractedFromVec)
6097 // Quit if more than 2 vectors to shuffle
6101 if (ExtractedFromVec == VecIn1)
6103 else if (ExtractedFromVec == VecIn2)
6104 Mask[i] = Idx + NumElems;
6107 if (!VecIn1.getNode())
6110 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6111 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6112 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6113 unsigned Idx = InsertIndices[i];
6114 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6115 DAG.getIntPtrConstant(Idx));
6121 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6123 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6125 MVT VT = Op.getSimpleValueType();
6126 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6127 "Unexpected type in LowerBUILD_VECTORvXi1!");
6130 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6131 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6132 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6133 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6136 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6137 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6138 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6139 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6142 bool AllContants = true;
6143 uint64_t Immediate = 0;
6144 int NonConstIdx = -1;
6145 bool IsSplat = true;
6146 unsigned NumNonConsts = 0;
6147 unsigned NumConsts = 0;
6148 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6149 SDValue In = Op.getOperand(idx);
6150 if (In.getOpcode() == ISD::UNDEF)
6152 if (!isa<ConstantSDNode>(In)) {
6153 AllContants = false;
6159 if (cast<ConstantSDNode>(In)->getZExtValue())
6160 Immediate |= (1ULL << idx);
6162 if (In != Op.getOperand(0))
6167 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6168 DAG.getConstant(Immediate, MVT::i16));
6169 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6170 DAG.getIntPtrConstant(0));
6173 if (NumNonConsts == 1 && NonConstIdx != 0) {
6176 SDValue VecAsImm = DAG.getConstant(Immediate,
6177 MVT::getIntegerVT(VT.getSizeInBits()));
6178 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6181 DstVec = DAG.getUNDEF(VT);
6182 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6183 Op.getOperand(NonConstIdx),
6184 DAG.getIntPtrConstant(NonConstIdx));
6186 if (!IsSplat && (NonConstIdx != 0))
6187 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6188 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6191 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6192 DAG.getConstant(-1, SelectVT),
6193 DAG.getConstant(0, SelectVT));
6195 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6196 DAG.getConstant((Immediate | 1), SelectVT),
6197 DAG.getConstant(Immediate, SelectVT));
6198 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6201 /// \brief Return true if \p N implements a horizontal binop and return the
6202 /// operands for the horizontal binop into V0 and V1.
6204 /// This is a helper function of PerformBUILD_VECTORCombine.
6205 /// This function checks that the build_vector \p N in input implements a
6206 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6207 /// operation to match.
6208 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6209 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6210 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6213 /// This function only analyzes elements of \p N whose indices are
6214 /// in range [BaseIdx, LastIdx).
6215 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6217 unsigned BaseIdx, unsigned LastIdx,
6218 SDValue &V0, SDValue &V1) {
6219 EVT VT = N->getValueType(0);
6221 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6222 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6223 "Invalid Vector in input!");
6225 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6226 bool CanFold = true;
6227 unsigned ExpectedVExtractIdx = BaseIdx;
6228 unsigned NumElts = LastIdx - BaseIdx;
6229 V0 = DAG.getUNDEF(VT);
6230 V1 = DAG.getUNDEF(VT);
6232 // Check if N implements a horizontal binop.
6233 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6234 SDValue Op = N->getOperand(i + BaseIdx);
6237 if (Op->getOpcode() == ISD::UNDEF) {
6238 // Update the expected vector extract index.
6239 if (i * 2 == NumElts)
6240 ExpectedVExtractIdx = BaseIdx;
6241 ExpectedVExtractIdx += 2;
6245 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6250 SDValue Op0 = Op.getOperand(0);
6251 SDValue Op1 = Op.getOperand(1);
6253 // Try to match the following pattern:
6254 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6255 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6256 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6257 Op0.getOperand(0) == Op1.getOperand(0) &&
6258 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6259 isa<ConstantSDNode>(Op1.getOperand(1)));
6263 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6264 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6266 if (i * 2 < NumElts) {
6267 if (V0.getOpcode() == ISD::UNDEF)
6268 V0 = Op0.getOperand(0);
6270 if (V1.getOpcode() == ISD::UNDEF)
6271 V1 = Op0.getOperand(0);
6272 if (i * 2 == NumElts)
6273 ExpectedVExtractIdx = BaseIdx;
6276 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6277 if (I0 == ExpectedVExtractIdx)
6278 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6279 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6280 // Try to match the following dag sequence:
6281 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6282 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6286 ExpectedVExtractIdx += 2;
6292 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6293 /// a concat_vector.
6295 /// This is a helper function of PerformBUILD_VECTORCombine.
6296 /// This function expects two 256-bit vectors called V0 and V1.
6297 /// At first, each vector is split into two separate 128-bit vectors.
6298 /// Then, the resulting 128-bit vectors are used to implement two
6299 /// horizontal binary operations.
6301 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6303 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6304 /// the two new horizontal binop.
6305 /// When Mode is set, the first horizontal binop dag node would take as input
6306 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6307 /// horizontal binop dag node would take as input the lower 128-bit of V1
6308 /// and the upper 128-bit of V1.
6310 /// HADD V0_LO, V0_HI
6311 /// HADD V1_LO, V1_HI
6313 /// Otherwise, the first horizontal binop dag node takes as input the lower
6314 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6315 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6317 /// HADD V0_LO, V1_LO
6318 /// HADD V0_HI, V1_HI
6320 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6321 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6322 /// the upper 128-bits of the result.
6323 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6324 SDLoc DL, SelectionDAG &DAG,
6325 unsigned X86Opcode, bool Mode,
6326 bool isUndefLO, bool isUndefHI) {
6327 EVT VT = V0.getValueType();
6328 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6329 "Invalid nodes in input!");
6331 unsigned NumElts = VT.getVectorNumElements();
6332 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6333 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6334 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6335 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6336 EVT NewVT = V0_LO.getValueType();
6338 SDValue LO = DAG.getUNDEF(NewVT);
6339 SDValue HI = DAG.getUNDEF(NewVT);
6342 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6343 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6344 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6345 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6346 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6348 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6349 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6350 V1_LO->getOpcode() != ISD::UNDEF))
6351 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6353 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6354 V1_HI->getOpcode() != ISD::UNDEF))
6355 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6358 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6361 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6362 /// sequence of 'vadd + vsub + blendi'.
6363 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6364 const X86Subtarget *Subtarget) {
6366 EVT VT = BV->getValueType(0);
6367 unsigned NumElts = VT.getVectorNumElements();
6368 SDValue InVec0 = DAG.getUNDEF(VT);
6369 SDValue InVec1 = DAG.getUNDEF(VT);
6371 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6372 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6374 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6375 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6376 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6379 // Odd-numbered elements in the input build vector are obtained from
6380 // adding two integer/float elements.
6381 // Even-numbered elements in the input build vector are obtained from
6382 // subtracting two integer/float elements.
6383 unsigned ExpectedOpcode = ISD::FSUB;
6384 unsigned NextExpectedOpcode = ISD::FADD;
6385 bool AddFound = false;
6386 bool SubFound = false;
6388 for (unsigned i = 0, e = NumElts; i != e; i++) {
6389 SDValue Op = BV->getOperand(i);
6391 // Skip 'undef' values.
6392 unsigned Opcode = Op.getOpcode();
6393 if (Opcode == ISD::UNDEF) {
6394 std::swap(ExpectedOpcode, NextExpectedOpcode);
6398 // Early exit if we found an unexpected opcode.
6399 if (Opcode != ExpectedOpcode)
6402 SDValue Op0 = Op.getOperand(0);
6403 SDValue Op1 = Op.getOperand(1);
6405 // Try to match the following pattern:
6406 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6407 // Early exit if we cannot match that sequence.
6408 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6409 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6410 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6411 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6412 Op0.getOperand(1) != Op1.getOperand(1))
6415 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6419 // We found a valid add/sub node. Update the information accordingly.
6425 // Update InVec0 and InVec1.
6426 if (InVec0.getOpcode() == ISD::UNDEF)
6427 InVec0 = Op0.getOperand(0);
6428 if (InVec1.getOpcode() == ISD::UNDEF)
6429 InVec1 = Op1.getOperand(0);
6431 // Make sure that operands in input to each add/sub node always
6432 // come from a same pair of vectors.
6433 if (InVec0 != Op0.getOperand(0)) {
6434 if (ExpectedOpcode == ISD::FSUB)
6437 // FADD is commutable. Try to commute the operands
6438 // and then test again.
6439 std::swap(Op0, Op1);
6440 if (InVec0 != Op0.getOperand(0))
6444 if (InVec1 != Op1.getOperand(0))
6447 // Update the pair of expected opcodes.
6448 std::swap(ExpectedOpcode, NextExpectedOpcode);
6451 // Don't try to fold this build_vector into a VSELECT if it has
6452 // too many UNDEF operands.
6453 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6454 InVec1.getOpcode() != ISD::UNDEF) {
6455 // Emit a sequence of vector add and sub followed by a VSELECT.
6456 // The new VSELECT will be lowered into a BLENDI.
6457 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6458 // and emit a single ADDSUB instruction.
6459 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6460 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6462 // Construct the VSELECT mask.
6463 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6464 EVT SVT = MaskVT.getVectorElementType();
6465 unsigned SVTBits = SVT.getSizeInBits();
6466 SmallVector<SDValue, 8> Ops;
6468 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6469 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6470 APInt::getAllOnesValue(SVTBits);
6471 SDValue Constant = DAG.getConstant(Value, SVT);
6472 Ops.push_back(Constant);
6475 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6476 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6482 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6483 const X86Subtarget *Subtarget) {
6485 EVT VT = N->getValueType(0);
6486 unsigned NumElts = VT.getVectorNumElements();
6487 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6488 SDValue InVec0, InVec1;
6490 // Try to match an ADDSUB.
6491 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6492 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6493 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6494 if (Value.getNode())
6498 // Try to match horizontal ADD/SUB.
6499 unsigned NumUndefsLO = 0;
6500 unsigned NumUndefsHI = 0;
6501 unsigned Half = NumElts/2;
6503 // Count the number of UNDEF operands in the build_vector in input.
6504 for (unsigned i = 0, e = Half; i != e; ++i)
6505 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6508 for (unsigned i = Half, e = NumElts; i != e; ++i)
6509 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6512 // Early exit if this is either a build_vector of all UNDEFs or all the
6513 // operands but one are UNDEF.
6514 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6517 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6518 // Try to match an SSE3 float HADD/HSUB.
6519 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6520 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6522 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6523 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6524 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6525 // Try to match an SSSE3 integer HADD/HSUB.
6526 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6527 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6529 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6530 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6533 if (!Subtarget->hasAVX())
6536 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6537 // Try to match an AVX horizontal add/sub of packed single/double
6538 // precision floating point values from 256-bit vectors.
6539 SDValue InVec2, InVec3;
6540 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6541 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6542 ((InVec0.getOpcode() == ISD::UNDEF ||
6543 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6544 ((InVec1.getOpcode() == ISD::UNDEF ||
6545 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6546 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6548 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6549 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6550 ((InVec0.getOpcode() == ISD::UNDEF ||
6551 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6552 ((InVec1.getOpcode() == ISD::UNDEF ||
6553 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6554 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6555 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6556 // Try to match an AVX2 horizontal add/sub of signed integers.
6557 SDValue InVec2, InVec3;
6559 bool CanFold = true;
6561 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6562 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6563 ((InVec0.getOpcode() == ISD::UNDEF ||
6564 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6565 ((InVec1.getOpcode() == ISD::UNDEF ||
6566 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6567 X86Opcode = X86ISD::HADD;
6568 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6569 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6570 ((InVec0.getOpcode() == ISD::UNDEF ||
6571 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6572 ((InVec1.getOpcode() == ISD::UNDEF ||
6573 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6574 X86Opcode = X86ISD::HSUB;
6579 // Fold this build_vector into a single horizontal add/sub.
6580 // Do this only if the target has AVX2.
6581 if (Subtarget->hasAVX2())
6582 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6584 // Do not try to expand this build_vector into a pair of horizontal
6585 // add/sub if we can emit a pair of scalar add/sub.
6586 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6589 // Convert this build_vector into a pair of horizontal binop followed by
6591 bool isUndefLO = NumUndefsLO == Half;
6592 bool isUndefHI = NumUndefsHI == Half;
6593 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6594 isUndefLO, isUndefHI);
6598 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6599 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6601 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6602 X86Opcode = X86ISD::HADD;
6603 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6604 X86Opcode = X86ISD::HSUB;
6605 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6606 X86Opcode = X86ISD::FHADD;
6607 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6608 X86Opcode = X86ISD::FHSUB;
6612 // Don't try to expand this build_vector into a pair of horizontal add/sub
6613 // if we can simply emit a pair of scalar add/sub.
6614 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6617 // Convert this build_vector into two horizontal add/sub followed by
6619 bool isUndefLO = NumUndefsLO == Half;
6620 bool isUndefHI = NumUndefsHI == Half;
6621 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6622 isUndefLO, isUndefHI);
6629 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6632 MVT VT = Op.getSimpleValueType();
6633 MVT ExtVT = VT.getVectorElementType();
6634 unsigned NumElems = Op.getNumOperands();
6636 // Generate vectors for predicate vectors.
6637 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6638 return LowerBUILD_VECTORvXi1(Op, DAG);
6640 // Vectors containing all zeros can be matched by pxor and xorps later
6641 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6642 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6643 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6644 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6647 return getZeroVector(VT, Subtarget, DAG, dl);
6650 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6651 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6652 // vpcmpeqd on 256-bit vectors.
6653 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6654 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6657 if (!VT.is512BitVector())
6658 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6661 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6662 if (Broadcast.getNode())
6665 unsigned EVTBits = ExtVT.getSizeInBits();
6667 unsigned NumZero = 0;
6668 unsigned NumNonZero = 0;
6669 unsigned NonZeros = 0;
6670 bool IsAllConstants = true;
6671 SmallSet<SDValue, 8> Values;
6672 for (unsigned i = 0; i < NumElems; ++i) {
6673 SDValue Elt = Op.getOperand(i);
6674 if (Elt.getOpcode() == ISD::UNDEF)
6677 if (Elt.getOpcode() != ISD::Constant &&
6678 Elt.getOpcode() != ISD::ConstantFP)
6679 IsAllConstants = false;
6680 if (X86::isZeroNode(Elt))
6683 NonZeros |= (1 << i);
6688 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6689 if (NumNonZero == 0)
6690 return DAG.getUNDEF(VT);
6692 // Special case for single non-zero, non-undef, element.
6693 if (NumNonZero == 1) {
6694 unsigned Idx = countTrailingZeros(NonZeros);
6695 SDValue Item = Op.getOperand(Idx);
6697 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6698 // the value are obviously zero, truncate the value to i32 and do the
6699 // insertion that way. Only do this if the value is non-constant or if the
6700 // value is a constant being inserted into element 0. It is cheaper to do
6701 // a constant pool load than it is to do a movd + shuffle.
6702 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6703 (!IsAllConstants || Idx == 0)) {
6704 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6706 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6707 EVT VecVT = MVT::v4i32;
6708 unsigned VecElts = 4;
6710 // Truncate the value (which may itself be a constant) to i32, and
6711 // convert it to a vector with movd (S2V+shuffle to zero extend).
6712 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6713 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6714 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6716 // Now we have our 32-bit value zero extended in the low element of
6717 // a vector. If Idx != 0, swizzle it into place.
6719 SmallVector<int, 4> Mask;
6720 Mask.push_back(Idx);
6721 for (unsigned i = 1; i != VecElts; ++i)
6723 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6726 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6730 // If we have a constant or non-constant insertion into the low element of
6731 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6732 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6733 // depending on what the source datatype is.
6736 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6738 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6739 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6740 if (VT.is256BitVector() || VT.is512BitVector()) {
6741 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6742 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6743 Item, DAG.getIntPtrConstant(0));
6745 assert(VT.is128BitVector() && "Expected an SSE value type!");
6746 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6747 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6748 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6751 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6752 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6753 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6754 if (VT.is256BitVector()) {
6755 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6756 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6758 assert(VT.is128BitVector() && "Expected an SSE value type!");
6759 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6761 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6765 // Is it a vector logical left shift?
6766 if (NumElems == 2 && Idx == 1 &&
6767 X86::isZeroNode(Op.getOperand(0)) &&
6768 !X86::isZeroNode(Op.getOperand(1))) {
6769 unsigned NumBits = VT.getSizeInBits();
6770 return getVShift(true, VT,
6771 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6772 VT, Op.getOperand(1)),
6773 NumBits/2, DAG, *this, dl);
6776 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6779 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6780 // is a non-constant being inserted into an element other than the low one,
6781 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6782 // movd/movss) to move this into the low element, then shuffle it into
6784 if (EVTBits == 32) {
6785 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6787 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6788 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6789 SmallVector<int, 8> MaskVec;
6790 for (unsigned i = 0; i != NumElems; ++i)
6791 MaskVec.push_back(i == Idx ? 0 : 1);
6792 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6796 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6797 if (Values.size() == 1) {
6798 if (EVTBits == 32) {
6799 // Instead of a shuffle like this:
6800 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6801 // Check if it's possible to issue this instead.
6802 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6803 unsigned Idx = countTrailingZeros(NonZeros);
6804 SDValue Item = Op.getOperand(Idx);
6805 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6806 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6811 // A vector full of immediates; various special cases are already
6812 // handled, so this is best done with a single constant-pool load.
6816 // For AVX-length vectors, build the individual 128-bit pieces and use
6817 // shuffles to put them in place.
6818 if (VT.is256BitVector() || VT.is512BitVector()) {
6819 SmallVector<SDValue, 64> V;
6820 for (unsigned i = 0; i != NumElems; ++i)
6821 V.push_back(Op.getOperand(i));
6823 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6825 // Build both the lower and upper subvector.
6826 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6827 makeArrayRef(&V[0], NumElems/2));
6828 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6829 makeArrayRef(&V[NumElems / 2], NumElems/2));
6831 // Recreate the wider vector with the lower and upper part.
6832 if (VT.is256BitVector())
6833 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6834 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6837 // Let legalizer expand 2-wide build_vectors.
6838 if (EVTBits == 64) {
6839 if (NumNonZero == 1) {
6840 // One half is zero or undef.
6841 unsigned Idx = countTrailingZeros(NonZeros);
6842 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6843 Op.getOperand(Idx));
6844 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6849 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6850 if (EVTBits == 8 && NumElems == 16) {
6851 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6853 if (V.getNode()) return V;
6856 if (EVTBits == 16 && NumElems == 8) {
6857 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6859 if (V.getNode()) return V;
6862 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6863 if (EVTBits == 32 && NumElems == 4) {
6864 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6865 NumZero, DAG, Subtarget, *this);
6870 // If element VT is == 32 bits, turn it into a number of shuffles.
6871 SmallVector<SDValue, 8> V(NumElems);
6872 if (NumElems == 4 && NumZero > 0) {
6873 for (unsigned i = 0; i < 4; ++i) {
6874 bool isZero = !(NonZeros & (1 << i));
6876 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6878 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6881 for (unsigned i = 0; i < 2; ++i) {
6882 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6885 V[i] = V[i*2]; // Must be a zero vector.
6888 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6891 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6894 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6899 bool Reverse1 = (NonZeros & 0x3) == 2;
6900 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6904 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6905 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6907 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6910 if (Values.size() > 1 && VT.is128BitVector()) {
6911 // Check for a build vector of consecutive loads.
6912 for (unsigned i = 0; i < NumElems; ++i)
6913 V[i] = Op.getOperand(i);
6915 // Check for elements which are consecutive loads.
6916 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6920 // Check for a build vector from mostly shuffle plus few inserting.
6921 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6925 // For SSE 4.1, use insertps to put the high elements into the low element.
6926 if (getSubtarget()->hasSSE41()) {
6928 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6929 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6931 Result = DAG.getUNDEF(VT);
6933 for (unsigned i = 1; i < NumElems; ++i) {
6934 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6935 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6936 Op.getOperand(i), DAG.getIntPtrConstant(i));
6941 // Otherwise, expand into a number of unpckl*, start by extending each of
6942 // our (non-undef) elements to the full vector width with the element in the
6943 // bottom slot of the vector (which generates no code for SSE).
6944 for (unsigned i = 0; i < NumElems; ++i) {
6945 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6946 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6948 V[i] = DAG.getUNDEF(VT);
6951 // Next, we iteratively mix elements, e.g. for v4f32:
6952 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6953 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6954 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6955 unsigned EltStride = NumElems >> 1;
6956 while (EltStride != 0) {
6957 for (unsigned i = 0; i < EltStride; ++i) {
6958 // If V[i+EltStride] is undef and this is the first round of mixing,
6959 // then it is safe to just drop this shuffle: V[i] is already in the
6960 // right place, the one element (since it's the first round) being
6961 // inserted as undef can be dropped. This isn't safe for successive
6962 // rounds because they will permute elements within both vectors.
6963 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6964 EltStride == NumElems/2)
6967 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6976 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6977 // to create 256-bit vectors from two other 128-bit ones.
6978 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6980 MVT ResVT = Op.getSimpleValueType();
6982 assert((ResVT.is256BitVector() ||
6983 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6985 SDValue V1 = Op.getOperand(0);
6986 SDValue V2 = Op.getOperand(1);
6987 unsigned NumElems = ResVT.getVectorNumElements();
6988 if(ResVT.is256BitVector())
6989 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6991 if (Op.getNumOperands() == 4) {
6992 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6993 ResVT.getVectorNumElements()/2);
6994 SDValue V3 = Op.getOperand(2);
6995 SDValue V4 = Op.getOperand(3);
6996 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6997 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6999 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7002 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7003 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7004 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7005 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7006 Op.getNumOperands() == 4)));
7008 // AVX can use the vinsertf128 instruction to create 256-bit vectors
7009 // from two other 128-bit ones.
7011 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7012 return LowerAVXCONCAT_VECTORS(Op, DAG);
7016 //===----------------------------------------------------------------------===//
7017 // Vector shuffle lowering
7019 // This is an experimental code path for lowering vector shuffles on x86. It is
7020 // designed to handle arbitrary vector shuffles and blends, gracefully
7021 // degrading performance as necessary. It works hard to recognize idiomatic
7022 // shuffles and lower them to optimal instruction patterns without leaving
7023 // a framework that allows reasonably efficient handling of all vector shuffle
7025 //===----------------------------------------------------------------------===//
7027 /// \brief Tiny helper function to identify a no-op mask.
7029 /// This is a somewhat boring predicate function. It checks whether the mask
7030 /// array input, which is assumed to be a single-input shuffle mask of the kind
7031 /// used by the X86 shuffle instructions (not a fully general
7032 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7033 /// in-place shuffle are 'no-op's.
7034 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7035 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7036 if (Mask[i] != -1 && Mask[i] != i)
7041 /// \brief Helper function to classify a mask as a single-input mask.
7043 /// This isn't a generic single-input test because in the vector shuffle
7044 /// lowering we canonicalize single inputs to be the first input operand. This
7045 /// means we can more quickly test for a single input by only checking whether
7046 /// an input from the second operand exists. We also assume that the size of
7047 /// mask corresponds to the size of the input vectors which isn't true in the
7048 /// fully general case.
7049 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7051 if (M >= (int)Mask.size())
7056 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7058 /// This helper function produces an 8-bit shuffle immediate corresponding to
7059 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7060 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7063 /// NB: We rely heavily on "undef" masks preserving the input lane.
7064 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7065 SelectionDAG &DAG) {
7066 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7067 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7068 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7069 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7070 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7073 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7074 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7075 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7076 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7077 return DAG.getConstant(Imm, MVT::i8);
7080 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7082 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7083 /// support for floating point shuffles but not integer shuffles. These
7084 /// instructions will incur a domain crossing penalty on some chips though so
7085 /// it is better to avoid lowering through this for integer vectors where
7087 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7088 const X86Subtarget *Subtarget,
7089 SelectionDAG &DAG) {
7091 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7092 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7093 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7094 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7095 ArrayRef<int> Mask = SVOp->getMask();
7096 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7098 if (isSingleInputShuffleMask(Mask)) {
7099 // Straight shuffle of a single input vector. Simulate this by using the
7100 // single input as both of the "inputs" to this instruction..
7101 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7102 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7103 DAG.getConstant(SHUFPDMask, MVT::i8));
7105 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7106 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7108 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7109 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7110 DAG.getConstant(SHUFPDMask, MVT::i8));
7113 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7115 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7116 /// the integer unit to minimize domain crossing penalties. However, for blends
7117 /// it falls back to the floating point shuffle operation with appropriate bit
7119 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7120 const X86Subtarget *Subtarget,
7121 SelectionDAG &DAG) {
7123 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7124 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7125 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7126 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7127 ArrayRef<int> Mask = SVOp->getMask();
7128 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7130 if (isSingleInputShuffleMask(Mask)) {
7131 // Straight shuffle of a single input vector. For everything from SSE2
7132 // onward this has a single fast instruction with no scary immediates.
7133 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7134 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7135 int WidenedMask[4] = {
7136 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7137 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7139 ISD::BITCAST, DL, MVT::v2i64,
7140 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7141 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7144 // We implement this with SHUFPD which is pretty lame because it will likely
7145 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7146 // However, all the alternatives are still more cycles and newer chips don't
7147 // have this problem. It would be really nice if x86 had better shuffles here.
7148 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7149 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7150 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7151 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7154 /// \brief Lower 4-lane 32-bit floating point shuffles.
7156 /// Uses instructions exclusively from the floating point unit to minimize
7157 /// domain crossing penalties, as these are sufficient to implement all v4f32
7159 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7160 const X86Subtarget *Subtarget,
7161 SelectionDAG &DAG) {
7163 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7164 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7165 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7166 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7167 ArrayRef<int> Mask = SVOp->getMask();
7168 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7170 SDValue LowV = V1, HighV = V2;
7171 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7174 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7176 if (NumV2Elements == 0)
7177 // Straight shuffle of a single input vector. We pass the input vector to
7178 // both operands to simulate this with a SHUFPS.
7179 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7180 getV4X86ShuffleImm8ForMask(Mask, DAG));
7182 if (NumV2Elements == 1) {
7184 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7186 // Compute the index adjacent to V2Index and in the same half by toggling
7188 int V2AdjIndex = V2Index ^ 1;
7190 if (Mask[V2AdjIndex] == -1) {
7191 // Handles all the cases where we have a single V2 element and an undef.
7192 // This will only ever happen in the high lanes because we commute the
7193 // vector otherwise.
7195 std::swap(LowV, HighV);
7196 NewMask[V2Index] -= 4;
7198 // Handle the case where the V2 element ends up adjacent to a V1 element.
7199 // To make this work, blend them together as the first step.
7200 int V1Index = V2AdjIndex;
7201 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7202 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7203 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7205 // Now proceed to reconstruct the final blend as we have the necessary
7206 // high or low half formed.
7213 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7214 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7216 } else if (NumV2Elements == 2) {
7217 if (Mask[0] < 4 && Mask[1] < 4) {
7218 // Handle the easy case where we have V1 in the low lanes and V2 in the
7219 // high lanes. We never see this reversed because we sort the shuffle.
7223 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7224 // trying to place elements directly, just blend them and set up the final
7225 // shuffle to place them.
7227 // The first two blend mask elements are for V1, the second two are for
7229 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7230 Mask[2] < 4 ? Mask[2] : Mask[3],
7231 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7232 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7233 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7234 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7236 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7239 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7240 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7241 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7242 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7245 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7246 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7249 /// \brief Lower 4-lane i32 vector shuffles.
7251 /// We try to handle these with integer-domain shuffles where we can, but for
7252 /// blends we use the floating point domain blend instructions.
7253 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7254 const X86Subtarget *Subtarget,
7255 SelectionDAG &DAG) {
7257 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7258 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7259 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7260 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7261 ArrayRef<int> Mask = SVOp->getMask();
7262 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7264 if (isSingleInputShuffleMask(Mask))
7265 // Straight shuffle of a single input vector. For everything from SSE2
7266 // onward this has a single fast instruction with no scary immediates.
7267 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7268 getV4X86ShuffleImm8ForMask(Mask, DAG));
7270 // We implement this with SHUFPS because it can blend from two vectors.
7271 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7272 // up the inputs, bypassing domain shift penalties that we would encur if we
7273 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7275 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7276 DAG.getVectorShuffle(
7278 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7279 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7282 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7283 /// shuffle lowering, and the most complex part.
7285 /// The lowering strategy is to try to form pairs of input lanes which are
7286 /// targeted at the same half of the final vector, and then use a dword shuffle
7287 /// to place them onto the right half, and finally unpack the paired lanes into
7288 /// their final position.
7290 /// The exact breakdown of how to form these dword pairs and align them on the
7291 /// correct sides is really tricky. See the comments within the function for
7292 /// more of the details.
7293 static SDValue lowerV8I16SingleInputVectorShuffle(
7294 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7295 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7296 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7297 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7298 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7300 SmallVector<int, 4> LoInputs;
7301 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7302 [](int M) { return M >= 0; });
7303 std::sort(LoInputs.begin(), LoInputs.end());
7304 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7305 SmallVector<int, 4> HiInputs;
7306 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7307 [](int M) { return M >= 0; });
7308 std::sort(HiInputs.begin(), HiInputs.end());
7309 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7311 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7312 int NumHToL = LoInputs.size() - NumLToL;
7314 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7315 int NumHToH = HiInputs.size() - NumLToH;
7316 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7317 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7318 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7319 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7321 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7322 // such inputs we can swap two of the dwords across the half mark and end up
7323 // with <=2 inputs to each half in each half. Once there, we can fall through
7324 // to the generic code below. For example:
7326 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7327 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7329 // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7331 auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7332 int ThreeInputHalfSum, int OneInputHalfOffset) {
7333 // Compute the index of dword with only one word among the three inputs in
7334 // a half by taking the sum of the half with three inputs and subtracting
7335 // the sum of the actual three inputs. The difference is the remaining
7337 int DWordA = (ThreeInputHalfSum -
7338 std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7340 int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7342 int PSHUFDMask[] = {0, 1, 2, 3};
7343 PSHUFDMask[DWordA] = DWordB;
7344 PSHUFDMask[DWordB] = DWordA;
7345 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7346 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7347 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7348 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7350 // Adjust the mask to match the new locations of A and B.
7352 if (M != -1 && M/2 == DWordA)
7353 M = 2 * DWordB + M % 2;
7354 else if (M != -1 && M/2 == DWordB)
7355 M = 2 * DWordA + M % 2;
7357 // Recurse back into this routine to re-compute state now that this isn't
7358 // a 3 and 1 problem.
7359 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7362 if (NumLToL == 3 && NumHToL == 1)
7363 return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7364 else if (NumLToL == 1 && NumHToL == 3)
7365 return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7366 else if (NumLToH == 1 && NumHToH == 3)
7367 return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7368 else if (NumLToH == 3 && NumHToH == 1)
7369 return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7371 // At this point there are at most two inputs to the low and high halves from
7372 // each half. That means the inputs can always be grouped into dwords and
7373 // those dwords can then be moved to the correct half with a dword shuffle.
7374 // We use at most one low and one high word shuffle to collect these paired
7375 // inputs into dwords, and finally a dword shuffle to place them.
7376 int PSHUFLMask[4] = {-1, -1, -1, -1};
7377 int PSHUFHMask[4] = {-1, -1, -1, -1};
7378 int PSHUFDMask[4] = {-1, -1, -1, -1};
7380 // First fix the masks for all the inputs that are staying in their
7381 // original halves. This will then dictate the targets of the cross-half
7383 auto fixInPlaceInputs = [&PSHUFDMask](
7384 ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7385 MutableArrayRef<int> HalfMask, int HalfOffset) {
7386 if (InPlaceInputs.empty())
7388 if (InPlaceInputs.size() == 1) {
7389 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7390 InPlaceInputs[0] - HalfOffset;
7391 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7395 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7396 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7397 InPlaceInputs[0] - HalfOffset;
7398 // Put the second input next to the first so that they are packed into
7399 // a dword. We find the adjacent index by toggling the low bit.
7400 int AdjIndex = InPlaceInputs[0] ^ 1;
7401 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7402 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7403 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7405 if (!HToLInputs.empty())
7406 fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7407 if (!LToHInputs.empty())
7408 fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7410 // Now gather the cross-half inputs and place them into a free dword of
7411 // their target half.
7412 // FIXME: This operation could almost certainly be simplified dramatically to
7413 // look more like the 3-1 fixing operation.
7414 auto moveInputsToRightHalf = [&PSHUFDMask](
7415 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7416 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7417 int SourceOffset, int DestOffset) {
7418 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7419 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7421 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7423 int LowWord = Word & ~1;
7424 int HighWord = Word | 1;
7425 return isWordClobbered(SourceHalfMask, LowWord) ||
7426 isWordClobbered(SourceHalfMask, HighWord);
7429 if (IncomingInputs.empty())
7432 if (ExistingInputs.empty()) {
7433 // Map any dwords with inputs from them into the right half.
7434 for (int Input : IncomingInputs) {
7435 // If the source half mask maps over the inputs, turn those into
7436 // swaps and use the swapped lane.
7437 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7438 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7439 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7440 Input - SourceOffset;
7441 // We have to swap the uses in our half mask in one sweep.
7442 for (int &M : HalfMask)
7443 if (M == SourceHalfMask[Input - SourceOffset])
7445 else if (M == Input)
7446 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7448 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7449 Input - SourceOffset &&
7450 "Previous placement doesn't match!");
7452 // Note that this correctly re-maps both when we do a swap and when
7453 // we observe the other side of the swap above. We rely on that to
7454 // avoid swapping the members of the input list directly.
7455 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7458 // Map the input's dword into the correct half.
7459 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7460 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7462 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7464 "Previous placement doesn't match!");
7467 // And just directly shift any other-half mask elements to be same-half
7468 // as we will have mirrored the dword containing the element into the
7469 // same position within that half.
7470 for (int &M : HalfMask)
7471 if (M >= SourceOffset && M < SourceOffset + 4) {
7472 M = M - SourceOffset + DestOffset;
7473 assert(M >= 0 && "This should never wrap below zero!");
7478 // Ensure we have the input in a viable dword of its current half. This
7479 // is particularly tricky because the original position may be clobbered
7480 // by inputs being moved and *staying* in that half.
7481 if (IncomingInputs.size() == 1) {
7482 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7483 int InputFixed = std::find(std::begin(SourceHalfMask),
7484 std::end(SourceHalfMask), -1) -
7485 std::begin(SourceHalfMask) + SourceOffset;
7486 SourceHalfMask[InputFixed - SourceOffset] =
7487 IncomingInputs[0] - SourceOffset;
7488 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7490 IncomingInputs[0] = InputFixed;
7492 } else if (IncomingInputs.size() == 2) {
7493 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7494 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7495 int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7496 assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7497 "Not all dwords can be clobbered!");
7498 SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7499 SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7500 for (int &M : HalfMask)
7501 if (M == IncomingInputs[0])
7502 M = SourceDWordBase + SourceOffset;
7503 else if (M == IncomingInputs[1])
7504 M = SourceDWordBase + 1 + SourceOffset;
7505 IncomingInputs[0] = SourceDWordBase + SourceOffset;
7506 IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7509 llvm_unreachable("Unhandled input size!");
7512 // Now hoist the DWord down to the right half.
7513 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7514 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7515 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7516 for (int Input : IncomingInputs)
7517 std::replace(HalfMask.begin(), HalfMask.end(), Input,
7518 FreeDWord * 2 + Input % 2);
7520 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7521 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7522 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7523 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7525 // Now enact all the shuffles we've computed to move the inputs into their
7527 if (!isNoopShuffleMask(PSHUFLMask))
7528 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7529 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7530 if (!isNoopShuffleMask(PSHUFHMask))
7531 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7532 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7533 if (!isNoopShuffleMask(PSHUFDMask))
7534 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7535 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7536 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7537 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7539 // At this point, each half should contain all its inputs, and we can then
7540 // just shuffle them into their final position.
7541 assert(std::count_if(LoMask.begin(), LoMask.end(),
7542 [](int M) { return M >= 4; }) == 0 &&
7543 "Failed to lift all the high half inputs to the low mask!");
7544 assert(std::count_if(HiMask.begin(), HiMask.end(),
7545 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7546 "Failed to lift all the low half inputs to the high mask!");
7548 // Do a half shuffle for the low mask.
7549 if (!isNoopShuffleMask(LoMask))
7550 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7551 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7553 // Do a half shuffle with the high mask after shifting its values down.
7554 for (int &M : HiMask)
7557 if (!isNoopShuffleMask(HiMask))
7558 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7559 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7564 /// \brief Detect whether the mask pattern should be lowered through
7567 /// This essentially tests whether viewing the mask as an interleaving of two
7568 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7569 /// lowering it through interleaving is a significantly better strategy.
7570 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7571 int NumEvenInputs[2] = {0, 0};
7572 int NumOddInputs[2] = {0, 0};
7573 int NumLoInputs[2] = {0, 0};
7574 int NumHiInputs[2] = {0, 0};
7575 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7579 int InputIdx = Mask[i] >= Size;
7582 ++NumLoInputs[InputIdx];
7584 ++NumHiInputs[InputIdx];
7587 ++NumEvenInputs[InputIdx];
7589 ++NumOddInputs[InputIdx];
7592 // The minimum number of cross-input results for both the interleaved and
7593 // split cases. If interleaving results in fewer cross-input results, return
7595 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7596 NumEvenInputs[0] + NumOddInputs[1]);
7597 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7598 NumLoInputs[0] + NumHiInputs[1]);
7599 return InterleavedCrosses < SplitCrosses;
7602 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7604 /// This strategy only works when the inputs from each vector fit into a single
7605 /// half of that vector, and generally there are not so many inputs as to leave
7606 /// the in-place shuffles required highly constrained (and thus expensive). It
7607 /// shifts all the inputs into a single side of both input vectors and then
7608 /// uses an unpack to interleave these inputs in a single vector. At that
7609 /// point, we will fall back on the generic single input shuffle lowering.
7610 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7612 MutableArrayRef<int> Mask,
7613 const X86Subtarget *Subtarget,
7614 SelectionDAG &DAG) {
7615 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7616 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7617 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7618 for (int i = 0; i < 8; ++i)
7619 if (Mask[i] >= 0 && Mask[i] < 4)
7620 LoV1Inputs.push_back(i);
7621 else if (Mask[i] >= 4 && Mask[i] < 8)
7622 HiV1Inputs.push_back(i);
7623 else if (Mask[i] >= 8 && Mask[i] < 12)
7624 LoV2Inputs.push_back(i);
7625 else if (Mask[i] >= 12)
7626 HiV2Inputs.push_back(i);
7628 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7629 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7632 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7633 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7634 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7636 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7637 HiV1Inputs.size() + HiV2Inputs.size();
7639 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7640 ArrayRef<int> HiInputs, bool MoveToLo,
7642 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7643 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7644 if (BadInputs.empty())
7647 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7648 int MoveOffset = MoveToLo ? 0 : 4;
7650 if (GoodInputs.empty()) {
7651 for (int BadInput : BadInputs) {
7652 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7653 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7656 if (GoodInputs.size() == 2) {
7657 // If the low inputs are spread across two dwords, pack them into
7659 MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7660 MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7661 Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7662 Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7664 // Otherwise pin the good inputs.
7665 for (int GoodInput : GoodInputs)
7666 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7669 if (BadInputs.size() == 2) {
7670 // If we have two bad inputs then there may be either one or two good
7671 // inputs fixed in place. Find a fixed input, and then find the *other*
7672 // two adjacent indices by using modular arithmetic.
7674 std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7675 [](int M) { return M >= 0; }) -
7676 std::begin(MoveMask);
7678 (((GoodMaskIdx - MoveOffset) & ~1) + 2 % 4) + MoveOffset;
7679 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7680 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7681 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7682 MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7683 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7684 Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7686 assert(BadInputs.size() == 1 && "All sizes handled");
7687 int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
7688 std::end(MoveMask), -1) -
7689 std::begin(MoveMask);
7690 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7691 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7695 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7698 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7700 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7703 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7704 // cross-half traffic in the final shuffle.
7706 // Munge the mask to be a single-input mask after the unpack merges the
7710 M = 2 * (M % 4) + (M / 8);
7712 return DAG.getVectorShuffle(
7713 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7714 DL, MVT::v8i16, V1, V2),
7715 DAG.getUNDEF(MVT::v8i16), Mask);
7718 /// \brief Generic lowering of 8-lane i16 shuffles.
7720 /// This handles both single-input shuffles and combined shuffle/blends with
7721 /// two inputs. The single input shuffles are immediately delegated to
7722 /// a dedicated lowering routine.
7724 /// The blends are lowered in one of three fundamental ways. If there are few
7725 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7726 /// of the input is significantly cheaper when lowered as an interleaving of
7727 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7728 /// halves of the inputs separately (making them have relatively few inputs)
7729 /// and then concatenate them.
7730 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7731 const X86Subtarget *Subtarget,
7732 SelectionDAG &DAG) {
7734 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7735 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7736 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7737 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7738 ArrayRef<int> OrigMask = SVOp->getMask();
7739 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7740 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7741 MutableArrayRef<int> Mask(MaskStorage);
7743 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7745 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7746 auto isV2 = [](int M) { return M >= 8; };
7748 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7749 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7751 if (NumV2Inputs == 0)
7752 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7754 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7755 "to be V1-input shuffles.");
7757 if (NumV1Inputs + NumV2Inputs <= 4)
7758 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7760 // Check whether an interleaving lowering is likely to be more efficient.
7761 // This isn't perfect but it is a strong heuristic that tends to work well on
7762 // the kinds of shuffles that show up in practice.
7764 // FIXME: Handle 1x, 2x, and 4x interleaving.
7765 if (shouldLowerAsInterleaving(Mask)) {
7766 // FIXME: Figure out whether we should pack these into the low or high
7769 int EMask[8], OMask[8];
7770 for (int i = 0; i < 4; ++i) {
7771 EMask[i] = Mask[2*i];
7772 OMask[i] = Mask[2*i + 1];
7777 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7778 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7780 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7783 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7784 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7786 for (int i = 0; i < 4; ++i) {
7787 LoBlendMask[i] = Mask[i];
7788 HiBlendMask[i] = Mask[i + 4];
7791 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7792 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7793 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7794 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7796 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7797 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7800 /// \brief Check whether a compaction lowering can be done by dropping even
7801 /// elements and compute how many times even elements must be dropped.
7803 /// This handles shuffles which take every Nth element where N is a power of
7804 /// two. Example shuffle masks:
7806 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
7807 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
7808 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
7809 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
7810 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
7811 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
7813 /// Any of these lanes can of course be undef.
7815 /// This routine only supports N <= 3.
7816 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
7819 /// \returns N above, or the number of times even elements must be dropped if
7820 /// there is such a number. Otherwise returns zero.
7821 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
7822 // Figure out whether we're looping over two inputs or just one.
7823 bool IsSingleInput = isSingleInputShuffleMask(Mask);
7825 // The modulus for the shuffle vector entries is based on whether this is
7826 // a single input or not.
7827 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
7828 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
7829 "We should only be called with masks with a power-of-2 size!");
7831 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
7833 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
7834 // and 2^3 simultaneously. This is because we may have ambiguity with
7835 // partially undef inputs.
7836 bool ViableForN[3] = {true, true, true};
7838 for (int i = 0, e = Mask.size(); i < e; ++i) {
7839 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
7844 bool IsAnyViable = false;
7845 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
7846 if (ViableForN[j]) {
7849 // The shuffle mask must be equal to (i * 2^N) % M.
7850 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
7853 ViableForN[j] = false;
7855 // Early exit if we exhaust the possible powers of two.
7860 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
7864 // Return 0 as there is no viable power of two.
7868 /// \brief Generic lowering of v16i8 shuffles.
7870 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7871 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7872 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7873 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7875 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7876 const X86Subtarget *Subtarget,
7877 SelectionDAG &DAG) {
7879 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7880 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7881 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7882 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7883 ArrayRef<int> OrigMask = SVOp->getMask();
7884 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7885 int MaskStorage[16] = {
7886 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7887 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
7888 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
7889 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7890 MutableArrayRef<int> Mask(MaskStorage);
7891 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7892 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7894 // For single-input shuffles, there are some nicer lowering tricks we can use.
7895 if (isSingleInputShuffleMask(Mask)) {
7896 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7897 // Notably, this handles splat and partial-splat shuffles more efficiently.
7898 // However, it only makes sense if the pre-duplication shuffle simplifies
7899 // things significantly. Currently, this means we need to be able to
7900 // express the pre-duplication shuffle as an i16 shuffle.
7902 // FIXME: We should check for other patterns which can be widened into an
7903 // i16 shuffle as well.
7904 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7905 for (int i = 0; i < 16; i += 2) {
7906 if (Mask[i] != Mask[i + 1])
7911 auto tryToWidenViaDuplication = [&]() -> SDValue {
7912 if (!canWidenViaDuplication(Mask))
7914 SmallVector<int, 4> LoInputs;
7915 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7916 [](int M) { return M >= 0 && M < 8; });
7917 std::sort(LoInputs.begin(), LoInputs.end());
7918 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7920 SmallVector<int, 4> HiInputs;
7921 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7922 [](int M) { return M >= 8; });
7923 std::sort(HiInputs.begin(), HiInputs.end());
7924 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7927 bool TargetLo = LoInputs.size() >= HiInputs.size();
7928 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7929 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7931 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7932 SmallDenseMap<int, int, 8> LaneMap;
7933 for (int I : InPlaceInputs) {
7934 PreDupI16Shuffle[I/2] = I/2;
7937 int j = TargetLo ? 0 : 4, je = j + 4;
7938 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7939 // Check if j is already a shuffle of this input. This happens when
7940 // there are two adjacent bytes after we move the low one.
7941 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7942 // If we haven't yet mapped the input, search for a slot into which
7944 while (j < je && PreDupI16Shuffle[j] != -1)
7948 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7951 // Map this input with the i16 shuffle.
7952 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7955 // Update the lane map based on the mapping we ended up with.
7956 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7959 ISD::BITCAST, DL, MVT::v16i8,
7960 DAG.getVectorShuffle(MVT::v8i16, DL,
7961 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7962 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7964 // Unpack the bytes to form the i16s that will be shuffled into place.
7965 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7966 MVT::v16i8, V1, V1);
7968 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7969 for (int i = 0; i < 16; i += 2) {
7971 PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7972 assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7975 ISD::BITCAST, DL, MVT::v16i8,
7976 DAG.getVectorShuffle(MVT::v8i16, DL,
7977 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7978 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7980 if (SDValue V = tryToWidenViaDuplication())
7984 // Check whether an interleaving lowering is likely to be more efficient.
7985 // This isn't perfect but it is a strong heuristic that tends to work well on
7986 // the kinds of shuffles that show up in practice.
7988 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7989 if (shouldLowerAsInterleaving(Mask)) {
7990 // FIXME: Figure out whether we should pack these into the low or high
7993 int EMask[16], OMask[16];
7994 for (int i = 0; i < 8; ++i) {
7995 EMask[i] = Mask[2*i];
7996 OMask[i] = Mask[2*i + 1];
8001 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8002 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8004 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8007 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8008 // with PSHUFB. It is important to do this before we attempt to generate any
8009 // blends but after all of the single-input lowerings. If the single input
8010 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8011 // want to preserve that and we can DAG combine any longer sequences into
8012 // a PSHUFB in the end. But once we start blending from multiple inputs,
8013 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8014 // and there are *very* few patterns that would actually be faster than the
8015 // PSHUFB approach because of its ability to zero lanes.
8017 // FIXME: The only exceptions to the above are blends which are exact
8018 // interleavings with direct instructions supporting them. We currently don't
8019 // handle those well here.
8020 if (Subtarget->hasSSSE3()) {
8023 for (int i = 0; i < 16; ++i)
8024 if (Mask[i] == -1) {
8025 V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8027 V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8029 DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8031 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8032 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8033 if (isSingleInputShuffleMask(Mask))
8034 return V1; // Single inputs are easy.
8036 // Otherwise, blend the two.
8037 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8038 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8039 return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8042 // Check whether a compaction lowering can be done. This handles shuffles
8043 // which take every Nth element for some even N. See the helper function for
8046 // We special case these as they can be particularly efficiently handled with
8047 // the PACKUSB instruction on x86 and they show up in common patterns of
8048 // rearranging bytes to truncate wide elements.
8049 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8050 // NumEvenDrops is the power of two stride of the elements. Another way of
8051 // thinking about it is that we need to drop the even elements this many
8052 // times to get the original input.
8053 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8055 // First we need to zero all the dropped bytes.
8056 assert(NumEvenDrops <= 3 &&
8057 "No support for dropping even elements more than 3 times.");
8058 // We use the mask type to pick which bytes are preserved based on how many
8059 // elements are dropped.
8060 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8061 SDValue ByteClearMask =
8062 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8063 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8064 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8066 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8068 // Now pack things back together.
8069 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8070 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8071 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8072 for (int i = 1; i < NumEvenDrops; ++i) {
8073 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8074 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8080 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8081 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8082 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8083 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8085 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8086 MutableArrayRef<int> V1HalfBlendMask,
8087 MutableArrayRef<int> V2HalfBlendMask) {
8088 for (int i = 0; i < 8; ++i)
8089 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8090 V1HalfBlendMask[i] = HalfMask[i];
8092 } else if (HalfMask[i] >= 16) {
8093 V2HalfBlendMask[i] = HalfMask[i] - 16;
8094 HalfMask[i] = i + 8;
8097 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8098 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8100 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8102 auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8103 MutableArrayRef<int> HiBlendMask) {
8105 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8106 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8108 if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8109 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8110 std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8111 [](int M) { return M >= 0 && M % 2 == 1; })) {
8112 // Use a mask to drop the high bytes.
8113 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8114 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8115 DAG.getConstant(0x00FF, MVT::v8i16));
8117 // This will be a single vector shuffle instead of a blend so nuke V2.
8118 V2 = DAG.getUNDEF(MVT::v8i16);
8120 // Squash the masks to point directly into V1.
8121 for (int &M : LoBlendMask)
8124 for (int &M : HiBlendMask)
8128 // Otherwise just unpack the low half of V into V1 and the high half into
8129 // V2 so that we can blend them as i16s.
8130 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8131 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8132 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8133 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8136 SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8137 SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8138 return std::make_pair(BlendedLo, BlendedHi);
8140 SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8141 std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8142 std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8144 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8145 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8147 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8150 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8152 /// This routine breaks down the specific type of 128-bit shuffle and
8153 /// dispatches to the lowering routines accordingly.
8154 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8155 MVT VT, const X86Subtarget *Subtarget,
8156 SelectionDAG &DAG) {
8157 switch (VT.SimpleTy) {
8159 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8161 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8163 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8165 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8167 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8169 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8172 llvm_unreachable("Unimplemented!");
8176 /// \brief Tiny helper function to test whether adjacent masks are sequential.
8177 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
8178 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8179 if (Mask[i] + 1 != Mask[i+1])
8185 /// \brief Top-level lowering for x86 vector shuffles.
8187 /// This handles decomposition, canonicalization, and lowering of all x86
8188 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8189 /// above in helper routines. The canonicalization attempts to widen shuffles
8190 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8191 /// s.t. only one of the two inputs needs to be tested, etc.
8192 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8193 SelectionDAG &DAG) {
8194 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8195 ArrayRef<int> Mask = SVOp->getMask();
8196 SDValue V1 = Op.getOperand(0);
8197 SDValue V2 = Op.getOperand(1);
8198 MVT VT = Op.getSimpleValueType();
8199 int NumElements = VT.getVectorNumElements();
8202 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8204 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8205 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8206 if (V1IsUndef && V2IsUndef)
8207 return DAG.getUNDEF(VT);
8209 // When we create a shuffle node we put the UNDEF node to second operand,
8210 // but in some cases the first operand may be transformed to UNDEF.
8211 // In this case we should just commute the node.
8213 return DAG.getCommutedVectorShuffle(*SVOp);
8215 // Check for non-undef masks pointing at an undef vector and make the masks
8216 // undef as well. This makes it easier to match the shuffle based solely on
8220 if (M >= NumElements) {
8221 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8222 for (int &M : NewMask)
8223 if (M >= NumElements)
8225 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8228 // For integer vector shuffles, try to collapse them into a shuffle of fewer
8229 // lanes but wider integers. We cap this to not form integers larger than i64
8230 // but it might be interesting to form i128 integers to handle flipping the
8231 // low and high halves of AVX 256-bit vectors.
8232 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8233 areAdjacentMasksSequential(Mask)) {
8234 SmallVector<int, 8> NewMask;
8235 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8236 NewMask.push_back(Mask[i] / 2);
8238 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8239 VT.getVectorNumElements() / 2);
8240 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8241 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8242 return DAG.getNode(ISD::BITCAST, dl, VT,
8243 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8246 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8247 for (int M : SVOp->getMask())
8250 else if (M < NumElements)
8255 // Commute the shuffle as needed such that more elements come from V1 than
8256 // V2. This allows us to match the shuffle pattern strictly on how many
8257 // elements come from V1 without handling the symmetric cases.
8258 if (NumV2Elements > NumV1Elements)
8259 return DAG.getCommutedVectorShuffle(*SVOp);
8261 // When the number of V1 and V2 elements are the same, try to minimize the
8262 // number of uses of V2 in the low half of the vector.
8263 if (NumV1Elements == NumV2Elements) {
8264 int LowV1Elements = 0, LowV2Elements = 0;
8265 for (int M : SVOp->getMask().slice(0, NumElements / 2))
8266 if (M >= NumElements)
8270 if (LowV2Elements > LowV1Elements)
8271 return DAG.getCommutedVectorShuffle(*SVOp);
8274 // For each vector width, delegate to a specialized lowering routine.
8275 if (VT.getSizeInBits() == 128)
8276 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8278 llvm_unreachable("Unimplemented!");
8282 //===----------------------------------------------------------------------===//
8283 // Legacy vector shuffle lowering
8285 // This code is the legacy code handling vector shuffles until the above
8286 // replaces its functionality and performance.
8287 //===----------------------------------------------------------------------===//
8289 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8290 bool hasInt256, unsigned *MaskOut = nullptr) {
8291 MVT EltVT = VT.getVectorElementType();
8293 // There is no blend with immediate in AVX-512.
8294 if (VT.is512BitVector())
8297 if (!hasSSE41 || EltVT == MVT::i8)
8299 if (!hasInt256 && VT == MVT::v16i16)
8302 unsigned MaskValue = 0;
8303 unsigned NumElems = VT.getVectorNumElements();
8304 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8305 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8306 unsigned NumElemsInLane = NumElems / NumLanes;
8308 // Blend for v16i16 should be symetric for the both lanes.
8309 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8311 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8312 int EltIdx = MaskVals[i];
8314 if ((EltIdx < 0 || EltIdx == (int)i) &&
8315 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8318 if (((unsigned)EltIdx == (i + NumElems)) &&
8319 (SndLaneEltIdx < 0 ||
8320 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8321 MaskValue |= (1 << i);
8327 *MaskOut = MaskValue;
8331 // Try to lower a shuffle node into a simple blend instruction.
8332 // This function assumes isBlendMask returns true for this
8333 // SuffleVectorSDNode
8334 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8336 const X86Subtarget *Subtarget,
8337 SelectionDAG &DAG) {
8338 MVT VT = SVOp->getSimpleValueType(0);
8339 MVT EltVT = VT.getVectorElementType();
8340 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8341 Subtarget->hasInt256() && "Trying to lower a "
8342 "VECTOR_SHUFFLE to a Blend but "
8343 "with the wrong mask"));
8344 SDValue V1 = SVOp->getOperand(0);
8345 SDValue V2 = SVOp->getOperand(1);
8347 unsigned NumElems = VT.getVectorNumElements();
8349 // Convert i32 vectors to floating point if it is not AVX2.
8350 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8352 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8353 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8355 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8356 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8359 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8360 DAG.getConstant(MaskValue, MVT::i32));
8361 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8364 /// In vector type \p VT, return true if the element at index \p InputIdx
8365 /// falls on a different 128-bit lane than \p OutputIdx.
8366 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8367 unsigned OutputIdx) {
8368 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8369 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8372 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8373 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8374 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8375 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8377 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8378 SelectionDAG &DAG) {
8379 MVT VT = V1.getSimpleValueType();
8380 assert(VT.is128BitVector() || VT.is256BitVector());
8382 MVT EltVT = VT.getVectorElementType();
8383 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8384 unsigned NumElts = VT.getVectorNumElements();
8386 SmallVector<SDValue, 32> PshufbMask;
8387 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8388 int InputIdx = MaskVals[OutputIdx];
8389 unsigned InputByteIdx;
8391 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8392 InputByteIdx = 0x80;
8394 // Cross lane is not allowed.
8395 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8397 InputByteIdx = InputIdx * EltSizeInBytes;
8398 // Index is an byte offset within the 128-bit lane.
8399 InputByteIdx &= 0xf;
8402 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8403 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8404 if (InputByteIdx != 0x80)
8409 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8411 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8412 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8413 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8416 // v8i16 shuffles - Prefer shuffles in the following order:
8417 // 1. [all] pshuflw, pshufhw, optional move
8418 // 2. [ssse3] 1 x pshufb
8419 // 3. [ssse3] 2 x pshufb + 1 x por
8420 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8422 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8423 SelectionDAG &DAG) {
8424 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8425 SDValue V1 = SVOp->getOperand(0);
8426 SDValue V2 = SVOp->getOperand(1);
8428 SmallVector<int, 8> MaskVals;
8430 // Determine if more than 1 of the words in each of the low and high quadwords
8431 // of the result come from the same quadword of one of the two inputs. Undef
8432 // mask values count as coming from any quadword, for better codegen.
8434 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8435 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8436 unsigned LoQuad[] = { 0, 0, 0, 0 };
8437 unsigned HiQuad[] = { 0, 0, 0, 0 };
8438 // Indices of quads used.
8439 std::bitset<4> InputQuads;
8440 for (unsigned i = 0; i < 8; ++i) {
8441 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8442 int EltIdx = SVOp->getMaskElt(i);
8443 MaskVals.push_back(EltIdx);
8452 InputQuads.set(EltIdx / 4);
8455 int BestLoQuad = -1;
8456 unsigned MaxQuad = 1;
8457 for (unsigned i = 0; i < 4; ++i) {
8458 if (LoQuad[i] > MaxQuad) {
8460 MaxQuad = LoQuad[i];
8464 int BestHiQuad = -1;
8466 for (unsigned i = 0; i < 4; ++i) {
8467 if (HiQuad[i] > MaxQuad) {
8469 MaxQuad = HiQuad[i];
8473 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8474 // of the two input vectors, shuffle them into one input vector so only a
8475 // single pshufb instruction is necessary. If there are more than 2 input
8476 // quads, disable the next transformation since it does not help SSSE3.
8477 bool V1Used = InputQuads[0] || InputQuads[1];
8478 bool V2Used = InputQuads[2] || InputQuads[3];
8479 if (Subtarget->hasSSSE3()) {
8480 if (InputQuads.count() == 2 && V1Used && V2Used) {
8481 BestLoQuad = InputQuads[0] ? 0 : 1;
8482 BestHiQuad = InputQuads[2] ? 2 : 3;
8484 if (InputQuads.count() > 2) {
8490 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8491 // the shuffle mask. If a quad is scored as -1, that means that it contains
8492 // words from all 4 input quadwords.
8494 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8496 BestLoQuad < 0 ? 0 : BestLoQuad,
8497 BestHiQuad < 0 ? 1 : BestHiQuad
8499 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8500 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8501 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8502 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8504 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8505 // source words for the shuffle, to aid later transformations.
8506 bool AllWordsInNewV = true;
8507 bool InOrder[2] = { true, true };
8508 for (unsigned i = 0; i != 8; ++i) {
8509 int idx = MaskVals[i];
8511 InOrder[i/4] = false;
8512 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8514 AllWordsInNewV = false;
8518 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8519 if (AllWordsInNewV) {
8520 for (int i = 0; i != 8; ++i) {
8521 int idx = MaskVals[i];
8524 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8525 if ((idx != i) && idx < 4)
8527 if ((idx != i) && idx > 3)
8536 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8537 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8538 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8539 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8540 unsigned TargetMask = 0;
8541 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8542 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8543 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8544 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8545 getShufflePSHUFLWImmediate(SVOp);
8546 V1 = NewV.getOperand(0);
8547 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8551 // Promote splats to a larger type which usually leads to more efficient code.
8552 // FIXME: Is this true if pshufb is available?
8553 if (SVOp->isSplat())
8554 return PromoteSplat(SVOp, DAG);
8556 // If we have SSSE3, and all words of the result are from 1 input vector,
8557 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
8558 // is present, fall back to case 4.
8559 if (Subtarget->hasSSSE3()) {
8560 SmallVector<SDValue,16> pshufbMask;
8562 // If we have elements from both input vectors, set the high bit of the
8563 // shuffle mask element to zero out elements that come from V2 in the V1
8564 // mask, and elements that come from V1 in the V2 mask, so that the two
8565 // results can be OR'd together.
8566 bool TwoInputs = V1Used && V2Used;
8567 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8569 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8571 // Calculate the shuffle mask for the second input, shuffle it, and
8572 // OR it with the first shuffled input.
8573 CommuteVectorShuffleMask(MaskVals, 8);
8574 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8575 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8576 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8579 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8580 // and update MaskVals with new element order.
8581 std::bitset<8> InOrder;
8582 if (BestLoQuad >= 0) {
8583 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8584 for (int i = 0; i != 4; ++i) {
8585 int idx = MaskVals[i];
8588 } else if ((idx / 4) == BestLoQuad) {
8593 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8596 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8597 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8598 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8600 getShufflePSHUFLWImmediate(SVOp), DAG);
8604 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8605 // and update MaskVals with the new element order.
8606 if (BestHiQuad >= 0) {
8607 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8608 for (unsigned i = 4; i != 8; ++i) {
8609 int idx = MaskVals[i];
8612 } else if ((idx / 4) == BestHiQuad) {
8613 MaskV[i] = (idx & 3) + 4;
8617 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8620 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8621 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8622 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8624 getShufflePSHUFHWImmediate(SVOp), DAG);
8628 // In case BestHi & BestLo were both -1, which means each quadword has a word
8629 // from each of the four input quadwords, calculate the InOrder bitvector now
8630 // before falling through to the insert/extract cleanup.
8631 if (BestLoQuad == -1 && BestHiQuad == -1) {
8633 for (int i = 0; i != 8; ++i)
8634 if (MaskVals[i] < 0 || MaskVals[i] == i)
8638 // The other elements are put in the right place using pextrw and pinsrw.
8639 for (unsigned i = 0; i != 8; ++i) {
8642 int EltIdx = MaskVals[i];
8645 SDValue ExtOp = (EltIdx < 8) ?
8646 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8647 DAG.getIntPtrConstant(EltIdx)) :
8648 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8649 DAG.getIntPtrConstant(EltIdx - 8));
8650 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8651 DAG.getIntPtrConstant(i));
8656 /// \brief v16i16 shuffles
8658 /// FIXME: We only support generation of a single pshufb currently. We can
8659 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8660 /// well (e.g 2 x pshufb + 1 x por).
8662 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8663 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8664 SDValue V1 = SVOp->getOperand(0);
8665 SDValue V2 = SVOp->getOperand(1);
8668 if (V2.getOpcode() != ISD::UNDEF)
8671 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8672 return getPSHUFB(MaskVals, V1, dl, DAG);
8675 // v16i8 shuffles - Prefer shuffles in the following order:
8676 // 1. [ssse3] 1 x pshufb
8677 // 2. [ssse3] 2 x pshufb + 1 x por
8678 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
8679 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8680 const X86Subtarget* Subtarget,
8681 SelectionDAG &DAG) {
8682 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8683 SDValue V1 = SVOp->getOperand(0);
8684 SDValue V2 = SVOp->getOperand(1);
8686 ArrayRef<int> MaskVals = SVOp->getMask();
8688 // Promote splats to a larger type which usually leads to more efficient code.
8689 // FIXME: Is this true if pshufb is available?
8690 if (SVOp->isSplat())
8691 return PromoteSplat(SVOp, DAG);
8693 // If we have SSSE3, case 1 is generated when all result bytes come from
8694 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
8695 // present, fall back to case 3.
8697 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8698 if (Subtarget->hasSSSE3()) {
8699 SmallVector<SDValue,16> pshufbMask;
8701 // If all result elements are from one input vector, then only translate
8702 // undef mask values to 0x80 (zero out result) in the pshufb mask.
8704 // Otherwise, we have elements from both input vectors, and must zero out
8705 // elements that come from V2 in the first mask, and V1 in the second mask
8706 // so that we can OR them together.
8707 for (unsigned i = 0; i != 16; ++i) {
8708 int EltIdx = MaskVals[i];
8709 if (EltIdx < 0 || EltIdx >= 16)
8711 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8713 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8714 DAG.getNode(ISD::BUILD_VECTOR, dl,
8715 MVT::v16i8, pshufbMask));
8717 // As PSHUFB will zero elements with negative indices, it's safe to ignore
8718 // the 2nd operand if it's undefined or zero.
8719 if (V2.getOpcode() == ISD::UNDEF ||
8720 ISD::isBuildVectorAllZeros(V2.getNode()))
8723 // Calculate the shuffle mask for the second input, shuffle it, and
8724 // OR it with the first shuffled input.
8726 for (unsigned i = 0; i != 16; ++i) {
8727 int EltIdx = MaskVals[i];
8728 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8729 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8731 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8732 DAG.getNode(ISD::BUILD_VECTOR, dl,
8733 MVT::v16i8, pshufbMask));
8734 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8737 // No SSSE3 - Calculate in place words and then fix all out of place words
8738 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
8739 // the 16 different words that comprise the two doublequadword input vectors.
8740 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8741 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8743 for (int i = 0; i != 8; ++i) {
8744 int Elt0 = MaskVals[i*2];
8745 int Elt1 = MaskVals[i*2+1];
8747 // This word of the result is all undef, skip it.
8748 if (Elt0 < 0 && Elt1 < 0)
8751 // This word of the result is already in the correct place, skip it.
8752 if ((Elt0 == i*2) && (Elt1 == i*2+1))
8755 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8756 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8759 // If Elt0 and Elt1 are defined, are consecutive, and can be load
8760 // using a single extract together, load it and store it.
8761 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8762 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8763 DAG.getIntPtrConstant(Elt1 / 2));
8764 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8765 DAG.getIntPtrConstant(i));
8769 // If Elt1 is defined, extract it from the appropriate source. If the
8770 // source byte is not also odd, shift the extracted word left 8 bits
8771 // otherwise clear the bottom 8 bits if we need to do an or.
8773 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8774 DAG.getIntPtrConstant(Elt1 / 2));
8775 if ((Elt1 & 1) == 0)
8776 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8778 TLI.getShiftAmountTy(InsElt.getValueType())));
8780 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8781 DAG.getConstant(0xFF00, MVT::i16));
8783 // If Elt0 is defined, extract it from the appropriate source. If the
8784 // source byte is not also even, shift the extracted word right 8 bits. If
8785 // Elt1 was also defined, OR the extracted values together before
8786 // inserting them in the result.
8788 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8789 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8790 if ((Elt0 & 1) != 0)
8791 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8793 TLI.getShiftAmountTy(InsElt0.getValueType())));
8795 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8796 DAG.getConstant(0x00FF, MVT::i16));
8797 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8800 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8801 DAG.getIntPtrConstant(i));
8803 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8806 // v32i8 shuffles - Translate to VPSHUFB if possible.
8808 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8809 const X86Subtarget *Subtarget,
8810 SelectionDAG &DAG) {
8811 MVT VT = SVOp->getSimpleValueType(0);
8812 SDValue V1 = SVOp->getOperand(0);
8813 SDValue V2 = SVOp->getOperand(1);
8815 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8817 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8818 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8819 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8821 // VPSHUFB may be generated if
8822 // (1) one of input vector is undefined or zeroinitializer.
8823 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8824 // And (2) the mask indexes don't cross the 128-bit lane.
8825 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8826 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8829 if (V1IsAllZero && !V2IsAllZero) {
8830 CommuteVectorShuffleMask(MaskVals, 32);
8833 return getPSHUFB(MaskVals, V1, dl, DAG);
8836 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8837 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8838 /// done when every pair / quad of shuffle mask elements point to elements in
8839 /// the right sequence. e.g.
8840 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8842 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8843 SelectionDAG &DAG) {
8844 MVT VT = SVOp->getSimpleValueType(0);
8846 unsigned NumElems = VT.getVectorNumElements();
8849 switch (VT.SimpleTy) {
8850 default: llvm_unreachable("Unexpected!");
8853 return SDValue(SVOp, 0);
8854 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
8855 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
8856 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
8857 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
8858 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8859 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
8862 SmallVector<int, 8> MaskVec;
8863 for (unsigned i = 0; i != NumElems; i += Scale) {
8865 for (unsigned j = 0; j != Scale; ++j) {
8866 int EltIdx = SVOp->getMaskElt(i+j);
8870 StartIdx = (EltIdx / Scale);
8871 if (EltIdx != (int)(StartIdx*Scale + j))
8874 MaskVec.push_back(StartIdx);
8877 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8878 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8879 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8882 /// getVZextMovL - Return a zero-extending vector move low node.
8884 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8885 SDValue SrcOp, SelectionDAG &DAG,
8886 const X86Subtarget *Subtarget, SDLoc dl) {
8887 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8888 LoadSDNode *LD = nullptr;
8889 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8890 LD = dyn_cast<LoadSDNode>(SrcOp);
8892 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8894 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8895 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8896 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8897 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8898 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8900 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8901 return DAG.getNode(ISD::BITCAST, dl, VT,
8902 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8903 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8911 return DAG.getNode(ISD::BITCAST, dl, VT,
8912 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8913 DAG.getNode(ISD::BITCAST, dl,
8917 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8918 /// which could not be matched by any known target speficic shuffle
8920 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8922 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8923 if (NewOp.getNode())
8926 MVT VT = SVOp->getSimpleValueType(0);
8928 unsigned NumElems = VT.getVectorNumElements();
8929 unsigned NumLaneElems = NumElems / 2;
8932 MVT EltVT = VT.getVectorElementType();
8933 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8936 SmallVector<int, 16> Mask;
8937 for (unsigned l = 0; l < 2; ++l) {
8938 // Build a shuffle mask for the output, discovering on the fly which
8939 // input vectors to use as shuffle operands (recorded in InputUsed).
8940 // If building a suitable shuffle vector proves too hard, then bail
8941 // out with UseBuildVector set.
8942 bool UseBuildVector = false;
8943 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8944 unsigned LaneStart = l * NumLaneElems;
8945 for (unsigned i = 0; i != NumLaneElems; ++i) {
8946 // The mask element. This indexes into the input.
8947 int Idx = SVOp->getMaskElt(i+LaneStart);
8949 // the mask element does not index into any input vector.
8954 // The input vector this mask element indexes into.
8955 int Input = Idx / NumLaneElems;
8957 // Turn the index into an offset from the start of the input vector.
8958 Idx -= Input * NumLaneElems;
8960 // Find or create a shuffle vector operand to hold this input.
8962 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8963 if (InputUsed[OpNo] == Input)
8964 // This input vector is already an operand.
8966 if (InputUsed[OpNo] < 0) {
8967 // Create a new operand for this input vector.
8968 InputUsed[OpNo] = Input;
8973 if (OpNo >= array_lengthof(InputUsed)) {
8974 // More than two input vectors used! Give up on trying to create a
8975 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
8976 UseBuildVector = true;
8980 // Add the mask index for the new shuffle vector.
8981 Mask.push_back(Idx + OpNo * NumLaneElems);
8984 if (UseBuildVector) {
8985 SmallVector<SDValue, 16> SVOps;
8986 for (unsigned i = 0; i != NumLaneElems; ++i) {
8987 // The mask element. This indexes into the input.
8988 int Idx = SVOp->getMaskElt(i+LaneStart);
8990 SVOps.push_back(DAG.getUNDEF(EltVT));
8994 // The input vector this mask element indexes into.
8995 int Input = Idx / NumElems;
8997 // Turn the index into an offset from the start of the input vector.
8998 Idx -= Input * NumElems;
9000 // Extract the vector element by hand.
9001 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9002 SVOp->getOperand(Input),
9003 DAG.getIntPtrConstant(Idx)));
9006 // Construct the output using a BUILD_VECTOR.
9007 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9008 } else if (InputUsed[0] < 0) {
9009 // No input vectors were used! The result is undefined.
9010 Output[l] = DAG.getUNDEF(NVT);
9012 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9013 (InputUsed[0] % 2) * NumLaneElems,
9015 // If only one input was used, use an undefined vector for the other.
9016 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9017 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9018 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9019 // At least one input vector was used. Create a new shuffle vector.
9020 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9026 // Concatenate the result back
9027 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9030 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9031 /// 4 elements, and match them with several different shuffle types.
9033 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9034 SDValue V1 = SVOp->getOperand(0);
9035 SDValue V2 = SVOp->getOperand(1);
9037 MVT VT = SVOp->getSimpleValueType(0);
9039 assert(VT.is128BitVector() && "Unsupported vector size");
9041 std::pair<int, int> Locs[4];
9042 int Mask1[] = { -1, -1, -1, -1 };
9043 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9047 for (unsigned i = 0; i != 4; ++i) {
9048 int Idx = PermMask[i];
9050 Locs[i] = std::make_pair(-1, -1);
9052 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9054 Locs[i] = std::make_pair(0, NumLo);
9058 Locs[i] = std::make_pair(1, NumHi);
9060 Mask1[2+NumHi] = Idx;
9066 if (NumLo <= 2 && NumHi <= 2) {
9067 // If no more than two elements come from either vector. This can be
9068 // implemented with two shuffles. First shuffle gather the elements.
9069 // The second shuffle, which takes the first shuffle as both of its
9070 // vector operands, put the elements into the right order.
9071 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9073 int Mask2[] = { -1, -1, -1, -1 };
9075 for (unsigned i = 0; i != 4; ++i)
9076 if (Locs[i].first != -1) {
9077 unsigned Idx = (i < 2) ? 0 : 4;
9078 Idx += Locs[i].first * 2 + Locs[i].second;
9082 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9085 if (NumLo == 3 || NumHi == 3) {
9086 // Otherwise, we must have three elements from one vector, call it X, and
9087 // one element from the other, call it Y. First, use a shufps to build an
9088 // intermediate vector with the one element from Y and the element from X
9089 // that will be in the same half in the final destination (the indexes don't
9090 // matter). Then, use a shufps to build the final vector, taking the half
9091 // containing the element from Y from the intermediate, and the other half
9094 // Normalize it so the 3 elements come from V1.
9095 CommuteVectorShuffleMask(PermMask, 4);
9099 // Find the element from V2.
9101 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9102 int Val = PermMask[HiIndex];
9109 Mask1[0] = PermMask[HiIndex];
9111 Mask1[2] = PermMask[HiIndex^1];
9113 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9116 Mask1[0] = PermMask[0];
9117 Mask1[1] = PermMask[1];
9118 Mask1[2] = HiIndex & 1 ? 6 : 4;
9119 Mask1[3] = HiIndex & 1 ? 4 : 6;
9120 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9123 Mask1[0] = HiIndex & 1 ? 2 : 0;
9124 Mask1[1] = HiIndex & 1 ? 0 : 2;
9125 Mask1[2] = PermMask[2];
9126 Mask1[3] = PermMask[3];
9131 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9134 // Break it into (shuffle shuffle_hi, shuffle_lo).
9135 int LoMask[] = { -1, -1, -1, -1 };
9136 int HiMask[] = { -1, -1, -1, -1 };
9138 int *MaskPtr = LoMask;
9139 unsigned MaskIdx = 0;
9142 for (unsigned i = 0; i != 4; ++i) {
9149 int Idx = PermMask[i];
9151 Locs[i] = std::make_pair(-1, -1);
9152 } else if (Idx < 4) {
9153 Locs[i] = std::make_pair(MaskIdx, LoIdx);
9154 MaskPtr[LoIdx] = Idx;
9157 Locs[i] = std::make_pair(MaskIdx, HiIdx);
9158 MaskPtr[HiIdx] = Idx;
9163 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9164 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9165 int MaskOps[] = { -1, -1, -1, -1 };
9166 for (unsigned i = 0; i != 4; ++i)
9167 if (Locs[i].first != -1)
9168 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9169 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9172 static bool MayFoldVectorLoad(SDValue V) {
9173 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9174 V = V.getOperand(0);
9176 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9177 V = V.getOperand(0);
9178 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9179 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9180 // BUILD_VECTOR (load), undef
9181 V = V.getOperand(0);
9183 return MayFoldLoad(V);
9187 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9188 MVT VT = Op.getSimpleValueType();
9190 // Canonizalize to v2f64.
9191 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9192 return DAG.getNode(ISD::BITCAST, dl, VT,
9193 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9198 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9200 SDValue V1 = Op.getOperand(0);
9201 SDValue V2 = Op.getOperand(1);
9202 MVT VT = Op.getSimpleValueType();
9204 assert(VT != MVT::v2i64 && "unsupported shuffle type");
9206 if (HasSSE2 && VT == MVT::v2f64)
9207 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9209 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9210 return DAG.getNode(ISD::BITCAST, dl, VT,
9211 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9212 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9213 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9217 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9218 SDValue V1 = Op.getOperand(0);
9219 SDValue V2 = Op.getOperand(1);
9220 MVT VT = Op.getSimpleValueType();
9222 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9223 "unsupported shuffle type");
9225 if (V2.getOpcode() == ISD::UNDEF)
9229 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9233 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9234 SDValue V1 = Op.getOperand(0);
9235 SDValue V2 = Op.getOperand(1);
9236 MVT VT = Op.getSimpleValueType();
9237 unsigned NumElems = VT.getVectorNumElements();
9239 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9240 // operand of these instructions is only memory, so check if there's a
9241 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9243 bool CanFoldLoad = false;
9245 // Trivial case, when V2 comes from a load.
9246 if (MayFoldVectorLoad(V2))
9249 // When V1 is a load, it can be folded later into a store in isel, example:
9250 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9252 // (MOVLPSmr addr:$src1, VR128:$src2)
9253 // So, recognize this potential and also use MOVLPS or MOVLPD
9254 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9257 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9259 if (HasSSE2 && NumElems == 2)
9260 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9263 // If we don't care about the second element, proceed to use movss.
9264 if (SVOp->getMaskElt(1) != -1)
9265 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9268 // movl and movlp will both match v2i64, but v2i64 is never matched by
9269 // movl earlier because we make it strict to avoid messing with the movlp load
9270 // folding logic (see the code above getMOVLP call). Match it here then,
9271 // this is horrible, but will stay like this until we move all shuffle
9272 // matching to x86 specific nodes. Note that for the 1st condition all
9273 // types are matched with movsd.
9275 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9276 // as to remove this logic from here, as much as possible
9277 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9278 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9279 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9282 assert(VT != MVT::v4i32 && "unsupported shuffle type");
9284 // Invert the operand order and use SHUFPS to match it.
9285 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9286 getShuffleSHUFImmediate(SVOp), DAG);
9289 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9290 SelectionDAG &DAG) {
9292 MVT VT = Load->getSimpleValueType(0);
9293 MVT EVT = VT.getVectorElementType();
9294 SDValue Addr = Load->getOperand(1);
9295 SDValue NewAddr = DAG.getNode(
9296 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9297 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9300 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9301 DAG.getMachineFunction().getMachineMemOperand(
9302 Load->getMemOperand(), 0, EVT.getStoreSize()));
9306 // It is only safe to call this function if isINSERTPSMask is true for
9307 // this shufflevector mask.
9308 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9309 SelectionDAG &DAG) {
9310 // Generate an insertps instruction when inserting an f32 from memory onto a
9311 // v4f32 or when copying a member from one v4f32 to another.
9312 // We also use it for transferring i32 from one register to another,
9313 // since it simply copies the same bits.
9314 // If we're transferring an i32 from memory to a specific element in a
9315 // register, we output a generic DAG that will match the PINSRD
9317 MVT VT = SVOp->getSimpleValueType(0);
9318 MVT EVT = VT.getVectorElementType();
9319 SDValue V1 = SVOp->getOperand(0);
9320 SDValue V2 = SVOp->getOperand(1);
9321 auto Mask = SVOp->getMask();
9322 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9323 "unsupported vector type for insertps/pinsrd");
9325 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9326 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9327 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9335 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9338 // If we have 1 element from each vector, we have to check if we're
9339 // changing V1's element's place. If so, we're done. Otherwise, we
9340 // should assume we're changing V2's element's place and behave
9342 int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9343 assert(DestIndex <= INT32_MAX && "truncated destination index");
9344 if (FromV1 == FromV2 &&
9345 static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9349 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9352 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9353 "More than one element from V1 and from V2, or no elements from one "
9354 "of the vectors. This case should not have returned true from "
9359 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9362 // Get an index into the source vector in the range [0,4) (the mask is
9363 // in the range [0,8) because it can address V1 and V2)
9364 unsigned SrcIndex = Mask[DestIndex] % 4;
9365 if (MayFoldLoad(From)) {
9366 // Trivial case, when From comes from a load and is only used by the
9367 // shuffle. Make it use insertps from the vector that we need from that
9370 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9371 if (!NewLoad.getNode())
9374 if (EVT == MVT::f32) {
9375 // Create this as a scalar to vector to match the instruction pattern.
9376 SDValue LoadScalarToVector =
9377 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9378 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9379 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9381 } else { // EVT == MVT::i32
9382 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9383 // instruction, to match the PINSRD instruction, which loads an i32 to a
9384 // certain vector element.
9385 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9386 DAG.getConstant(DestIndex, MVT::i32));
9390 // Vector-element-to-vector
9391 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9392 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9395 // Reduce a vector shuffle to zext.
9396 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9397 SelectionDAG &DAG) {
9398 // PMOVZX is only available from SSE41.
9399 if (!Subtarget->hasSSE41())
9402 MVT VT = Op.getSimpleValueType();
9404 // Only AVX2 support 256-bit vector integer extending.
9405 if (!Subtarget->hasInt256() && VT.is256BitVector())
9408 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9410 SDValue V1 = Op.getOperand(0);
9411 SDValue V2 = Op.getOperand(1);
9412 unsigned NumElems = VT.getVectorNumElements();
9414 // Extending is an unary operation and the element type of the source vector
9415 // won't be equal to or larger than i64.
9416 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9417 VT.getVectorElementType() == MVT::i64)
9420 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9421 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9422 while ((1U << Shift) < NumElems) {
9423 if (SVOp->getMaskElt(1U << Shift) == 1)
9426 // The maximal ratio is 8, i.e. from i8 to i64.
9431 // Check the shuffle mask.
9432 unsigned Mask = (1U << Shift) - 1;
9433 for (unsigned i = 0; i != NumElems; ++i) {
9434 int EltIdx = SVOp->getMaskElt(i);
9435 if ((i & Mask) != 0 && EltIdx != -1)
9437 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9441 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9442 MVT NeVT = MVT::getIntegerVT(NBits);
9443 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9445 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9448 // Simplify the operand as it's prepared to be fed into shuffle.
9449 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9450 if (V1.getOpcode() == ISD::BITCAST &&
9451 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9452 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9453 V1.getOperand(0).getOperand(0)
9454 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9455 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9456 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9457 ConstantSDNode *CIdx =
9458 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9459 // If it's foldable, i.e. normal load with single use, we will let code
9460 // selection to fold it. Otherwise, we will short the conversion sequence.
9461 if (CIdx && CIdx->getZExtValue() == 0 &&
9462 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9463 MVT FullVT = V.getSimpleValueType();
9464 MVT V1VT = V1.getSimpleValueType();
9465 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9466 // The "ext_vec_elt" node is wider than the result node.
9467 // In this case we should extract subvector from V.
9468 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9469 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9470 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9471 FullVT.getVectorNumElements()/Ratio);
9472 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9473 DAG.getIntPtrConstant(0));
9475 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9479 return DAG.getNode(ISD::BITCAST, DL, VT,
9480 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9483 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9484 SelectionDAG &DAG) {
9485 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9486 MVT VT = Op.getSimpleValueType();
9488 SDValue V1 = Op.getOperand(0);
9489 SDValue V2 = Op.getOperand(1);
9491 if (isZeroShuffle(SVOp))
9492 return getZeroVector(VT, Subtarget, DAG, dl);
9494 // Handle splat operations
9495 if (SVOp->isSplat()) {
9496 // Use vbroadcast whenever the splat comes from a foldable load
9497 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9498 if (Broadcast.getNode())
9502 // Check integer expanding shuffles.
9503 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9504 if (NewOp.getNode())
9507 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9509 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9511 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9512 if (NewOp.getNode())
9513 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9514 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9515 // FIXME: Figure out a cleaner way to do this.
9516 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9517 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9518 if (NewOp.getNode()) {
9519 MVT NewVT = NewOp.getSimpleValueType();
9520 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9521 NewVT, true, false))
9522 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9525 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9526 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9527 if (NewOp.getNode()) {
9528 MVT NewVT = NewOp.getSimpleValueType();
9529 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9530 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9539 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9540 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9541 SDValue V1 = Op.getOperand(0);
9542 SDValue V2 = Op.getOperand(1);
9543 MVT VT = Op.getSimpleValueType();
9545 unsigned NumElems = VT.getVectorNumElements();
9546 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9547 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9548 bool V1IsSplat = false;
9549 bool V2IsSplat = false;
9550 bool HasSSE2 = Subtarget->hasSSE2();
9551 bool HasFp256 = Subtarget->hasFp256();
9552 bool HasInt256 = Subtarget->hasInt256();
9553 MachineFunction &MF = DAG.getMachineFunction();
9554 bool OptForSize = MF.getFunction()->getAttributes().
9555 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9557 // Check if we should use the experimental vector shuffle lowering. If so,
9558 // delegate completely to that code path.
9559 if (ExperimentalVectorShuffleLowering)
9560 return lowerVectorShuffle(Op, Subtarget, DAG);
9562 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9564 if (V1IsUndef && V2IsUndef)
9565 return DAG.getUNDEF(VT);
9567 // When we create a shuffle node we put the UNDEF node to second operand,
9568 // but in some cases the first operand may be transformed to UNDEF.
9569 // In this case we should just commute the node.
9571 return DAG.getCommutedVectorShuffle(*SVOp);
9573 // Vector shuffle lowering takes 3 steps:
9575 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9576 // narrowing and commutation of operands should be handled.
9577 // 2) Matching of shuffles with known shuffle masks to x86 target specific
9579 // 3) Rewriting of unmatched masks into new generic shuffle operations,
9580 // so the shuffle can be broken into other shuffles and the legalizer can
9581 // try the lowering again.
9583 // The general idea is that no vector_shuffle operation should be left to
9584 // be matched during isel, all of them must be converted to a target specific
9587 // Normalize the input vectors. Here splats, zeroed vectors, profitable
9588 // narrowing and commutation of operands should be handled. The actual code
9589 // doesn't include all of those, work in progress...
9590 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9591 if (NewOp.getNode())
9594 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9596 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9597 // unpckh_undef). Only use pshufd if speed is more important than size.
9598 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9599 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9600 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9601 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9603 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9604 V2IsUndef && MayFoldVectorLoad(V1))
9605 return getMOVDDup(Op, dl, V1, DAG);
9607 if (isMOVHLPS_v_undef_Mask(M, VT))
9608 return getMOVHighToLow(Op, dl, DAG);
9610 // Use to match splats
9611 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9612 (VT == MVT::v2f64 || VT == MVT::v2i64))
9613 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9615 if (isPSHUFDMask(M, VT)) {
9616 // The actual implementation will match the mask in the if above and then
9617 // during isel it can match several different instructions, not only pshufd
9618 // as its name says, sad but true, emulate the behavior for now...
9619 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9620 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9622 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9624 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9625 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9627 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9628 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9631 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9635 if (isPALIGNRMask(M, VT, Subtarget))
9636 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9637 getShufflePALIGNRImmediate(SVOp),
9640 if (isVALIGNMask(M, VT, Subtarget))
9641 return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
9642 getShuffleVALIGNImmediate(SVOp),
9645 // Check if this can be converted into a logical shift.
9646 bool isLeft = false;
9649 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9650 if (isShift && ShVal.hasOneUse()) {
9651 // If the shifted value has multiple uses, it may be cheaper to use
9652 // v_set0 + movlhps or movhlps, etc.
9653 MVT EltVT = VT.getVectorElementType();
9654 ShAmt *= EltVT.getSizeInBits();
9655 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9658 if (isMOVLMask(M, VT)) {
9659 if (ISD::isBuildVectorAllZeros(V1.getNode()))
9660 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9661 if (!isMOVLPMask(M, VT)) {
9662 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9663 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9665 if (VT == MVT::v4i32 || VT == MVT::v4f32)
9666 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9670 // FIXME: fold these into legal mask.
9671 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9672 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9674 if (isMOVHLPSMask(M, VT))
9675 return getMOVHighToLow(Op, dl, DAG);
9677 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9678 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9680 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9681 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9683 if (isMOVLPMask(M, VT))
9684 return getMOVLP(Op, dl, DAG, HasSSE2);
9686 if (ShouldXformToMOVHLPS(M, VT) ||
9687 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9688 return DAG.getCommutedVectorShuffle(*SVOp);
9691 // No better options. Use a vshldq / vsrldq.
9692 MVT EltVT = VT.getVectorElementType();
9693 ShAmt *= EltVT.getSizeInBits();
9694 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9697 bool Commuted = false;
9698 // FIXME: This should also accept a bitcast of a splat? Be careful, not
9699 // 1,1,1,1 -> v8i16 though.
9700 BitVector UndefElements;
9701 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9702 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9704 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9705 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9708 // Canonicalize the splat or undef, if present, to be on the RHS.
9709 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9710 CommuteVectorShuffleMask(M, NumElems);
9712 std::swap(V1IsSplat, V2IsSplat);
9716 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9717 // Shuffling low element of v1 into undef, just return v1.
9720 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9721 // the instruction selector will not match, so get a canonical MOVL with
9722 // swapped operands to undo the commute.
9723 return getMOVL(DAG, dl, VT, V2, V1);
9726 if (isUNPCKLMask(M, VT, HasInt256))
9727 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9729 if (isUNPCKHMask(M, VT, HasInt256))
9730 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9733 // Normalize mask so all entries that point to V2 points to its first
9734 // element then try to match unpck{h|l} again. If match, return a
9735 // new vector_shuffle with the corrected mask.p
9736 SmallVector<int, 8> NewMask(M.begin(), M.end());
9737 NormalizeMask(NewMask, NumElems);
9738 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9739 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9740 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9741 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9745 // Commute is back and try unpck* again.
9746 // FIXME: this seems wrong.
9747 CommuteVectorShuffleMask(M, NumElems);
9749 std::swap(V1IsSplat, V2IsSplat);
9751 if (isUNPCKLMask(M, VT, HasInt256))
9752 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9754 if (isUNPCKHMask(M, VT, HasInt256))
9755 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9758 // Normalize the node to match x86 shuffle ops if needed
9759 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9760 return DAG.getCommutedVectorShuffle(*SVOp);
9762 // The checks below are all present in isShuffleMaskLegal, but they are
9763 // inlined here right now to enable us to directly emit target specific
9764 // nodes, and remove one by one until they don't return Op anymore.
9766 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9767 SVOp->getSplatIndex() == 0 && V2IsUndef) {
9768 if (VT == MVT::v2f64 || VT == MVT::v2i64)
9769 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9772 if (isPSHUFHWMask(M, VT, HasInt256))
9773 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9774 getShufflePSHUFHWImmediate(SVOp),
9777 if (isPSHUFLWMask(M, VT, HasInt256))
9778 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9779 getShufflePSHUFLWImmediate(SVOp),
9783 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9785 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9787 if (isSHUFPMask(M, VT))
9788 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9789 getShuffleSHUFImmediate(SVOp), DAG);
9791 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9792 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9793 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9794 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9796 //===--------------------------------------------------------------------===//
9797 // Generate target specific nodes for 128 or 256-bit shuffles only
9798 // supported in the AVX instruction set.
9801 // Handle VMOVDDUPY permutations
9802 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9803 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9805 // Handle VPERMILPS/D* permutations
9806 if (isVPERMILPMask(M, VT)) {
9807 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9808 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9809 getShuffleSHUFImmediate(SVOp), DAG);
9810 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9811 getShuffleSHUFImmediate(SVOp), DAG);
9815 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9816 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9817 Idx*(NumElems/2), DAG, dl);
9819 // Handle VPERM2F128/VPERM2I128 permutations
9820 if (isVPERM2X128Mask(M, VT, HasFp256))
9821 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9822 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9824 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9825 return getINSERTPS(SVOp, dl, DAG);
9828 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9829 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9831 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9832 VT.is512BitVector()) {
9833 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9834 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9835 SmallVector<SDValue, 16> permclMask;
9836 for (unsigned i = 0; i != NumElems; ++i) {
9837 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9840 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9842 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9843 return DAG.getNode(X86ISD::VPERMV, dl, VT,
9844 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9845 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9846 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9849 //===--------------------------------------------------------------------===//
9850 // Since no target specific shuffle was selected for this generic one,
9851 // lower it into other known shuffles. FIXME: this isn't true yet, but
9852 // this is the plan.
9855 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9856 if (VT == MVT::v8i16) {
9857 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9858 if (NewOp.getNode())
9862 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9863 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9864 if (NewOp.getNode())
9868 if (VT == MVT::v16i8) {
9869 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9870 if (NewOp.getNode())
9874 if (VT == MVT::v32i8) {
9875 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9876 if (NewOp.getNode())
9880 // Handle all 128-bit wide vectors with 4 elements, and match them with
9881 // several different shuffle types.
9882 if (NumElems == 4 && VT.is128BitVector())
9883 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9885 // Handle general 256-bit shuffles
9886 if (VT.is256BitVector())
9887 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9892 // This function assumes its argument is a BUILD_VECTOR of constants or
9893 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9895 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9896 unsigned &MaskValue) {
9898 unsigned NumElems = BuildVector->getNumOperands();
9899 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9900 unsigned NumLanes = (NumElems - 1) / 8 + 1;
9901 unsigned NumElemsInLane = NumElems / NumLanes;
9903 // Blend for v16i16 should be symetric for the both lanes.
9904 for (unsigned i = 0; i < NumElemsInLane; ++i) {
9905 SDValue EltCond = BuildVector->getOperand(i);
9906 SDValue SndLaneEltCond =
9907 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9909 int Lane1Cond = -1, Lane2Cond = -1;
9910 if (isa<ConstantSDNode>(EltCond))
9911 Lane1Cond = !isZero(EltCond);
9912 if (isa<ConstantSDNode>(SndLaneEltCond))
9913 Lane2Cond = !isZero(SndLaneEltCond);
9915 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9916 // Lane1Cond != 0, means we want the first argument.
9917 // Lane1Cond == 0, means we want the second argument.
9918 // The encoding of this argument is 0 for the first argument, 1
9919 // for the second. Therefore, invert the condition.
9920 MaskValue |= !Lane1Cond << i;
9921 else if (Lane1Cond < 0)
9922 MaskValue |= !Lane2Cond << i;
9929 // Try to lower a vselect node into a simple blend instruction.
9930 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9931 SelectionDAG &DAG) {
9932 SDValue Cond = Op.getOperand(0);
9933 SDValue LHS = Op.getOperand(1);
9934 SDValue RHS = Op.getOperand(2);
9936 MVT VT = Op.getSimpleValueType();
9937 MVT EltVT = VT.getVectorElementType();
9938 unsigned NumElems = VT.getVectorNumElements();
9940 // There is no blend with immediate in AVX-512.
9941 if (VT.is512BitVector())
9944 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9946 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9949 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9952 // Check the mask for BLEND and build the value.
9953 unsigned MaskValue = 0;
9954 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9957 // Convert i32 vectors to floating point if it is not AVX2.
9958 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9960 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9961 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9963 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9964 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9967 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9968 DAG.getConstant(MaskValue, MVT::i32));
9969 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9972 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9973 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9974 if (BlendOp.getNode())
9977 // Some types for vselect were previously set to Expand, not Legal or
9978 // Custom. Return an empty SDValue so we fall-through to Expand, after
9979 // the Custom lowering phase.
9980 MVT VT = Op.getSimpleValueType();
9981 switch (VT.SimpleTy) {
9989 // We couldn't create a "Blend with immediate" node.
9990 // This node should still be legal, but we'll have to emit a blendv*
9995 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9996 MVT VT = Op.getSimpleValueType();
9999 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10002 if (VT.getSizeInBits() == 8) {
10003 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10004 Op.getOperand(0), Op.getOperand(1));
10005 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10006 DAG.getValueType(VT));
10007 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10010 if (VT.getSizeInBits() == 16) {
10011 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10012 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10014 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10015 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10016 DAG.getNode(ISD::BITCAST, dl,
10019 Op.getOperand(1)));
10020 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10021 Op.getOperand(0), Op.getOperand(1));
10022 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10023 DAG.getValueType(VT));
10024 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10027 if (VT == MVT::f32) {
10028 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10029 // the result back to FR32 register. It's only worth matching if the
10030 // result has a single use which is a store or a bitcast to i32. And in
10031 // the case of a store, it's not worth it if the index is a constant 0,
10032 // because a MOVSSmr can be used instead, which is smaller and faster.
10033 if (!Op.hasOneUse())
10035 SDNode *User = *Op.getNode()->use_begin();
10036 if ((User->getOpcode() != ISD::STORE ||
10037 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10038 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10039 (User->getOpcode() != ISD::BITCAST ||
10040 User->getValueType(0) != MVT::i32))
10042 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10043 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10046 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10049 if (VT == MVT::i32 || VT == MVT::i64) {
10050 // ExtractPS/pextrq works with constant index.
10051 if (isa<ConstantSDNode>(Op.getOperand(1)))
10057 /// Extract one bit from mask vector, like v16i1 or v8i1.
10058 /// AVX-512 feature.
10060 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10061 SDValue Vec = Op.getOperand(0);
10063 MVT VecVT = Vec.getSimpleValueType();
10064 SDValue Idx = Op.getOperand(1);
10065 MVT EltVT = Op.getSimpleValueType();
10067 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10069 // variable index can't be handled in mask registers,
10070 // extend vector to VR512
10071 if (!isa<ConstantSDNode>(Idx)) {
10072 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10073 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10074 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10075 ExtVT.getVectorElementType(), Ext, Idx);
10076 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10079 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10080 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10081 unsigned MaxSift = rc->getSize()*8 - 1;
10082 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10083 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10084 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10085 DAG.getConstant(MaxSift, MVT::i8));
10086 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10087 DAG.getIntPtrConstant(0));
10091 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10092 SelectionDAG &DAG) const {
10094 SDValue Vec = Op.getOperand(0);
10095 MVT VecVT = Vec.getSimpleValueType();
10096 SDValue Idx = Op.getOperand(1);
10098 if (Op.getSimpleValueType() == MVT::i1)
10099 return ExtractBitFromMaskVector(Op, DAG);
10101 if (!isa<ConstantSDNode>(Idx)) {
10102 if (VecVT.is512BitVector() ||
10103 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10104 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10107 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10108 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10109 MaskEltVT.getSizeInBits());
10111 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10112 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10113 getZeroVector(MaskVT, Subtarget, DAG, dl),
10114 Idx, DAG.getConstant(0, getPointerTy()));
10115 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10116 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10117 Perm, DAG.getConstant(0, getPointerTy()));
10122 // If this is a 256-bit vector result, first extract the 128-bit vector and
10123 // then extract the element from the 128-bit vector.
10124 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10126 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10127 // Get the 128-bit vector.
10128 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10129 MVT EltVT = VecVT.getVectorElementType();
10131 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10133 //if (IdxVal >= NumElems/2)
10134 // IdxVal -= NumElems/2;
10135 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10136 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10137 DAG.getConstant(IdxVal, MVT::i32));
10140 assert(VecVT.is128BitVector() && "Unexpected vector length");
10142 if (Subtarget->hasSSE41()) {
10143 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10148 MVT VT = Op.getSimpleValueType();
10149 // TODO: handle v16i8.
10150 if (VT.getSizeInBits() == 16) {
10151 SDValue Vec = Op.getOperand(0);
10152 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10154 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10155 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10156 DAG.getNode(ISD::BITCAST, dl,
10158 Op.getOperand(1)));
10159 // Transform it so it match pextrw which produces a 32-bit result.
10160 MVT EltVT = MVT::i32;
10161 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10162 Op.getOperand(0), Op.getOperand(1));
10163 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10164 DAG.getValueType(VT));
10165 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10168 if (VT.getSizeInBits() == 32) {
10169 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10173 // SHUFPS the element to the lowest double word, then movss.
10174 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10175 MVT VVT = Op.getOperand(0).getSimpleValueType();
10176 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10177 DAG.getUNDEF(VVT), Mask);
10178 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10179 DAG.getIntPtrConstant(0));
10182 if (VT.getSizeInBits() == 64) {
10183 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10184 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10185 // to match extract_elt for f64.
10186 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10190 // UNPCKHPD the element to the lowest double word, then movsd.
10191 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10192 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10193 int Mask[2] = { 1, -1 };
10194 MVT VVT = Op.getOperand(0).getSimpleValueType();
10195 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10196 DAG.getUNDEF(VVT), Mask);
10197 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10198 DAG.getIntPtrConstant(0));
10204 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10205 MVT VT = Op.getSimpleValueType();
10206 MVT EltVT = VT.getVectorElementType();
10209 SDValue N0 = Op.getOperand(0);
10210 SDValue N1 = Op.getOperand(1);
10211 SDValue N2 = Op.getOperand(2);
10213 if (!VT.is128BitVector())
10216 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10217 isa<ConstantSDNode>(N2)) {
10219 if (VT == MVT::v8i16)
10220 Opc = X86ISD::PINSRW;
10221 else if (VT == MVT::v16i8)
10222 Opc = X86ISD::PINSRB;
10224 Opc = X86ISD::PINSRB;
10226 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10228 if (N1.getValueType() != MVT::i32)
10229 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10230 if (N2.getValueType() != MVT::i32)
10231 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10232 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10235 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10236 // Bits [7:6] of the constant are the source select. This will always be
10237 // zero here. The DAG Combiner may combine an extract_elt index into these
10238 // bits. For example (insert (extract, 3), 2) could be matched by putting
10239 // the '3' into bits [7:6] of X86ISD::INSERTPS.
10240 // Bits [5:4] of the constant are the destination select. This is the
10241 // value of the incoming immediate.
10242 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10243 // combine either bitwise AND or insert of float 0.0 to set these bits.
10244 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10245 // Create this as a scalar to vector..
10246 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10247 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10250 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10251 // PINSR* works with constant index.
10257 /// Insert one bit to mask vector, like v16i1 or v8i1.
10258 /// AVX-512 feature.
10260 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10262 SDValue Vec = Op.getOperand(0);
10263 SDValue Elt = Op.getOperand(1);
10264 SDValue Idx = Op.getOperand(2);
10265 MVT VecVT = Vec.getSimpleValueType();
10267 if (!isa<ConstantSDNode>(Idx)) {
10268 // Non constant index. Extend source and destination,
10269 // insert element and then truncate the result.
10270 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10271 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10272 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10273 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10274 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10275 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10278 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10279 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10280 if (Vec.getOpcode() == ISD::UNDEF)
10281 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10282 DAG.getConstant(IdxVal, MVT::i8));
10283 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10284 unsigned MaxSift = rc->getSize()*8 - 1;
10285 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10286 DAG.getConstant(MaxSift, MVT::i8));
10287 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10288 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10289 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10292 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10293 MVT VT = Op.getSimpleValueType();
10294 MVT EltVT = VT.getVectorElementType();
10296 if (EltVT == MVT::i1)
10297 return InsertBitToMaskVector(Op, DAG);
10300 SDValue N0 = Op.getOperand(0);
10301 SDValue N1 = Op.getOperand(1);
10302 SDValue N2 = Op.getOperand(2);
10304 // If this is a 256-bit vector result, first extract the 128-bit vector,
10305 // insert the element into the extracted half and then place it back.
10306 if (VT.is256BitVector() || VT.is512BitVector()) {
10307 if (!isa<ConstantSDNode>(N2))
10310 // Get the desired 128-bit vector half.
10311 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10312 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10314 // Insert the element into the desired half.
10315 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10316 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10318 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10319 DAG.getConstant(IdxIn128, MVT::i32));
10321 // Insert the changed part back to the 256-bit vector
10322 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10325 if (Subtarget->hasSSE41())
10326 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10328 if (EltVT == MVT::i8)
10331 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10332 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10333 // as its second argument.
10334 if (N1.getValueType() != MVT::i32)
10335 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10336 if (N2.getValueType() != MVT::i32)
10337 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10338 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10343 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10345 MVT OpVT = Op.getSimpleValueType();
10347 // If this is a 256-bit vector result, first insert into a 128-bit
10348 // vector and then insert into the 256-bit vector.
10349 if (!OpVT.is128BitVector()) {
10350 // Insert into a 128-bit vector.
10351 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10352 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10353 OpVT.getVectorNumElements() / SizeFactor);
10355 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10357 // Insert the 128-bit vector.
10358 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10361 if (OpVT == MVT::v1i64 &&
10362 Op.getOperand(0).getValueType() == MVT::i64)
10363 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10365 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10366 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10367 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10368 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10371 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10372 // a simple subregister reference or explicit instructions to grab
10373 // upper bits of a vector.
10374 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10375 SelectionDAG &DAG) {
10377 SDValue In = Op.getOperand(0);
10378 SDValue Idx = Op.getOperand(1);
10379 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10380 MVT ResVT = Op.getSimpleValueType();
10381 MVT InVT = In.getSimpleValueType();
10383 if (Subtarget->hasFp256()) {
10384 if (ResVT.is128BitVector() &&
10385 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10386 isa<ConstantSDNode>(Idx)) {
10387 return Extract128BitVector(In, IdxVal, DAG, dl);
10389 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10390 isa<ConstantSDNode>(Idx)) {
10391 return Extract256BitVector(In, IdxVal, DAG, dl);
10397 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10398 // simple superregister reference or explicit instructions to insert
10399 // the upper bits of a vector.
10400 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10401 SelectionDAG &DAG) {
10402 if (Subtarget->hasFp256()) {
10403 SDLoc dl(Op.getNode());
10404 SDValue Vec = Op.getNode()->getOperand(0);
10405 SDValue SubVec = Op.getNode()->getOperand(1);
10406 SDValue Idx = Op.getNode()->getOperand(2);
10408 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10409 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10410 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10411 isa<ConstantSDNode>(Idx)) {
10412 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10413 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10416 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10417 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10418 isa<ConstantSDNode>(Idx)) {
10419 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10420 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10426 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10427 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10428 // one of the above mentioned nodes. It has to be wrapped because otherwise
10429 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10430 // be used to form addressing mode. These wrapped nodes will be selected
10433 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10434 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10436 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10437 // global base reg.
10438 unsigned char OpFlag = 0;
10439 unsigned WrapperKind = X86ISD::Wrapper;
10440 CodeModel::Model M = DAG.getTarget().getCodeModel();
10442 if (Subtarget->isPICStyleRIPRel() &&
10443 (M == CodeModel::Small || M == CodeModel::Kernel))
10444 WrapperKind = X86ISD::WrapperRIP;
10445 else if (Subtarget->isPICStyleGOT())
10446 OpFlag = X86II::MO_GOTOFF;
10447 else if (Subtarget->isPICStyleStubPIC())
10448 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10450 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10451 CP->getAlignment(),
10452 CP->getOffset(), OpFlag);
10454 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10455 // With PIC, the address is actually $g + Offset.
10457 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10458 DAG.getNode(X86ISD::GlobalBaseReg,
10459 SDLoc(), getPointerTy()),
10466 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10467 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10469 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10470 // global base reg.
10471 unsigned char OpFlag = 0;
10472 unsigned WrapperKind = X86ISD::Wrapper;
10473 CodeModel::Model M = DAG.getTarget().getCodeModel();
10475 if (Subtarget->isPICStyleRIPRel() &&
10476 (M == CodeModel::Small || M == CodeModel::Kernel))
10477 WrapperKind = X86ISD::WrapperRIP;
10478 else if (Subtarget->isPICStyleGOT())
10479 OpFlag = X86II::MO_GOTOFF;
10480 else if (Subtarget->isPICStyleStubPIC())
10481 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10483 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10486 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10488 // With PIC, the address is actually $g + Offset.
10490 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10491 DAG.getNode(X86ISD::GlobalBaseReg,
10492 SDLoc(), getPointerTy()),
10499 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10500 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10502 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10503 // global base reg.
10504 unsigned char OpFlag = 0;
10505 unsigned WrapperKind = X86ISD::Wrapper;
10506 CodeModel::Model M = DAG.getTarget().getCodeModel();
10508 if (Subtarget->isPICStyleRIPRel() &&
10509 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10510 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10511 OpFlag = X86II::MO_GOTPCREL;
10512 WrapperKind = X86ISD::WrapperRIP;
10513 } else if (Subtarget->isPICStyleGOT()) {
10514 OpFlag = X86II::MO_GOT;
10515 } else if (Subtarget->isPICStyleStubPIC()) {
10516 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10517 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10518 OpFlag = X86II::MO_DARWIN_NONLAZY;
10521 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10524 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10526 // With PIC, the address is actually $g + Offset.
10527 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10528 !Subtarget->is64Bit()) {
10529 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10530 DAG.getNode(X86ISD::GlobalBaseReg,
10531 SDLoc(), getPointerTy()),
10535 // For symbols that require a load from a stub to get the address, emit the
10537 if (isGlobalStubReference(OpFlag))
10538 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10539 MachinePointerInfo::getGOT(), false, false, false, 0);
10545 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10546 // Create the TargetBlockAddressAddress node.
10547 unsigned char OpFlags =
10548 Subtarget->ClassifyBlockAddressReference();
10549 CodeModel::Model M = DAG.getTarget().getCodeModel();
10550 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10551 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10553 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10556 if (Subtarget->isPICStyleRIPRel() &&
10557 (M == CodeModel::Small || M == CodeModel::Kernel))
10558 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10560 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10562 // With PIC, the address is actually $g + Offset.
10563 if (isGlobalRelativeToPICBase(OpFlags)) {
10564 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10565 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10573 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10574 int64_t Offset, SelectionDAG &DAG) const {
10575 // Create the TargetGlobalAddress node, folding in the constant
10576 // offset if it is legal.
10577 unsigned char OpFlags =
10578 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10579 CodeModel::Model M = DAG.getTarget().getCodeModel();
10581 if (OpFlags == X86II::MO_NO_FLAG &&
10582 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10583 // A direct static reference to a global.
10584 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10587 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10590 if (Subtarget->isPICStyleRIPRel() &&
10591 (M == CodeModel::Small || M == CodeModel::Kernel))
10592 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10594 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10596 // With PIC, the address is actually $g + Offset.
10597 if (isGlobalRelativeToPICBase(OpFlags)) {
10598 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10599 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10603 // For globals that require a load from a stub to get the address, emit the
10605 if (isGlobalStubReference(OpFlags))
10606 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10607 MachinePointerInfo::getGOT(), false, false, false, 0);
10609 // If there was a non-zero offset that we didn't fold, create an explicit
10610 // addition for it.
10612 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10613 DAG.getConstant(Offset, getPointerTy()));
10619 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10620 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10621 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10622 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10626 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10627 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10628 unsigned char OperandFlags, bool LocalDynamic = false) {
10629 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10630 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10632 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10633 GA->getValueType(0),
10637 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10641 SDValue Ops[] = { Chain, TGA, *InFlag };
10642 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10644 SDValue Ops[] = { Chain, TGA };
10645 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10648 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10649 MFI->setAdjustsStack(true);
10651 SDValue Flag = Chain.getValue(1);
10652 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10655 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10657 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10660 SDLoc dl(GA); // ? function entry point might be better
10661 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10662 DAG.getNode(X86ISD::GlobalBaseReg,
10663 SDLoc(), PtrVT), InFlag);
10664 InFlag = Chain.getValue(1);
10666 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10669 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10671 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10673 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10674 X86::RAX, X86II::MO_TLSGD);
10677 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10683 // Get the start address of the TLS block for this module.
10684 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10685 .getInfo<X86MachineFunctionInfo>();
10686 MFI->incNumLocalDynamicTLSAccesses();
10690 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10691 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10694 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10695 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10696 InFlag = Chain.getValue(1);
10697 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10698 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10701 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10705 unsigned char OperandFlags = X86II::MO_DTPOFF;
10706 unsigned WrapperKind = X86ISD::Wrapper;
10707 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10708 GA->getValueType(0),
10709 GA->getOffset(), OperandFlags);
10710 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10712 // Add x@dtpoff with the base.
10713 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10716 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10717 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10718 const EVT PtrVT, TLSModel::Model model,
10719 bool is64Bit, bool isPIC) {
10722 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10723 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10724 is64Bit ? 257 : 256));
10726 SDValue ThreadPointer =
10727 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10728 MachinePointerInfo(Ptr), false, false, false, 0);
10730 unsigned char OperandFlags = 0;
10731 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10733 unsigned WrapperKind = X86ISD::Wrapper;
10734 if (model == TLSModel::LocalExec) {
10735 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10736 } else if (model == TLSModel::InitialExec) {
10738 OperandFlags = X86II::MO_GOTTPOFF;
10739 WrapperKind = X86ISD::WrapperRIP;
10741 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10744 llvm_unreachable("Unexpected model");
10747 // emit "addl x@ntpoff,%eax" (local exec)
10748 // or "addl x@indntpoff,%eax" (initial exec)
10749 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10751 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10752 GA->getOffset(), OperandFlags);
10753 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10755 if (model == TLSModel::InitialExec) {
10756 if (isPIC && !is64Bit) {
10757 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10758 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10762 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10763 MachinePointerInfo::getGOT(), false, false, false, 0);
10766 // The address of the thread local variable is the add of the thread
10767 // pointer with the offset of the variable.
10768 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10772 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10774 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10775 const GlobalValue *GV = GA->getGlobal();
10777 if (Subtarget->isTargetELF()) {
10778 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10781 case TLSModel::GeneralDynamic:
10782 if (Subtarget->is64Bit())
10783 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10784 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10785 case TLSModel::LocalDynamic:
10786 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10787 Subtarget->is64Bit());
10788 case TLSModel::InitialExec:
10789 case TLSModel::LocalExec:
10790 return LowerToTLSExecModel(
10791 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10792 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10794 llvm_unreachable("Unknown TLS model.");
10797 if (Subtarget->isTargetDarwin()) {
10798 // Darwin only has one model of TLS. Lower to that.
10799 unsigned char OpFlag = 0;
10800 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10801 X86ISD::WrapperRIP : X86ISD::Wrapper;
10803 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10804 // global base reg.
10805 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10806 !Subtarget->is64Bit();
10808 OpFlag = X86II::MO_TLVP_PIC_BASE;
10810 OpFlag = X86II::MO_TLVP;
10812 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10813 GA->getValueType(0),
10814 GA->getOffset(), OpFlag);
10815 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10817 // With PIC32, the address is actually $g + Offset.
10819 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10820 DAG.getNode(X86ISD::GlobalBaseReg,
10821 SDLoc(), getPointerTy()),
10824 // Lowering the machine isd will make sure everything is in the right
10826 SDValue Chain = DAG.getEntryNode();
10827 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10828 SDValue Args[] = { Chain, Offset };
10829 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10831 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10832 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10833 MFI->setAdjustsStack(true);
10835 // And our return value (tls address) is in the standard call return value
10837 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10838 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10839 Chain.getValue(1));
10842 if (Subtarget->isTargetKnownWindowsMSVC() ||
10843 Subtarget->isTargetWindowsGNU()) {
10844 // Just use the implicit TLS architecture
10845 // Need to generate someting similar to:
10846 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10848 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
10849 // mov rcx, qword [rdx+rcx*8]
10850 // mov eax, .tls$:tlsvar
10851 // [rax+rcx] contains the address
10852 // Windows 64bit: gs:0x58
10853 // Windows 32bit: fs:__tls_array
10856 SDValue Chain = DAG.getEntryNode();
10858 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10859 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10860 // use its literal value of 0x2C.
10861 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10862 ? Type::getInt8PtrTy(*DAG.getContext(),
10864 : Type::getInt32PtrTy(*DAG.getContext(),
10868 Subtarget->is64Bit()
10869 ? DAG.getIntPtrConstant(0x58)
10870 : (Subtarget->isTargetWindowsGNU()
10871 ? DAG.getIntPtrConstant(0x2C)
10872 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10874 SDValue ThreadPointer =
10875 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10876 MachinePointerInfo(Ptr), false, false, false, 0);
10878 // Load the _tls_index variable
10879 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10880 if (Subtarget->is64Bit())
10881 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10882 IDX, MachinePointerInfo(), MVT::i32,
10883 false, false, false, 0);
10885 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10886 false, false, false, 0);
10888 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10890 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10892 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10893 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10894 false, false, false, 0);
10896 // Get the offset of start of .tls section
10897 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10898 GA->getValueType(0),
10899 GA->getOffset(), X86II::MO_SECREL);
10900 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10902 // The address of the thread local variable is the add of the thread
10903 // pointer with the offset of the variable.
10904 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10907 llvm_unreachable("TLS not implemented for this target.");
10910 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10911 /// and take a 2 x i32 value to shift plus a shift amount.
10912 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10913 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10914 MVT VT = Op.getSimpleValueType();
10915 unsigned VTBits = VT.getSizeInBits();
10917 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10918 SDValue ShOpLo = Op.getOperand(0);
10919 SDValue ShOpHi = Op.getOperand(1);
10920 SDValue ShAmt = Op.getOperand(2);
10921 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10922 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10924 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10925 DAG.getConstant(VTBits - 1, MVT::i8));
10926 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10927 DAG.getConstant(VTBits - 1, MVT::i8))
10928 : DAG.getConstant(0, VT);
10930 SDValue Tmp2, Tmp3;
10931 if (Op.getOpcode() == ISD::SHL_PARTS) {
10932 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10933 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10935 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10936 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10939 // If the shift amount is larger or equal than the width of a part we can't
10940 // rely on the results of shld/shrd. Insert a test and select the appropriate
10941 // values for large shift amounts.
10942 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10943 DAG.getConstant(VTBits, MVT::i8));
10944 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10945 AndNode, DAG.getConstant(0, MVT::i8));
10948 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10949 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10950 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10952 if (Op.getOpcode() == ISD::SHL_PARTS) {
10953 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10954 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10956 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10957 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10960 SDValue Ops[2] = { Lo, Hi };
10961 return DAG.getMergeValues(Ops, dl);
10964 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10965 SelectionDAG &DAG) const {
10966 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10968 if (SrcVT.isVector())
10971 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10972 "Unknown SINT_TO_FP to lower!");
10974 // These are really Legal; return the operand so the caller accepts it as
10976 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10978 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10979 Subtarget->is64Bit()) {
10984 unsigned Size = SrcVT.getSizeInBits()/8;
10985 MachineFunction &MF = DAG.getMachineFunction();
10986 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10987 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10988 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10990 MachinePointerInfo::getFixedStack(SSFI),
10992 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10995 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10997 SelectionDAG &DAG) const {
11001 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11003 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11005 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11007 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11009 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11010 MachineMemOperand *MMO;
11012 int SSFI = FI->getIndex();
11014 DAG.getMachineFunction()
11015 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11016 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11018 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11019 StackSlot = StackSlot.getOperand(1);
11021 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11022 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11024 Tys, Ops, SrcVT, MMO);
11027 Chain = Result.getValue(1);
11028 SDValue InFlag = Result.getValue(2);
11030 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11031 // shouldn't be necessary except that RFP cannot be live across
11032 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11033 MachineFunction &MF = DAG.getMachineFunction();
11034 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11035 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11036 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11037 Tys = DAG.getVTList(MVT::Other);
11039 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11041 MachineMemOperand *MMO =
11042 DAG.getMachineFunction()
11043 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11044 MachineMemOperand::MOStore, SSFISize, SSFISize);
11046 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11047 Ops, Op.getValueType(), MMO);
11048 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11049 MachinePointerInfo::getFixedStack(SSFI),
11050 false, false, false, 0);
11056 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11057 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11058 SelectionDAG &DAG) const {
11059 // This algorithm is not obvious. Here it is what we're trying to output:
11062 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11063 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11065 haddpd %xmm0, %xmm0
11067 pshufd $0x4e, %xmm0, %xmm1
11073 LLVMContext *Context = DAG.getContext();
11075 // Build some magic constants.
11076 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11077 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11078 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11080 SmallVector<Constant*,2> CV1;
11082 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11083 APInt(64, 0x4330000000000000ULL))));
11085 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11086 APInt(64, 0x4530000000000000ULL))));
11087 Constant *C1 = ConstantVector::get(CV1);
11088 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11090 // Load the 64-bit value into an XMM register.
11091 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11093 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11094 MachinePointerInfo::getConstantPool(),
11095 false, false, false, 16);
11096 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11097 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11100 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11101 MachinePointerInfo::getConstantPool(),
11102 false, false, false, 16);
11103 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11104 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11107 if (Subtarget->hasSSE3()) {
11108 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11109 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11111 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11112 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11114 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11115 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11119 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11120 DAG.getIntPtrConstant(0));
11123 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11124 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11125 SelectionDAG &DAG) const {
11127 // FP constant to bias correct the final result.
11128 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11131 // Load the 32-bit value into an XMM register.
11132 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11135 // Zero out the upper parts of the register.
11136 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11138 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11139 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11140 DAG.getIntPtrConstant(0));
11142 // Or the load with the bias.
11143 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11144 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11145 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11146 MVT::v2f64, Load)),
11147 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11148 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11149 MVT::v2f64, Bias)));
11150 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11151 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11152 DAG.getIntPtrConstant(0));
11154 // Subtract the bias.
11155 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11157 // Handle final rounding.
11158 EVT DestVT = Op.getValueType();
11160 if (DestVT.bitsLT(MVT::f64))
11161 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11162 DAG.getIntPtrConstant(0));
11163 if (DestVT.bitsGT(MVT::f64))
11164 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11166 // Handle final rounding.
11170 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11171 SelectionDAG &DAG) const {
11172 SDValue N0 = Op.getOperand(0);
11173 MVT SVT = N0.getSimpleValueType();
11176 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11177 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11178 "Custom UINT_TO_FP is not supported!");
11180 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11181 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11182 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11185 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11186 SelectionDAG &DAG) const {
11187 SDValue N0 = Op.getOperand(0);
11190 if (Op.getValueType().isVector())
11191 return lowerUINT_TO_FP_vec(Op, DAG);
11193 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11194 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11195 // the optimization here.
11196 if (DAG.SignBitIsZero(N0))
11197 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11199 MVT SrcVT = N0.getSimpleValueType();
11200 MVT DstVT = Op.getSimpleValueType();
11201 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11202 return LowerUINT_TO_FP_i64(Op, DAG);
11203 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11204 return LowerUINT_TO_FP_i32(Op, DAG);
11205 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11208 // Make a 64-bit buffer, and use it to build an FILD.
11209 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11210 if (SrcVT == MVT::i32) {
11211 SDValue WordOff = DAG.getConstant(4, getPointerTy());
11212 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11213 getPointerTy(), StackSlot, WordOff);
11214 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11215 StackSlot, MachinePointerInfo(),
11217 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11218 OffsetSlot, MachinePointerInfo(),
11220 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11224 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11225 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11226 StackSlot, MachinePointerInfo(),
11228 // For i64 source, we need to add the appropriate power of 2 if the input
11229 // was negative. This is the same as the optimization in
11230 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11231 // we must be careful to do the computation in x87 extended precision, not
11232 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11233 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11234 MachineMemOperand *MMO =
11235 DAG.getMachineFunction()
11236 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11237 MachineMemOperand::MOLoad, 8, 8);
11239 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11240 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11241 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11244 APInt FF(32, 0x5F800000ULL);
11246 // Check whether the sign bit is set.
11247 SDValue SignSet = DAG.getSetCC(dl,
11248 getSetCCResultType(*DAG.getContext(), MVT::i64),
11249 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11252 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11253 SDValue FudgePtr = DAG.getConstantPool(
11254 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11257 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11258 SDValue Zero = DAG.getIntPtrConstant(0);
11259 SDValue Four = DAG.getIntPtrConstant(4);
11260 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11262 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11264 // Load the value out, extending it from f32 to f80.
11265 // FIXME: Avoid the extend by constructing the right constant pool?
11266 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11267 FudgePtr, MachinePointerInfo::getConstantPool(),
11268 MVT::f32, false, false, false, 4);
11269 // Extend everything to 80 bits to force it to be done on x87.
11270 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11271 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11274 std::pair<SDValue,SDValue>
11275 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11276 bool IsSigned, bool IsReplace) const {
11279 EVT DstTy = Op.getValueType();
11281 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11282 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11286 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11287 DstTy.getSimpleVT() >= MVT::i16 &&
11288 "Unknown FP_TO_INT to lower!");
11290 // These are really Legal.
11291 if (DstTy == MVT::i32 &&
11292 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11293 return std::make_pair(SDValue(), SDValue());
11294 if (Subtarget->is64Bit() &&
11295 DstTy == MVT::i64 &&
11296 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11297 return std::make_pair(SDValue(), SDValue());
11299 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11300 // stack slot, or into the FTOL runtime function.
11301 MachineFunction &MF = DAG.getMachineFunction();
11302 unsigned MemSize = DstTy.getSizeInBits()/8;
11303 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11304 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11307 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11308 Opc = X86ISD::WIN_FTOL;
11310 switch (DstTy.getSimpleVT().SimpleTy) {
11311 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11312 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11313 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11314 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11317 SDValue Chain = DAG.getEntryNode();
11318 SDValue Value = Op.getOperand(0);
11319 EVT TheVT = Op.getOperand(0).getValueType();
11320 // FIXME This causes a redundant load/store if the SSE-class value is already
11321 // in memory, such as if it is on the callstack.
11322 if (isScalarFPTypeInSSEReg(TheVT)) {
11323 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11324 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11325 MachinePointerInfo::getFixedStack(SSFI),
11327 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11329 Chain, StackSlot, DAG.getValueType(TheVT)
11332 MachineMemOperand *MMO =
11333 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11334 MachineMemOperand::MOLoad, MemSize, MemSize);
11335 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11336 Chain = Value.getValue(1);
11337 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11338 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11341 MachineMemOperand *MMO =
11342 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11343 MachineMemOperand::MOStore, MemSize, MemSize);
11345 if (Opc != X86ISD::WIN_FTOL) {
11346 // Build the FP_TO_INT*_IN_MEM
11347 SDValue Ops[] = { Chain, Value, StackSlot };
11348 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11350 return std::make_pair(FIST, StackSlot);
11352 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11353 DAG.getVTList(MVT::Other, MVT::Glue),
11355 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11356 MVT::i32, ftol.getValue(1));
11357 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11358 MVT::i32, eax.getValue(2));
11359 SDValue Ops[] = { eax, edx };
11360 SDValue pair = IsReplace
11361 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11362 : DAG.getMergeValues(Ops, DL);
11363 return std::make_pair(pair, SDValue());
11367 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11368 const X86Subtarget *Subtarget) {
11369 MVT VT = Op->getSimpleValueType(0);
11370 SDValue In = Op->getOperand(0);
11371 MVT InVT = In.getSimpleValueType();
11374 // Optimize vectors in AVX mode:
11377 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11378 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11379 // Concat upper and lower parts.
11382 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11383 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11384 // Concat upper and lower parts.
11387 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11388 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11389 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11392 if (Subtarget->hasInt256())
11393 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11395 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11396 SDValue Undef = DAG.getUNDEF(InVT);
11397 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11398 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11399 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11401 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11402 VT.getVectorNumElements()/2);
11404 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11405 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11407 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11410 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11411 SelectionDAG &DAG) {
11412 MVT VT = Op->getSimpleValueType(0);
11413 SDValue In = Op->getOperand(0);
11414 MVT InVT = In.getSimpleValueType();
11416 unsigned int NumElts = VT.getVectorNumElements();
11417 if (NumElts != 8 && NumElts != 16)
11420 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11421 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11423 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11424 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11425 // Now we have only mask extension
11426 assert(InVT.getVectorElementType() == MVT::i1);
11427 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11428 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11429 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11430 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11431 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11432 MachinePointerInfo::getConstantPool(),
11433 false, false, false, Alignment);
11435 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11436 if (VT.is512BitVector())
11438 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11441 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11442 SelectionDAG &DAG) {
11443 if (Subtarget->hasFp256()) {
11444 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11452 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11453 SelectionDAG &DAG) {
11455 MVT VT = Op.getSimpleValueType();
11456 SDValue In = Op.getOperand(0);
11457 MVT SVT = In.getSimpleValueType();
11459 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11460 return LowerZERO_EXTEND_AVX512(Op, DAG);
11462 if (Subtarget->hasFp256()) {
11463 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11468 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11469 VT.getVectorNumElements() != SVT.getVectorNumElements());
11473 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11475 MVT VT = Op.getSimpleValueType();
11476 SDValue In = Op.getOperand(0);
11477 MVT InVT = In.getSimpleValueType();
11479 if (VT == MVT::i1) {
11480 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11481 "Invalid scalar TRUNCATE operation");
11482 if (InVT == MVT::i32)
11484 if (InVT.getSizeInBits() == 64)
11485 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11486 else if (InVT.getSizeInBits() < 32)
11487 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11488 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11490 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11491 "Invalid TRUNCATE operation");
11493 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11494 if (VT.getVectorElementType().getSizeInBits() >=8)
11495 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11497 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11498 unsigned NumElts = InVT.getVectorNumElements();
11499 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11500 if (InVT.getSizeInBits() < 512) {
11501 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11502 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11506 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11507 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11508 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11509 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11510 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11511 MachinePointerInfo::getConstantPool(),
11512 false, false, false, Alignment);
11513 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11514 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11515 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11518 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11519 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11520 if (Subtarget->hasInt256()) {
11521 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11522 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11523 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11525 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11526 DAG.getIntPtrConstant(0));
11529 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11530 DAG.getIntPtrConstant(0));
11531 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11532 DAG.getIntPtrConstant(2));
11533 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11534 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11535 static const int ShufMask[] = {0, 2, 4, 6};
11536 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11539 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11540 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11541 if (Subtarget->hasInt256()) {
11542 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11544 SmallVector<SDValue,32> pshufbMask;
11545 for (unsigned i = 0; i < 2; ++i) {
11546 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11547 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11548 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11549 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11550 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11551 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11552 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11553 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11554 for (unsigned j = 0; j < 8; ++j)
11555 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11557 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11558 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11559 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11561 static const int ShufMask[] = {0, 2, -1, -1};
11562 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11564 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11565 DAG.getIntPtrConstant(0));
11566 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11569 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11570 DAG.getIntPtrConstant(0));
11572 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11573 DAG.getIntPtrConstant(4));
11575 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11576 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11578 // The PSHUFB mask:
11579 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11580 -1, -1, -1, -1, -1, -1, -1, -1};
11582 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11583 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11584 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11586 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11587 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11589 // The MOVLHPS Mask:
11590 static const int ShufMask2[] = {0, 1, 4, 5};
11591 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11592 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11595 // Handle truncation of V256 to V128 using shuffles.
11596 if (!VT.is128BitVector() || !InVT.is256BitVector())
11599 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11601 unsigned NumElems = VT.getVectorNumElements();
11602 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11604 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11605 // Prepare truncation shuffle mask
11606 for (unsigned i = 0; i != NumElems; ++i)
11607 MaskVec[i] = i * 2;
11608 SDValue V = DAG.getVectorShuffle(NVT, DL,
11609 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11610 DAG.getUNDEF(NVT), &MaskVec[0]);
11611 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11612 DAG.getIntPtrConstant(0));
11615 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11616 SelectionDAG &DAG) const {
11617 assert(!Op.getSimpleValueType().isVector());
11619 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11620 /*IsSigned=*/ true, /*IsReplace=*/ false);
11621 SDValue FIST = Vals.first, StackSlot = Vals.second;
11622 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11623 if (!FIST.getNode()) return Op;
11625 if (StackSlot.getNode())
11626 // Load the result.
11627 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11628 FIST, StackSlot, MachinePointerInfo(),
11629 false, false, false, 0);
11631 // The node is the result.
11635 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11636 SelectionDAG &DAG) const {
11637 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11638 /*IsSigned=*/ false, /*IsReplace=*/ false);
11639 SDValue FIST = Vals.first, StackSlot = Vals.second;
11640 assert(FIST.getNode() && "Unexpected failure");
11642 if (StackSlot.getNode())
11643 // Load the result.
11644 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11645 FIST, StackSlot, MachinePointerInfo(),
11646 false, false, false, 0);
11648 // The node is the result.
11652 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11654 MVT VT = Op.getSimpleValueType();
11655 SDValue In = Op.getOperand(0);
11656 MVT SVT = In.getSimpleValueType();
11658 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11660 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11661 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11662 In, DAG.getUNDEF(SVT)));
11665 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11666 LLVMContext *Context = DAG.getContext();
11668 MVT VT = Op.getSimpleValueType();
11670 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11671 if (VT.isVector()) {
11672 EltVT = VT.getVectorElementType();
11673 NumElts = VT.getVectorNumElements();
11676 if (EltVT == MVT::f64)
11677 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11678 APInt(64, ~(1ULL << 63))));
11680 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11681 APInt(32, ~(1U << 31))));
11682 C = ConstantVector::getSplat(NumElts, C);
11683 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11684 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11685 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11686 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11687 MachinePointerInfo::getConstantPool(),
11688 false, false, false, Alignment);
11689 if (VT.isVector()) {
11690 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11691 return DAG.getNode(ISD::BITCAST, dl, VT,
11692 DAG.getNode(ISD::AND, dl, ANDVT,
11693 DAG.getNode(ISD::BITCAST, dl, ANDVT,
11695 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11697 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11700 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11701 LLVMContext *Context = DAG.getContext();
11703 MVT VT = Op.getSimpleValueType();
11705 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11706 if (VT.isVector()) {
11707 EltVT = VT.getVectorElementType();
11708 NumElts = VT.getVectorNumElements();
11711 if (EltVT == MVT::f64)
11712 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11713 APInt(64, 1ULL << 63)));
11715 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11716 APInt(32, 1U << 31)));
11717 C = ConstantVector::getSplat(NumElts, C);
11718 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11719 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11720 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11721 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11722 MachinePointerInfo::getConstantPool(),
11723 false, false, false, Alignment);
11724 if (VT.isVector()) {
11725 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11726 return DAG.getNode(ISD::BITCAST, dl, VT,
11727 DAG.getNode(ISD::XOR, dl, XORVT,
11728 DAG.getNode(ISD::BITCAST, dl, XORVT,
11730 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11733 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11736 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11737 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11738 LLVMContext *Context = DAG.getContext();
11739 SDValue Op0 = Op.getOperand(0);
11740 SDValue Op1 = Op.getOperand(1);
11742 MVT VT = Op.getSimpleValueType();
11743 MVT SrcVT = Op1.getSimpleValueType();
11745 // If second operand is smaller, extend it first.
11746 if (SrcVT.bitsLT(VT)) {
11747 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11750 // And if it is bigger, shrink it first.
11751 if (SrcVT.bitsGT(VT)) {
11752 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11756 // At this point the operands and the result should have the same
11757 // type, and that won't be f80 since that is not custom lowered.
11759 // First get the sign bit of second operand.
11760 SmallVector<Constant*,4> CV;
11761 if (SrcVT == MVT::f64) {
11762 const fltSemantics &Sem = APFloat::IEEEdouble;
11763 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11764 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11766 const fltSemantics &Sem = APFloat::IEEEsingle;
11767 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11768 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11769 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11770 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11772 Constant *C = ConstantVector::get(CV);
11773 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11774 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11775 MachinePointerInfo::getConstantPool(),
11776 false, false, false, 16);
11777 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11779 // Shift sign bit right or left if the two operands have different types.
11780 if (SrcVT.bitsGT(VT)) {
11781 // Op0 is MVT::f32, Op1 is MVT::f64.
11782 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11783 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11784 DAG.getConstant(32, MVT::i32));
11785 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11786 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11787 DAG.getIntPtrConstant(0));
11790 // Clear first operand sign bit.
11792 if (VT == MVT::f64) {
11793 const fltSemantics &Sem = APFloat::IEEEdouble;
11794 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11795 APInt(64, ~(1ULL << 63)))));
11796 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11798 const fltSemantics &Sem = APFloat::IEEEsingle;
11799 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11800 APInt(32, ~(1U << 31)))));
11801 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11802 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11803 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11805 C = ConstantVector::get(CV);
11806 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11807 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11808 MachinePointerInfo::getConstantPool(),
11809 false, false, false, 16);
11810 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11812 // Or the value with the sign bit.
11813 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11816 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11817 SDValue N0 = Op.getOperand(0);
11819 MVT VT = Op.getSimpleValueType();
11821 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11822 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11823 DAG.getConstant(1, VT));
11824 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11827 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11829 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11830 SelectionDAG &DAG) {
11831 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11833 if (!Subtarget->hasSSE41())
11836 if (!Op->hasOneUse())
11839 SDNode *N = Op.getNode();
11842 SmallVector<SDValue, 8> Opnds;
11843 DenseMap<SDValue, unsigned> VecInMap;
11844 SmallVector<SDValue, 8> VecIns;
11845 EVT VT = MVT::Other;
11847 // Recognize a special case where a vector is casted into wide integer to
11849 Opnds.push_back(N->getOperand(0));
11850 Opnds.push_back(N->getOperand(1));
11852 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11853 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11854 // BFS traverse all OR'd operands.
11855 if (I->getOpcode() == ISD::OR) {
11856 Opnds.push_back(I->getOperand(0));
11857 Opnds.push_back(I->getOperand(1));
11858 // Re-evaluate the number of nodes to be traversed.
11859 e += 2; // 2 more nodes (LHS and RHS) are pushed.
11863 // Quit if a non-EXTRACT_VECTOR_ELT
11864 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11867 // Quit if without a constant index.
11868 SDValue Idx = I->getOperand(1);
11869 if (!isa<ConstantSDNode>(Idx))
11872 SDValue ExtractedFromVec = I->getOperand(0);
11873 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11874 if (M == VecInMap.end()) {
11875 VT = ExtractedFromVec.getValueType();
11876 // Quit if not 128/256-bit vector.
11877 if (!VT.is128BitVector() && !VT.is256BitVector())
11879 // Quit if not the same type.
11880 if (VecInMap.begin() != VecInMap.end() &&
11881 VT != VecInMap.begin()->first.getValueType())
11883 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11884 VecIns.push_back(ExtractedFromVec);
11886 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11889 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11890 "Not extracted from 128-/256-bit vector.");
11892 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11894 for (DenseMap<SDValue, unsigned>::const_iterator
11895 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11896 // Quit if not all elements are used.
11897 if (I->second != FullMask)
11901 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11903 // Cast all vectors into TestVT for PTEST.
11904 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11905 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11907 // If more than one full vectors are evaluated, OR them first before PTEST.
11908 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11909 // Each iteration will OR 2 nodes and append the result until there is only
11910 // 1 node left, i.e. the final OR'd value of all vectors.
11911 SDValue LHS = VecIns[Slot];
11912 SDValue RHS = VecIns[Slot + 1];
11913 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11916 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11917 VecIns.back(), VecIns.back());
11920 /// \brief return true if \c Op has a use that doesn't just read flags.
11921 static bool hasNonFlagsUse(SDValue Op) {
11922 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11924 SDNode *User = *UI;
11925 unsigned UOpNo = UI.getOperandNo();
11926 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11927 // Look pass truncate.
11928 UOpNo = User->use_begin().getOperandNo();
11929 User = *User->use_begin();
11932 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11933 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11939 /// Emit nodes that will be selected as "test Op0,Op0", or something
11941 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11942 SelectionDAG &DAG) const {
11943 if (Op.getValueType() == MVT::i1)
11944 // KORTEST instruction should be selected
11945 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11946 DAG.getConstant(0, Op.getValueType()));
11948 // CF and OF aren't always set the way we want. Determine which
11949 // of these we need.
11950 bool NeedCF = false;
11951 bool NeedOF = false;
11954 case X86::COND_A: case X86::COND_AE:
11955 case X86::COND_B: case X86::COND_BE:
11958 case X86::COND_G: case X86::COND_GE:
11959 case X86::COND_L: case X86::COND_LE:
11960 case X86::COND_O: case X86::COND_NO: {
11961 // Check if we really need to set the
11962 // Overflow flag. If NoSignedWrap is present
11963 // that is not actually needed.
11964 switch (Op->getOpcode()) {
11969 const BinaryWithFlagsSDNode *BinNode =
11970 cast<BinaryWithFlagsSDNode>(Op.getNode());
11971 if (BinNode->hasNoSignedWrap())
11981 // See if we can use the EFLAGS value from the operand instead of
11982 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11983 // we prove that the arithmetic won't overflow, we can't use OF or CF.
11984 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11985 // Emit a CMP with 0, which is the TEST pattern.
11986 //if (Op.getValueType() == MVT::i1)
11987 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11988 // DAG.getConstant(0, MVT::i1));
11989 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11990 DAG.getConstant(0, Op.getValueType()));
11992 unsigned Opcode = 0;
11993 unsigned NumOperands = 0;
11995 // Truncate operations may prevent the merge of the SETCC instruction
11996 // and the arithmetic instruction before it. Attempt to truncate the operands
11997 // of the arithmetic instruction and use a reduced bit-width instruction.
11998 bool NeedTruncation = false;
11999 SDValue ArithOp = Op;
12000 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12001 SDValue Arith = Op->getOperand(0);
12002 // Both the trunc and the arithmetic op need to have one user each.
12003 if (Arith->hasOneUse())
12004 switch (Arith.getOpcode()) {
12011 NeedTruncation = true;
12017 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12018 // which may be the result of a CAST. We use the variable 'Op', which is the
12019 // non-casted variable when we check for possible users.
12020 switch (ArithOp.getOpcode()) {
12022 // Due to an isel shortcoming, be conservative if this add is likely to be
12023 // selected as part of a load-modify-store instruction. When the root node
12024 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12025 // uses of other nodes in the match, such as the ADD in this case. This
12026 // leads to the ADD being left around and reselected, with the result being
12027 // two adds in the output. Alas, even if none our users are stores, that
12028 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12029 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12030 // climbing the DAG back to the root, and it doesn't seem to be worth the
12032 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12033 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12034 if (UI->getOpcode() != ISD::CopyToReg &&
12035 UI->getOpcode() != ISD::SETCC &&
12036 UI->getOpcode() != ISD::STORE)
12039 if (ConstantSDNode *C =
12040 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12041 // An add of one will be selected as an INC.
12042 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12043 Opcode = X86ISD::INC;
12048 // An add of negative one (subtract of one) will be selected as a DEC.
12049 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12050 Opcode = X86ISD::DEC;
12056 // Otherwise use a regular EFLAGS-setting add.
12057 Opcode = X86ISD::ADD;
12062 // If we have a constant logical shift that's only used in a comparison
12063 // against zero turn it into an equivalent AND. This allows turning it into
12064 // a TEST instruction later.
12065 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12066 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12067 EVT VT = Op.getValueType();
12068 unsigned BitWidth = VT.getSizeInBits();
12069 unsigned ShAmt = Op->getConstantOperandVal(1);
12070 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12072 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12073 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12074 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12075 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12077 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12078 DAG.getConstant(Mask, VT));
12079 DAG.ReplaceAllUsesWith(Op, New);
12085 // If the primary and result isn't used, don't bother using X86ISD::AND,
12086 // because a TEST instruction will be better.
12087 if (!hasNonFlagsUse(Op))
12093 // Due to the ISEL shortcoming noted above, be conservative if this op is
12094 // likely to be selected as part of a load-modify-store instruction.
12095 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12096 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12097 if (UI->getOpcode() == ISD::STORE)
12100 // Otherwise use a regular EFLAGS-setting instruction.
12101 switch (ArithOp.getOpcode()) {
12102 default: llvm_unreachable("unexpected operator!");
12103 case ISD::SUB: Opcode = X86ISD::SUB; break;
12104 case ISD::XOR: Opcode = X86ISD::XOR; break;
12105 case ISD::AND: Opcode = X86ISD::AND; break;
12107 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12108 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12109 if (EFLAGS.getNode())
12112 Opcode = X86ISD::OR;
12126 return SDValue(Op.getNode(), 1);
12132 // If we found that truncation is beneficial, perform the truncation and
12134 if (NeedTruncation) {
12135 EVT VT = Op.getValueType();
12136 SDValue WideVal = Op->getOperand(0);
12137 EVT WideVT = WideVal.getValueType();
12138 unsigned ConvertedOp = 0;
12139 // Use a target machine opcode to prevent further DAGCombine
12140 // optimizations that may separate the arithmetic operations
12141 // from the setcc node.
12142 switch (WideVal.getOpcode()) {
12144 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12145 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12146 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12147 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12148 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12152 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12153 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12154 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12155 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12156 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12162 // Emit a CMP with 0, which is the TEST pattern.
12163 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12164 DAG.getConstant(0, Op.getValueType()));
12166 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12167 SmallVector<SDValue, 4> Ops;
12168 for (unsigned i = 0; i != NumOperands; ++i)
12169 Ops.push_back(Op.getOperand(i));
12171 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12172 DAG.ReplaceAllUsesWith(Op, New);
12173 return SDValue(New.getNode(), 1);
12176 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12178 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12179 SDLoc dl, SelectionDAG &DAG) const {
12180 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12181 if (C->getAPIntValue() == 0)
12182 return EmitTest(Op0, X86CC, dl, DAG);
12184 if (Op0.getValueType() == MVT::i1)
12185 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12188 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12189 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12190 // Do the comparison at i32 if it's smaller, besides the Atom case.
12191 // This avoids subregister aliasing issues. Keep the smaller reference
12192 // if we're optimizing for size, however, as that'll allow better folding
12193 // of memory operations.
12194 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12195 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12196 AttributeSet::FunctionIndex, Attribute::MinSize) &&
12197 !Subtarget->isAtom()) {
12198 unsigned ExtendOp =
12199 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12200 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12201 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12203 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12204 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12205 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12207 return SDValue(Sub.getNode(), 1);
12209 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12212 /// Convert a comparison if required by the subtarget.
12213 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12214 SelectionDAG &DAG) const {
12215 // If the subtarget does not support the FUCOMI instruction, floating-point
12216 // comparisons have to be converted.
12217 if (Subtarget->hasCMov() ||
12218 Cmp.getOpcode() != X86ISD::CMP ||
12219 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12220 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12223 // The instruction selector will select an FUCOM instruction instead of
12224 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12225 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12226 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12228 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12229 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12230 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12231 DAG.getConstant(8, MVT::i8));
12232 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12233 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12236 static bool isAllOnes(SDValue V) {
12237 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12238 return C && C->isAllOnesValue();
12241 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12242 /// if it's possible.
12243 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12244 SDLoc dl, SelectionDAG &DAG) const {
12245 SDValue Op0 = And.getOperand(0);
12246 SDValue Op1 = And.getOperand(1);
12247 if (Op0.getOpcode() == ISD::TRUNCATE)
12248 Op0 = Op0.getOperand(0);
12249 if (Op1.getOpcode() == ISD::TRUNCATE)
12250 Op1 = Op1.getOperand(0);
12253 if (Op1.getOpcode() == ISD::SHL)
12254 std::swap(Op0, Op1);
12255 if (Op0.getOpcode() == ISD::SHL) {
12256 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12257 if (And00C->getZExtValue() == 1) {
12258 // If we looked past a truncate, check that it's only truncating away
12260 unsigned BitWidth = Op0.getValueSizeInBits();
12261 unsigned AndBitWidth = And.getValueSizeInBits();
12262 if (BitWidth > AndBitWidth) {
12264 DAG.computeKnownBits(Op0, Zeros, Ones);
12265 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12269 RHS = Op0.getOperand(1);
12271 } else if (Op1.getOpcode() == ISD::Constant) {
12272 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12273 uint64_t AndRHSVal = AndRHS->getZExtValue();
12274 SDValue AndLHS = Op0;
12276 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12277 LHS = AndLHS.getOperand(0);
12278 RHS = AndLHS.getOperand(1);
12281 // Use BT if the immediate can't be encoded in a TEST instruction.
12282 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12284 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12288 if (LHS.getNode()) {
12289 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12290 // instruction. Since the shift amount is in-range-or-undefined, we know
12291 // that doing a bittest on the i32 value is ok. We extend to i32 because
12292 // the encoding for the i16 version is larger than the i32 version.
12293 // Also promote i16 to i32 for performance / code size reason.
12294 if (LHS.getValueType() == MVT::i8 ||
12295 LHS.getValueType() == MVT::i16)
12296 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12298 // If the operand types disagree, extend the shift amount to match. Since
12299 // BT ignores high bits (like shifts) we can use anyextend.
12300 if (LHS.getValueType() != RHS.getValueType())
12301 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12303 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12304 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12305 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12306 DAG.getConstant(Cond, MVT::i8), BT);
12312 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12314 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12319 // SSE Condition code mapping:
12328 switch (SetCCOpcode) {
12329 default: llvm_unreachable("Unexpected SETCC condition");
12331 case ISD::SETEQ: SSECC = 0; break;
12333 case ISD::SETGT: Swap = true; // Fallthrough
12335 case ISD::SETOLT: SSECC = 1; break;
12337 case ISD::SETGE: Swap = true; // Fallthrough
12339 case ISD::SETOLE: SSECC = 2; break;
12340 case ISD::SETUO: SSECC = 3; break;
12342 case ISD::SETNE: SSECC = 4; break;
12343 case ISD::SETULE: Swap = true; // Fallthrough
12344 case ISD::SETUGE: SSECC = 5; break;
12345 case ISD::SETULT: Swap = true; // Fallthrough
12346 case ISD::SETUGT: SSECC = 6; break;
12347 case ISD::SETO: SSECC = 7; break;
12349 case ISD::SETONE: SSECC = 8; break;
12352 std::swap(Op0, Op1);
12357 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12358 // ones, and then concatenate the result back.
12359 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12360 MVT VT = Op.getSimpleValueType();
12362 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12363 "Unsupported value type for operation");
12365 unsigned NumElems = VT.getVectorNumElements();
12367 SDValue CC = Op.getOperand(2);
12369 // Extract the LHS vectors
12370 SDValue LHS = Op.getOperand(0);
12371 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12372 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12374 // Extract the RHS vectors
12375 SDValue RHS = Op.getOperand(1);
12376 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12377 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12379 // Issue the operation on the smaller types and concatenate the result back
12380 MVT EltVT = VT.getVectorElementType();
12381 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12382 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12383 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12384 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12387 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12388 const X86Subtarget *Subtarget) {
12389 SDValue Op0 = Op.getOperand(0);
12390 SDValue Op1 = Op.getOperand(1);
12391 SDValue CC = Op.getOperand(2);
12392 MVT VT = Op.getSimpleValueType();
12395 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12396 Op.getValueType().getScalarType() == MVT::i1 &&
12397 "Cannot set masked compare for this operation");
12399 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12401 bool Unsigned = false;
12404 switch (SetCCOpcode) {
12405 default: llvm_unreachable("Unexpected SETCC condition");
12406 case ISD::SETNE: SSECC = 4; break;
12407 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12408 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12409 case ISD::SETLT: Swap = true; //fall-through
12410 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12411 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12412 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12413 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12414 case ISD::SETULE: Unsigned = true; //fall-through
12415 case ISD::SETLE: SSECC = 2; break;
12419 std::swap(Op0, Op1);
12421 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12422 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12423 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12424 DAG.getConstant(SSECC, MVT::i8));
12427 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12428 /// operand \p Op1. If non-trivial (for example because it's not constant)
12429 /// return an empty value.
12430 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12432 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12436 MVT VT = Op1.getSimpleValueType();
12437 MVT EVT = VT.getVectorElementType();
12438 unsigned n = VT.getVectorNumElements();
12439 SmallVector<SDValue, 8> ULTOp1;
12441 for (unsigned i = 0; i < n; ++i) {
12442 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12443 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12446 // Avoid underflow.
12447 APInt Val = Elt->getAPIntValue();
12451 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12454 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12457 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12458 SelectionDAG &DAG) {
12459 SDValue Op0 = Op.getOperand(0);
12460 SDValue Op1 = Op.getOperand(1);
12461 SDValue CC = Op.getOperand(2);
12462 MVT VT = Op.getSimpleValueType();
12463 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12464 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12469 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12470 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12473 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12474 unsigned Opc = X86ISD::CMPP;
12475 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12476 assert(VT.getVectorNumElements() <= 16);
12477 Opc = X86ISD::CMPM;
12479 // In the two special cases we can't handle, emit two comparisons.
12482 unsigned CombineOpc;
12483 if (SetCCOpcode == ISD::SETUEQ) {
12484 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12486 assert(SetCCOpcode == ISD::SETONE);
12487 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12490 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12491 DAG.getConstant(CC0, MVT::i8));
12492 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12493 DAG.getConstant(CC1, MVT::i8));
12494 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12496 // Handle all other FP comparisons here.
12497 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12498 DAG.getConstant(SSECC, MVT::i8));
12501 // Break 256-bit integer vector compare into smaller ones.
12502 if (VT.is256BitVector() && !Subtarget->hasInt256())
12503 return Lower256IntVSETCC(Op, DAG);
12505 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12506 EVT OpVT = Op1.getValueType();
12507 if (Subtarget->hasAVX512()) {
12508 if (Op1.getValueType().is512BitVector() ||
12509 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12510 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12512 // In AVX-512 architecture setcc returns mask with i1 elements,
12513 // But there is no compare instruction for i8 and i16 elements.
12514 // We are not talking about 512-bit operands in this case, these
12515 // types are illegal.
12517 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12518 OpVT.getVectorElementType().getSizeInBits() >= 8))
12519 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12520 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12523 // We are handling one of the integer comparisons here. Since SSE only has
12524 // GT and EQ comparisons for integer, swapping operands and multiple
12525 // operations may be required for some comparisons.
12527 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12528 bool Subus = false;
12530 switch (SetCCOpcode) {
12531 default: llvm_unreachable("Unexpected SETCC condition");
12532 case ISD::SETNE: Invert = true;
12533 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12534 case ISD::SETLT: Swap = true;
12535 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12536 case ISD::SETGE: Swap = true;
12537 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12538 Invert = true; break;
12539 case ISD::SETULT: Swap = true;
12540 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12541 FlipSigns = true; break;
12542 case ISD::SETUGE: Swap = true;
12543 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12544 FlipSigns = true; Invert = true; break;
12547 // Special case: Use min/max operations for SETULE/SETUGE
12548 MVT VET = VT.getVectorElementType();
12550 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12551 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12554 switch (SetCCOpcode) {
12556 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12557 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12560 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12563 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12564 if (!MinMax && hasSubus) {
12565 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12567 // t = psubus Op0, Op1
12568 // pcmpeq t, <0..0>
12569 switch (SetCCOpcode) {
12571 case ISD::SETULT: {
12572 // If the comparison is against a constant we can turn this into a
12573 // setule. With psubus, setule does not require a swap. This is
12574 // beneficial because the constant in the register is no longer
12575 // destructed as the destination so it can be hoisted out of a loop.
12576 // Only do this pre-AVX since vpcmp* is no longer destructive.
12577 if (Subtarget->hasAVX())
12579 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12580 if (ULEOp1.getNode()) {
12582 Subus = true; Invert = false; Swap = false;
12586 // Psubus is better than flip-sign because it requires no inversion.
12587 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12588 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12592 Opc = X86ISD::SUBUS;
12598 std::swap(Op0, Op1);
12600 // Check that the operation in question is available (most are plain SSE2,
12601 // but PCMPGTQ and PCMPEQQ have different requirements).
12602 if (VT == MVT::v2i64) {
12603 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12604 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12606 // First cast everything to the right type.
12607 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12608 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12610 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12611 // bits of the inputs before performing those operations. The lower
12612 // compare is always unsigned.
12615 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12617 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12618 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12619 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12620 Sign, Zero, Sign, Zero);
12622 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12623 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12625 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12626 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12627 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12629 // Create masks for only the low parts/high parts of the 64 bit integers.
12630 static const int MaskHi[] = { 1, 1, 3, 3 };
12631 static const int MaskLo[] = { 0, 0, 2, 2 };
12632 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12633 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12634 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12636 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12637 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12640 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12642 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12645 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12646 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12647 // pcmpeqd + pshufd + pand.
12648 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12650 // First cast everything to the right type.
12651 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12652 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12655 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12657 // Make sure the lower and upper halves are both all-ones.
12658 static const int Mask[] = { 1, 0, 3, 2 };
12659 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12660 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12663 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12665 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12669 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12670 // bits of the inputs before performing those operations.
12672 EVT EltVT = VT.getVectorElementType();
12673 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12674 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12675 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12678 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12680 // If the logical-not of the result is required, perform that now.
12682 Result = DAG.getNOT(dl, Result, VT);
12685 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12688 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12689 getZeroVector(VT, Subtarget, DAG, dl));
12694 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12696 MVT VT = Op.getSimpleValueType();
12698 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12700 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12701 && "SetCC type must be 8-bit or 1-bit integer");
12702 SDValue Op0 = Op.getOperand(0);
12703 SDValue Op1 = Op.getOperand(1);
12705 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12707 // Optimize to BT if possible.
12708 // Lower (X & (1 << N)) == 0 to BT(X, N).
12709 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12710 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12711 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12712 Op1.getOpcode() == ISD::Constant &&
12713 cast<ConstantSDNode>(Op1)->isNullValue() &&
12714 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12715 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12716 if (NewSetCC.getNode())
12720 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
12722 if (Op1.getOpcode() == ISD::Constant &&
12723 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12724 cast<ConstantSDNode>(Op1)->isNullValue()) &&
12725 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12727 // If the input is a setcc, then reuse the input setcc or use a new one with
12728 // the inverted condition.
12729 if (Op0.getOpcode() == X86ISD::SETCC) {
12730 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12731 bool Invert = (CC == ISD::SETNE) ^
12732 cast<ConstantSDNode>(Op1)->isNullValue();
12736 CCode = X86::GetOppositeBranchCondition(CCode);
12737 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12738 DAG.getConstant(CCode, MVT::i8),
12739 Op0.getOperand(1));
12741 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12745 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12746 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12747 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12749 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12750 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12753 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12754 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12755 if (X86CC == X86::COND_INVALID)
12758 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12759 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12760 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12761 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12763 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12767 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12768 static bool isX86LogicalCmp(SDValue Op) {
12769 unsigned Opc = Op.getNode()->getOpcode();
12770 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12771 Opc == X86ISD::SAHF)
12773 if (Op.getResNo() == 1 &&
12774 (Opc == X86ISD::ADD ||
12775 Opc == X86ISD::SUB ||
12776 Opc == X86ISD::ADC ||
12777 Opc == X86ISD::SBB ||
12778 Opc == X86ISD::SMUL ||
12779 Opc == X86ISD::UMUL ||
12780 Opc == X86ISD::INC ||
12781 Opc == X86ISD::DEC ||
12782 Opc == X86ISD::OR ||
12783 Opc == X86ISD::XOR ||
12784 Opc == X86ISD::AND))
12787 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12793 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12794 if (V.getOpcode() != ISD::TRUNCATE)
12797 SDValue VOp0 = V.getOperand(0);
12798 unsigned InBits = VOp0.getValueSizeInBits();
12799 unsigned Bits = V.getValueSizeInBits();
12800 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12803 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12804 bool addTest = true;
12805 SDValue Cond = Op.getOperand(0);
12806 SDValue Op1 = Op.getOperand(1);
12807 SDValue Op2 = Op.getOperand(2);
12809 EVT VT = Op1.getValueType();
12812 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12813 // are available. Otherwise fp cmovs get lowered into a less efficient branch
12814 // sequence later on.
12815 if (Cond.getOpcode() == ISD::SETCC &&
12816 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12817 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12818 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12819 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12820 int SSECC = translateX86FSETCC(
12821 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12824 if (Subtarget->hasAVX512()) {
12825 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12826 DAG.getConstant(SSECC, MVT::i8));
12827 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12829 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12830 DAG.getConstant(SSECC, MVT::i8));
12831 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12832 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12833 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12837 if (Cond.getOpcode() == ISD::SETCC) {
12838 SDValue NewCond = LowerSETCC(Cond, DAG);
12839 if (NewCond.getNode())
12843 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12844 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12845 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12846 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12847 if (Cond.getOpcode() == X86ISD::SETCC &&
12848 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12849 isZero(Cond.getOperand(1).getOperand(1))) {
12850 SDValue Cmp = Cond.getOperand(1);
12852 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12854 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12855 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12856 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12858 SDValue CmpOp0 = Cmp.getOperand(0);
12859 // Apply further optimizations for special cases
12860 // (select (x != 0), -1, 0) -> neg & sbb
12861 // (select (x == 0), 0, -1) -> neg & sbb
12862 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12863 if (YC->isNullValue() &&
12864 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12865 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12866 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12867 DAG.getConstant(0, CmpOp0.getValueType()),
12869 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12870 DAG.getConstant(X86::COND_B, MVT::i8),
12871 SDValue(Neg.getNode(), 1));
12875 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12876 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12877 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12879 SDValue Res = // Res = 0 or -1.
12880 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12881 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12883 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12884 Res = DAG.getNOT(DL, Res, Res.getValueType());
12886 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12887 if (!N2C || !N2C->isNullValue())
12888 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12893 // Look past (and (setcc_carry (cmp ...)), 1).
12894 if (Cond.getOpcode() == ISD::AND &&
12895 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12896 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12897 if (C && C->getAPIntValue() == 1)
12898 Cond = Cond.getOperand(0);
12901 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12902 // setting operand in place of the X86ISD::SETCC.
12903 unsigned CondOpcode = Cond.getOpcode();
12904 if (CondOpcode == X86ISD::SETCC ||
12905 CondOpcode == X86ISD::SETCC_CARRY) {
12906 CC = Cond.getOperand(0);
12908 SDValue Cmp = Cond.getOperand(1);
12909 unsigned Opc = Cmp.getOpcode();
12910 MVT VT = Op.getSimpleValueType();
12912 bool IllegalFPCMov = false;
12913 if (VT.isFloatingPoint() && !VT.isVector() &&
12914 !isScalarFPTypeInSSEReg(VT)) // FPStack?
12915 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12917 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12918 Opc == X86ISD::BT) { // FIXME
12922 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12923 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12924 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12925 Cond.getOperand(0).getValueType() != MVT::i8)) {
12926 SDValue LHS = Cond.getOperand(0);
12927 SDValue RHS = Cond.getOperand(1);
12928 unsigned X86Opcode;
12931 switch (CondOpcode) {
12932 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12933 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12934 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12935 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12936 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12937 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12938 default: llvm_unreachable("unexpected overflowing operator");
12940 if (CondOpcode == ISD::UMULO)
12941 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12944 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12946 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12948 if (CondOpcode == ISD::UMULO)
12949 Cond = X86Op.getValue(2);
12951 Cond = X86Op.getValue(1);
12953 CC = DAG.getConstant(X86Cond, MVT::i8);
12958 // Look pass the truncate if the high bits are known zero.
12959 if (isTruncWithZeroHighBitsInput(Cond, DAG))
12960 Cond = Cond.getOperand(0);
12962 // We know the result of AND is compared against zero. Try to match
12964 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12965 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12966 if (NewSetCC.getNode()) {
12967 CC = NewSetCC.getOperand(0);
12968 Cond = NewSetCC.getOperand(1);
12975 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12976 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12979 // a < b ? -1 : 0 -> RES = ~setcc_carry
12980 // a < b ? 0 : -1 -> RES = setcc_carry
12981 // a >= b ? -1 : 0 -> RES = setcc_carry
12982 // a >= b ? 0 : -1 -> RES = ~setcc_carry
12983 if (Cond.getOpcode() == X86ISD::SUB) {
12984 Cond = ConvertCmpIfNecessary(Cond, DAG);
12985 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12987 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12988 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12989 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12990 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12991 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12992 return DAG.getNOT(DL, Res, Res.getValueType());
12997 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12998 // widen the cmov and push the truncate through. This avoids introducing a new
12999 // branch during isel and doesn't add any extensions.
13000 if (Op.getValueType() == MVT::i8 &&
13001 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13002 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13003 if (T1.getValueType() == T2.getValueType() &&
13004 // Blacklist CopyFromReg to avoid partial register stalls.
13005 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13006 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13007 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13008 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13012 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13013 // condition is true.
13014 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13015 SDValue Ops[] = { Op2, Op1, CC, Cond };
13016 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13019 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13020 MVT VT = Op->getSimpleValueType(0);
13021 SDValue In = Op->getOperand(0);
13022 MVT InVT = In.getSimpleValueType();
13025 unsigned int NumElts = VT.getVectorNumElements();
13026 if (NumElts != 8 && NumElts != 16)
13029 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13030 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13032 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13033 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13035 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13036 Constant *C = ConstantInt::get(*DAG.getContext(),
13037 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13039 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13040 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13041 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13042 MachinePointerInfo::getConstantPool(),
13043 false, false, false, Alignment);
13044 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13045 if (VT.is512BitVector())
13047 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13050 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13051 SelectionDAG &DAG) {
13052 MVT VT = Op->getSimpleValueType(0);
13053 SDValue In = Op->getOperand(0);
13054 MVT InVT = In.getSimpleValueType();
13057 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13058 return LowerSIGN_EXTEND_AVX512(Op, DAG);
13060 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13061 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13062 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13065 if (Subtarget->hasInt256())
13066 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13068 // Optimize vectors in AVX mode
13069 // Sign extend v8i16 to v8i32 and
13072 // Divide input vector into two parts
13073 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13074 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13075 // concat the vectors to original VT
13077 unsigned NumElems = InVT.getVectorNumElements();
13078 SDValue Undef = DAG.getUNDEF(InVT);
13080 SmallVector<int,8> ShufMask1(NumElems, -1);
13081 for (unsigned i = 0; i != NumElems/2; ++i)
13084 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13086 SmallVector<int,8> ShufMask2(NumElems, -1);
13087 for (unsigned i = 0; i != NumElems/2; ++i)
13088 ShufMask2[i] = i + NumElems/2;
13090 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13092 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13093 VT.getVectorNumElements()/2);
13095 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13096 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13098 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13101 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13102 // may emit an illegal shuffle but the expansion is still better than scalar
13103 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13104 // we'll emit a shuffle and a arithmetic shift.
13105 // TODO: It is possible to support ZExt by zeroing the undef values during
13106 // the shuffle phase or after the shuffle.
13107 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13108 SelectionDAG &DAG) {
13109 MVT RegVT = Op.getSimpleValueType();
13110 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13111 assert(RegVT.isInteger() &&
13112 "We only custom lower integer vector sext loads.");
13114 // Nothing useful we can do without SSE2 shuffles.
13115 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13117 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13119 EVT MemVT = Ld->getMemoryVT();
13120 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13121 unsigned RegSz = RegVT.getSizeInBits();
13123 ISD::LoadExtType Ext = Ld->getExtensionType();
13125 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13126 && "Only anyext and sext are currently implemented.");
13127 assert(MemVT != RegVT && "Cannot extend to the same type");
13128 assert(MemVT.isVector() && "Must load a vector from memory");
13130 unsigned NumElems = RegVT.getVectorNumElements();
13131 unsigned MemSz = MemVT.getSizeInBits();
13132 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13134 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13135 // The only way in which we have a legal 256-bit vector result but not the
13136 // integer 256-bit operations needed to directly lower a sextload is if we
13137 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13138 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13139 // correctly legalized. We do this late to allow the canonical form of
13140 // sextload to persist throughout the rest of the DAG combiner -- it wants
13141 // to fold together any extensions it can, and so will fuse a sign_extend
13142 // of an sextload into an sextload targeting a wider value.
13144 if (MemSz == 128) {
13145 // Just switch this to a normal load.
13146 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13147 "it must be a legal 128-bit vector "
13149 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13150 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13151 Ld->isInvariant(), Ld->getAlignment());
13153 assert(MemSz < 128 &&
13154 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13155 // Do an sext load to a 128-bit vector type. We want to use the same
13156 // number of elements, but elements half as wide. This will end up being
13157 // recursively lowered by this routine, but will succeed as we definitely
13158 // have all the necessary features if we're using AVX1.
13160 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13161 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13163 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13164 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13165 Ld->isNonTemporal(), Ld->isInvariant(),
13166 Ld->getAlignment());
13169 // Replace chain users with the new chain.
13170 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13171 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13173 // Finally, do a normal sign-extend to the desired register.
13174 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13177 // All sizes must be a power of two.
13178 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13179 "Non-power-of-two elements are not custom lowered!");
13181 // Attempt to load the original value using scalar loads.
13182 // Find the largest scalar type that divides the total loaded size.
13183 MVT SclrLoadTy = MVT::i8;
13184 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13185 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13186 MVT Tp = (MVT::SimpleValueType)tp;
13187 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13192 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13193 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13195 SclrLoadTy = MVT::f64;
13197 // Calculate the number of scalar loads that we need to perform
13198 // in order to load our vector from memory.
13199 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13201 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13202 "Can only lower sext loads with a single scalar load!");
13204 unsigned loadRegZize = RegSz;
13205 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13208 // Represent our vector as a sequence of elements which are the
13209 // largest scalar that we can load.
13210 EVT LoadUnitVecVT = EVT::getVectorVT(
13211 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13213 // Represent the data using the same element type that is stored in
13214 // memory. In practice, we ''widen'' MemVT.
13216 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13217 loadRegZize / MemVT.getScalarType().getSizeInBits());
13219 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13220 "Invalid vector type");
13222 // We can't shuffle using an illegal type.
13223 assert(TLI.isTypeLegal(WideVecVT) &&
13224 "We only lower types that form legal widened vector types");
13226 SmallVector<SDValue, 8> Chains;
13227 SDValue Ptr = Ld->getBasePtr();
13228 SDValue Increment =
13229 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13230 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13232 for (unsigned i = 0; i < NumLoads; ++i) {
13233 // Perform a single load.
13234 SDValue ScalarLoad =
13235 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13236 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13237 Ld->getAlignment());
13238 Chains.push_back(ScalarLoad.getValue(1));
13239 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13240 // another round of DAGCombining.
13242 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13244 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13245 ScalarLoad, DAG.getIntPtrConstant(i));
13247 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13250 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13252 // Bitcast the loaded value to a vector of the original element type, in
13253 // the size of the target vector type.
13254 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13255 unsigned SizeRatio = RegSz / MemSz;
13257 if (Ext == ISD::SEXTLOAD) {
13258 // If we have SSE4.1 we can directly emit a VSEXT node.
13259 if (Subtarget->hasSSE41()) {
13260 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13261 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13265 // Otherwise we'll shuffle the small elements in the high bits of the
13266 // larger type and perform an arithmetic shift. If the shift is not legal
13267 // it's better to scalarize.
13268 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13269 "We can't implement an sext load without a arithmetic right shift!");
13271 // Redistribute the loaded elements into the different locations.
13272 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13273 for (unsigned i = 0; i != NumElems; ++i)
13274 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13276 SDValue Shuff = DAG.getVectorShuffle(
13277 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13279 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13281 // Build the arithmetic shift.
13282 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13283 MemVT.getVectorElementType().getSizeInBits();
13285 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13287 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13291 // Redistribute the loaded elements into the different locations.
13292 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13293 for (unsigned i = 0; i != NumElems; ++i)
13294 ShuffleVec[i * SizeRatio] = i;
13296 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13297 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13299 // Bitcast to the requested type.
13300 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13301 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13305 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13306 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13307 // from the AND / OR.
13308 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13309 Opc = Op.getOpcode();
13310 if (Opc != ISD::OR && Opc != ISD::AND)
13312 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13313 Op.getOperand(0).hasOneUse() &&
13314 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13315 Op.getOperand(1).hasOneUse());
13318 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13319 // 1 and that the SETCC node has a single use.
13320 static bool isXor1OfSetCC(SDValue Op) {
13321 if (Op.getOpcode() != ISD::XOR)
13323 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13324 if (N1C && N1C->getAPIntValue() == 1) {
13325 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13326 Op.getOperand(0).hasOneUse();
13331 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13332 bool addTest = true;
13333 SDValue Chain = Op.getOperand(0);
13334 SDValue Cond = Op.getOperand(1);
13335 SDValue Dest = Op.getOperand(2);
13338 bool Inverted = false;
13340 if (Cond.getOpcode() == ISD::SETCC) {
13341 // Check for setcc([su]{add,sub,mul}o == 0).
13342 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13343 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13344 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13345 Cond.getOperand(0).getResNo() == 1 &&
13346 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13347 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13348 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13349 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13350 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13351 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13353 Cond = Cond.getOperand(0);
13355 SDValue NewCond = LowerSETCC(Cond, DAG);
13356 if (NewCond.getNode())
13361 // FIXME: LowerXALUO doesn't handle these!!
13362 else if (Cond.getOpcode() == X86ISD::ADD ||
13363 Cond.getOpcode() == X86ISD::SUB ||
13364 Cond.getOpcode() == X86ISD::SMUL ||
13365 Cond.getOpcode() == X86ISD::UMUL)
13366 Cond = LowerXALUO(Cond, DAG);
13369 // Look pass (and (setcc_carry (cmp ...)), 1).
13370 if (Cond.getOpcode() == ISD::AND &&
13371 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13372 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13373 if (C && C->getAPIntValue() == 1)
13374 Cond = Cond.getOperand(0);
13377 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13378 // setting operand in place of the X86ISD::SETCC.
13379 unsigned CondOpcode = Cond.getOpcode();
13380 if (CondOpcode == X86ISD::SETCC ||
13381 CondOpcode == X86ISD::SETCC_CARRY) {
13382 CC = Cond.getOperand(0);
13384 SDValue Cmp = Cond.getOperand(1);
13385 unsigned Opc = Cmp.getOpcode();
13386 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13387 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13391 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13395 // These can only come from an arithmetic instruction with overflow,
13396 // e.g. SADDO, UADDO.
13397 Cond = Cond.getNode()->getOperand(1);
13403 CondOpcode = Cond.getOpcode();
13404 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13405 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13406 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13407 Cond.getOperand(0).getValueType() != MVT::i8)) {
13408 SDValue LHS = Cond.getOperand(0);
13409 SDValue RHS = Cond.getOperand(1);
13410 unsigned X86Opcode;
13413 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13414 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13416 switch (CondOpcode) {
13417 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13419 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13421 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13424 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13425 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13427 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13429 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13432 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13433 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13434 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13435 default: llvm_unreachable("unexpected overflowing operator");
13438 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13439 if (CondOpcode == ISD::UMULO)
13440 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13443 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13445 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13447 if (CondOpcode == ISD::UMULO)
13448 Cond = X86Op.getValue(2);
13450 Cond = X86Op.getValue(1);
13452 CC = DAG.getConstant(X86Cond, MVT::i8);
13456 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13457 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13458 if (CondOpc == ISD::OR) {
13459 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13460 // two branches instead of an explicit OR instruction with a
13462 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13463 isX86LogicalCmp(Cmp)) {
13464 CC = Cond.getOperand(0).getOperand(0);
13465 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13466 Chain, Dest, CC, Cmp);
13467 CC = Cond.getOperand(1).getOperand(0);
13471 } else { // ISD::AND
13472 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13473 // two branches instead of an explicit AND instruction with a
13474 // separate test. However, we only do this if this block doesn't
13475 // have a fall-through edge, because this requires an explicit
13476 // jmp when the condition is false.
13477 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13478 isX86LogicalCmp(Cmp) &&
13479 Op.getNode()->hasOneUse()) {
13480 X86::CondCode CCode =
13481 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13482 CCode = X86::GetOppositeBranchCondition(CCode);
13483 CC = DAG.getConstant(CCode, MVT::i8);
13484 SDNode *User = *Op.getNode()->use_begin();
13485 // Look for an unconditional branch following this conditional branch.
13486 // We need this because we need to reverse the successors in order
13487 // to implement FCMP_OEQ.
13488 if (User->getOpcode() == ISD::BR) {
13489 SDValue FalseBB = User->getOperand(1);
13491 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13492 assert(NewBR == User);
13496 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13497 Chain, Dest, CC, Cmp);
13498 X86::CondCode CCode =
13499 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13500 CCode = X86::GetOppositeBranchCondition(CCode);
13501 CC = DAG.getConstant(CCode, MVT::i8);
13507 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13508 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13509 // It should be transformed during dag combiner except when the condition
13510 // is set by a arithmetics with overflow node.
13511 X86::CondCode CCode =
13512 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13513 CCode = X86::GetOppositeBranchCondition(CCode);
13514 CC = DAG.getConstant(CCode, MVT::i8);
13515 Cond = Cond.getOperand(0).getOperand(1);
13517 } else if (Cond.getOpcode() == ISD::SETCC &&
13518 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13519 // For FCMP_OEQ, we can emit
13520 // two branches instead of an explicit AND instruction with a
13521 // separate test. However, we only do this if this block doesn't
13522 // have a fall-through edge, because this requires an explicit
13523 // jmp when the condition is false.
13524 if (Op.getNode()->hasOneUse()) {
13525 SDNode *User = *Op.getNode()->use_begin();
13526 // Look for an unconditional branch following this conditional branch.
13527 // We need this because we need to reverse the successors in order
13528 // to implement FCMP_OEQ.
13529 if (User->getOpcode() == ISD::BR) {
13530 SDValue FalseBB = User->getOperand(1);
13532 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13533 assert(NewBR == User);
13537 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13538 Cond.getOperand(0), Cond.getOperand(1));
13539 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13540 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13541 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13542 Chain, Dest, CC, Cmp);
13543 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13548 } else if (Cond.getOpcode() == ISD::SETCC &&
13549 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13550 // For FCMP_UNE, we can emit
13551 // two branches instead of an explicit AND instruction with a
13552 // separate test. However, we only do this if this block doesn't
13553 // have a fall-through edge, because this requires an explicit
13554 // jmp when the condition is false.
13555 if (Op.getNode()->hasOneUse()) {
13556 SDNode *User = *Op.getNode()->use_begin();
13557 // Look for an unconditional branch following this conditional branch.
13558 // We need this because we need to reverse the successors in order
13559 // to implement FCMP_UNE.
13560 if (User->getOpcode() == ISD::BR) {
13561 SDValue FalseBB = User->getOperand(1);
13563 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13564 assert(NewBR == User);
13567 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13568 Cond.getOperand(0), Cond.getOperand(1));
13569 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13570 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13571 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13572 Chain, Dest, CC, Cmp);
13573 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13583 // Look pass the truncate if the high bits are known zero.
13584 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13585 Cond = Cond.getOperand(0);
13587 // We know the result of AND is compared against zero. Try to match
13589 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13590 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13591 if (NewSetCC.getNode()) {
13592 CC = NewSetCC.getOperand(0);
13593 Cond = NewSetCC.getOperand(1);
13600 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13601 CC = DAG.getConstant(X86Cond, MVT::i8);
13602 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13604 Cond = ConvertCmpIfNecessary(Cond, DAG);
13605 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13606 Chain, Dest, CC, Cond);
13609 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13610 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13611 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13612 // that the guard pages used by the OS virtual memory manager are allocated in
13613 // correct sequence.
13615 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13616 SelectionDAG &DAG) const {
13617 MachineFunction &MF = DAG.getMachineFunction();
13618 bool SplitStack = MF.shouldSplitStack();
13619 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13624 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13625 SDNode* Node = Op.getNode();
13627 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13628 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13629 " not tell us which reg is the stack pointer!");
13630 EVT VT = Node->getValueType(0);
13631 SDValue Tmp1 = SDValue(Node, 0);
13632 SDValue Tmp2 = SDValue(Node, 1);
13633 SDValue Tmp3 = Node->getOperand(2);
13634 SDValue Chain = Tmp1.getOperand(0);
13636 // Chain the dynamic stack allocation so that it doesn't modify the stack
13637 // pointer when other instructions are using the stack.
13638 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13641 SDValue Size = Tmp2.getOperand(1);
13642 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13643 Chain = SP.getValue(1);
13644 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13645 const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
13646 unsigned StackAlign = TFI.getStackAlignment();
13647 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13648 if (Align > StackAlign)
13649 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13650 DAG.getConstant(-(uint64_t)Align, VT));
13651 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13653 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13654 DAG.getIntPtrConstant(0, true), SDValue(),
13657 SDValue Ops[2] = { Tmp1, Tmp2 };
13658 return DAG.getMergeValues(Ops, dl);
13662 SDValue Chain = Op.getOperand(0);
13663 SDValue Size = Op.getOperand(1);
13664 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13665 EVT VT = Op.getNode()->getValueType(0);
13667 bool Is64Bit = Subtarget->is64Bit();
13668 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13671 MachineRegisterInfo &MRI = MF.getRegInfo();
13674 // The 64 bit implementation of segmented stacks needs to clobber both r10
13675 // r11. This makes it impossible to use it along with nested parameters.
13676 const Function *F = MF.getFunction();
13678 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13680 if (I->hasNestAttr())
13681 report_fatal_error("Cannot use segmented stacks with functions that "
13682 "have nested arguments.");
13685 const TargetRegisterClass *AddrRegClass =
13686 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13687 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13688 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13689 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13690 DAG.getRegister(Vreg, SPTy));
13691 SDValue Ops1[2] = { Value, Chain };
13692 return DAG.getMergeValues(Ops1, dl);
13695 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13697 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13698 Flag = Chain.getValue(1);
13699 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13701 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13703 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
13704 DAG.getSubtarget().getRegisterInfo());
13705 unsigned SPReg = RegInfo->getStackRegister();
13706 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13707 Chain = SP.getValue(1);
13710 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13711 DAG.getConstant(-(uint64_t)Align, VT));
13712 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13715 SDValue Ops1[2] = { SP, Chain };
13716 return DAG.getMergeValues(Ops1, dl);
13720 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13721 MachineFunction &MF = DAG.getMachineFunction();
13722 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13724 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13727 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13728 // vastart just stores the address of the VarArgsFrameIndex slot into the
13729 // memory location argument.
13730 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13732 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13733 MachinePointerInfo(SV), false, false, 0);
13737 // gp_offset (0 - 6 * 8)
13738 // fp_offset (48 - 48 + 8 * 16)
13739 // overflow_arg_area (point to parameters coming in memory).
13741 SmallVector<SDValue, 8> MemOps;
13742 SDValue FIN = Op.getOperand(1);
13744 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13745 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13747 FIN, MachinePointerInfo(SV), false, false, 0);
13748 MemOps.push_back(Store);
13751 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13752 FIN, DAG.getIntPtrConstant(4));
13753 Store = DAG.getStore(Op.getOperand(0), DL,
13754 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13756 FIN, MachinePointerInfo(SV, 4), false, false, 0);
13757 MemOps.push_back(Store);
13759 // Store ptr to overflow_arg_area
13760 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13761 FIN, DAG.getIntPtrConstant(4));
13762 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13764 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13765 MachinePointerInfo(SV, 8),
13767 MemOps.push_back(Store);
13769 // Store ptr to reg_save_area.
13770 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13771 FIN, DAG.getIntPtrConstant(8));
13772 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13774 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13775 MachinePointerInfo(SV, 16), false, false, 0);
13776 MemOps.push_back(Store);
13777 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13780 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13781 assert(Subtarget->is64Bit() &&
13782 "LowerVAARG only handles 64-bit va_arg!");
13783 assert((Subtarget->isTargetLinux() ||
13784 Subtarget->isTargetDarwin()) &&
13785 "Unhandled target in LowerVAARG");
13786 assert(Op.getNode()->getNumOperands() == 4);
13787 SDValue Chain = Op.getOperand(0);
13788 SDValue SrcPtr = Op.getOperand(1);
13789 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13790 unsigned Align = Op.getConstantOperandVal(3);
13793 EVT ArgVT = Op.getNode()->getValueType(0);
13794 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13795 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13798 // Decide which area this value should be read from.
13799 // TODO: Implement the AMD64 ABI in its entirety. This simple
13800 // selection mechanism works only for the basic types.
13801 if (ArgVT == MVT::f80) {
13802 llvm_unreachable("va_arg for f80 not yet implemented");
13803 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13804 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
13805 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13806 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
13808 llvm_unreachable("Unhandled argument type in LowerVAARG");
13811 if (ArgMode == 2) {
13812 // Sanity Check: Make sure using fp_offset makes sense.
13813 assert(!DAG.getTarget().Options.UseSoftFloat &&
13814 !(DAG.getMachineFunction()
13815 .getFunction()->getAttributes()
13816 .hasAttribute(AttributeSet::FunctionIndex,
13817 Attribute::NoImplicitFloat)) &&
13818 Subtarget->hasSSE1());
13821 // Insert VAARG_64 node into the DAG
13822 // VAARG_64 returns two values: Variable Argument Address, Chain
13823 SmallVector<SDValue, 11> InstOps;
13824 InstOps.push_back(Chain);
13825 InstOps.push_back(SrcPtr);
13826 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13827 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13828 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13829 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13830 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13831 VTs, InstOps, MVT::i64,
13832 MachinePointerInfo(SV),
13834 /*Volatile=*/false,
13836 /*WriteMem=*/true);
13837 Chain = VAARG.getValue(1);
13839 // Load the next argument and return it
13840 return DAG.getLoad(ArgVT, dl,
13843 MachinePointerInfo(),
13844 false, false, false, 0);
13847 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13848 SelectionDAG &DAG) {
13849 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13850 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13851 SDValue Chain = Op.getOperand(0);
13852 SDValue DstPtr = Op.getOperand(1);
13853 SDValue SrcPtr = Op.getOperand(2);
13854 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13855 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13858 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13859 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13861 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13864 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13865 // amount is a constant. Takes immediate version of shift as input.
13866 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13867 SDValue SrcOp, uint64_t ShiftAmt,
13868 SelectionDAG &DAG) {
13869 MVT ElementType = VT.getVectorElementType();
13871 // Fold this packed shift into its first operand if ShiftAmt is 0.
13875 // Check for ShiftAmt >= element width
13876 if (ShiftAmt >= ElementType.getSizeInBits()) {
13877 if (Opc == X86ISD::VSRAI)
13878 ShiftAmt = ElementType.getSizeInBits() - 1;
13880 return DAG.getConstant(0, VT);
13883 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13884 && "Unknown target vector shift-by-constant node");
13886 // Fold this packed vector shift into a build vector if SrcOp is a
13887 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13888 if (VT == SrcOp.getSimpleValueType() &&
13889 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13890 SmallVector<SDValue, 8> Elts;
13891 unsigned NumElts = SrcOp->getNumOperands();
13892 ConstantSDNode *ND;
13895 default: llvm_unreachable(nullptr);
13896 case X86ISD::VSHLI:
13897 for (unsigned i=0; i!=NumElts; ++i) {
13898 SDValue CurrentOp = SrcOp->getOperand(i);
13899 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13900 Elts.push_back(CurrentOp);
13903 ND = cast<ConstantSDNode>(CurrentOp);
13904 const APInt &C = ND->getAPIntValue();
13905 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13908 case X86ISD::VSRLI:
13909 for (unsigned i=0; i!=NumElts; ++i) {
13910 SDValue CurrentOp = SrcOp->getOperand(i);
13911 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13912 Elts.push_back(CurrentOp);
13915 ND = cast<ConstantSDNode>(CurrentOp);
13916 const APInt &C = ND->getAPIntValue();
13917 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13920 case X86ISD::VSRAI:
13921 for (unsigned i=0; i!=NumElts; ++i) {
13922 SDValue CurrentOp = SrcOp->getOperand(i);
13923 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13924 Elts.push_back(CurrentOp);
13927 ND = cast<ConstantSDNode>(CurrentOp);
13928 const APInt &C = ND->getAPIntValue();
13929 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13934 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13937 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13940 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13941 // may or may not be a constant. Takes immediate version of shift as input.
13942 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13943 SDValue SrcOp, SDValue ShAmt,
13944 SelectionDAG &DAG) {
13945 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13947 // Catch shift-by-constant.
13948 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13949 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13950 CShAmt->getZExtValue(), DAG);
13952 // Change opcode to non-immediate version
13954 default: llvm_unreachable("Unknown target vector shift node");
13955 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13956 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13957 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13960 // Need to build a vector containing shift amount
13961 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13964 ShOps[1] = DAG.getConstant(0, MVT::i32);
13965 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13966 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13968 // The return type has to be a 128-bit type with the same element
13969 // type as the input type.
13970 MVT EltVT = VT.getVectorElementType();
13971 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13973 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13974 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13977 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13979 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13981 default: return SDValue(); // Don't custom lower most intrinsics.
13982 // Comparison intrinsics.
13983 case Intrinsic::x86_sse_comieq_ss:
13984 case Intrinsic::x86_sse_comilt_ss:
13985 case Intrinsic::x86_sse_comile_ss:
13986 case Intrinsic::x86_sse_comigt_ss:
13987 case Intrinsic::x86_sse_comige_ss:
13988 case Intrinsic::x86_sse_comineq_ss:
13989 case Intrinsic::x86_sse_ucomieq_ss:
13990 case Intrinsic::x86_sse_ucomilt_ss:
13991 case Intrinsic::x86_sse_ucomile_ss:
13992 case Intrinsic::x86_sse_ucomigt_ss:
13993 case Intrinsic::x86_sse_ucomige_ss:
13994 case Intrinsic::x86_sse_ucomineq_ss:
13995 case Intrinsic::x86_sse2_comieq_sd:
13996 case Intrinsic::x86_sse2_comilt_sd:
13997 case Intrinsic::x86_sse2_comile_sd:
13998 case Intrinsic::x86_sse2_comigt_sd:
13999 case Intrinsic::x86_sse2_comige_sd:
14000 case Intrinsic::x86_sse2_comineq_sd:
14001 case Intrinsic::x86_sse2_ucomieq_sd:
14002 case Intrinsic::x86_sse2_ucomilt_sd:
14003 case Intrinsic::x86_sse2_ucomile_sd:
14004 case Intrinsic::x86_sse2_ucomigt_sd:
14005 case Intrinsic::x86_sse2_ucomige_sd:
14006 case Intrinsic::x86_sse2_ucomineq_sd: {
14010 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14011 case Intrinsic::x86_sse_comieq_ss:
14012 case Intrinsic::x86_sse2_comieq_sd:
14013 Opc = X86ISD::COMI;
14016 case Intrinsic::x86_sse_comilt_ss:
14017 case Intrinsic::x86_sse2_comilt_sd:
14018 Opc = X86ISD::COMI;
14021 case Intrinsic::x86_sse_comile_ss:
14022 case Intrinsic::x86_sse2_comile_sd:
14023 Opc = X86ISD::COMI;
14026 case Intrinsic::x86_sse_comigt_ss:
14027 case Intrinsic::x86_sse2_comigt_sd:
14028 Opc = X86ISD::COMI;
14031 case Intrinsic::x86_sse_comige_ss:
14032 case Intrinsic::x86_sse2_comige_sd:
14033 Opc = X86ISD::COMI;
14036 case Intrinsic::x86_sse_comineq_ss:
14037 case Intrinsic::x86_sse2_comineq_sd:
14038 Opc = X86ISD::COMI;
14041 case Intrinsic::x86_sse_ucomieq_ss:
14042 case Intrinsic::x86_sse2_ucomieq_sd:
14043 Opc = X86ISD::UCOMI;
14046 case Intrinsic::x86_sse_ucomilt_ss:
14047 case Intrinsic::x86_sse2_ucomilt_sd:
14048 Opc = X86ISD::UCOMI;
14051 case Intrinsic::x86_sse_ucomile_ss:
14052 case Intrinsic::x86_sse2_ucomile_sd:
14053 Opc = X86ISD::UCOMI;
14056 case Intrinsic::x86_sse_ucomigt_ss:
14057 case Intrinsic::x86_sse2_ucomigt_sd:
14058 Opc = X86ISD::UCOMI;
14061 case Intrinsic::x86_sse_ucomige_ss:
14062 case Intrinsic::x86_sse2_ucomige_sd:
14063 Opc = X86ISD::UCOMI;
14066 case Intrinsic::x86_sse_ucomineq_ss:
14067 case Intrinsic::x86_sse2_ucomineq_sd:
14068 Opc = X86ISD::UCOMI;
14073 SDValue LHS = Op.getOperand(1);
14074 SDValue RHS = Op.getOperand(2);
14075 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14076 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14077 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
14078 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14079 DAG.getConstant(X86CC, MVT::i8), Cond);
14080 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14083 // Arithmetic intrinsics.
14084 case Intrinsic::x86_sse2_pmulu_dq:
14085 case Intrinsic::x86_avx2_pmulu_dq:
14086 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14087 Op.getOperand(1), Op.getOperand(2));
14089 case Intrinsic::x86_sse41_pmuldq:
14090 case Intrinsic::x86_avx2_pmul_dq:
14091 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14092 Op.getOperand(1), Op.getOperand(2));
14094 case Intrinsic::x86_sse2_pmulhu_w:
14095 case Intrinsic::x86_avx2_pmulhu_w:
14096 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14097 Op.getOperand(1), Op.getOperand(2));
14099 case Intrinsic::x86_sse2_pmulh_w:
14100 case Intrinsic::x86_avx2_pmulh_w:
14101 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14102 Op.getOperand(1), Op.getOperand(2));
14104 // SSE2/AVX2 sub with unsigned saturation intrinsics
14105 case Intrinsic::x86_sse2_psubus_b:
14106 case Intrinsic::x86_sse2_psubus_w:
14107 case Intrinsic::x86_avx2_psubus_b:
14108 case Intrinsic::x86_avx2_psubus_w:
14109 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
14110 Op.getOperand(1), Op.getOperand(2));
14112 // SSE3/AVX horizontal add/sub intrinsics
14113 case Intrinsic::x86_sse3_hadd_ps:
14114 case Intrinsic::x86_sse3_hadd_pd:
14115 case Intrinsic::x86_avx_hadd_ps_256:
14116 case Intrinsic::x86_avx_hadd_pd_256:
14117 case Intrinsic::x86_sse3_hsub_ps:
14118 case Intrinsic::x86_sse3_hsub_pd:
14119 case Intrinsic::x86_avx_hsub_ps_256:
14120 case Intrinsic::x86_avx_hsub_pd_256:
14121 case Intrinsic::x86_ssse3_phadd_w_128:
14122 case Intrinsic::x86_ssse3_phadd_d_128:
14123 case Intrinsic::x86_avx2_phadd_w:
14124 case Intrinsic::x86_avx2_phadd_d:
14125 case Intrinsic::x86_ssse3_phsub_w_128:
14126 case Intrinsic::x86_ssse3_phsub_d_128:
14127 case Intrinsic::x86_avx2_phsub_w:
14128 case Intrinsic::x86_avx2_phsub_d: {
14131 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14132 case Intrinsic::x86_sse3_hadd_ps:
14133 case Intrinsic::x86_sse3_hadd_pd:
14134 case Intrinsic::x86_avx_hadd_ps_256:
14135 case Intrinsic::x86_avx_hadd_pd_256:
14136 Opcode = X86ISD::FHADD;
14138 case Intrinsic::x86_sse3_hsub_ps:
14139 case Intrinsic::x86_sse3_hsub_pd:
14140 case Intrinsic::x86_avx_hsub_ps_256:
14141 case Intrinsic::x86_avx_hsub_pd_256:
14142 Opcode = X86ISD::FHSUB;
14144 case Intrinsic::x86_ssse3_phadd_w_128:
14145 case Intrinsic::x86_ssse3_phadd_d_128:
14146 case Intrinsic::x86_avx2_phadd_w:
14147 case Intrinsic::x86_avx2_phadd_d:
14148 Opcode = X86ISD::HADD;
14150 case Intrinsic::x86_ssse3_phsub_w_128:
14151 case Intrinsic::x86_ssse3_phsub_d_128:
14152 case Intrinsic::x86_avx2_phsub_w:
14153 case Intrinsic::x86_avx2_phsub_d:
14154 Opcode = X86ISD::HSUB;
14157 return DAG.getNode(Opcode, dl, Op.getValueType(),
14158 Op.getOperand(1), Op.getOperand(2));
14161 // SSE2/SSE41/AVX2 integer max/min intrinsics.
14162 case Intrinsic::x86_sse2_pmaxu_b:
14163 case Intrinsic::x86_sse41_pmaxuw:
14164 case Intrinsic::x86_sse41_pmaxud:
14165 case Intrinsic::x86_avx2_pmaxu_b:
14166 case Intrinsic::x86_avx2_pmaxu_w:
14167 case Intrinsic::x86_avx2_pmaxu_d:
14168 case Intrinsic::x86_sse2_pminu_b:
14169 case Intrinsic::x86_sse41_pminuw:
14170 case Intrinsic::x86_sse41_pminud:
14171 case Intrinsic::x86_avx2_pminu_b:
14172 case Intrinsic::x86_avx2_pminu_w:
14173 case Intrinsic::x86_avx2_pminu_d:
14174 case Intrinsic::x86_sse41_pmaxsb:
14175 case Intrinsic::x86_sse2_pmaxs_w:
14176 case Intrinsic::x86_sse41_pmaxsd:
14177 case Intrinsic::x86_avx2_pmaxs_b:
14178 case Intrinsic::x86_avx2_pmaxs_w:
14179 case Intrinsic::x86_avx2_pmaxs_d:
14180 case Intrinsic::x86_sse41_pminsb:
14181 case Intrinsic::x86_sse2_pmins_w:
14182 case Intrinsic::x86_sse41_pminsd:
14183 case Intrinsic::x86_avx2_pmins_b:
14184 case Intrinsic::x86_avx2_pmins_w:
14185 case Intrinsic::x86_avx2_pmins_d: {
14188 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14189 case Intrinsic::x86_sse2_pmaxu_b:
14190 case Intrinsic::x86_sse41_pmaxuw:
14191 case Intrinsic::x86_sse41_pmaxud:
14192 case Intrinsic::x86_avx2_pmaxu_b:
14193 case Intrinsic::x86_avx2_pmaxu_w:
14194 case Intrinsic::x86_avx2_pmaxu_d:
14195 Opcode = X86ISD::UMAX;
14197 case Intrinsic::x86_sse2_pminu_b:
14198 case Intrinsic::x86_sse41_pminuw:
14199 case Intrinsic::x86_sse41_pminud:
14200 case Intrinsic::x86_avx2_pminu_b:
14201 case Intrinsic::x86_avx2_pminu_w:
14202 case Intrinsic::x86_avx2_pminu_d:
14203 Opcode = X86ISD::UMIN;
14205 case Intrinsic::x86_sse41_pmaxsb:
14206 case Intrinsic::x86_sse2_pmaxs_w:
14207 case Intrinsic::x86_sse41_pmaxsd:
14208 case Intrinsic::x86_avx2_pmaxs_b:
14209 case Intrinsic::x86_avx2_pmaxs_w:
14210 case Intrinsic::x86_avx2_pmaxs_d:
14211 Opcode = X86ISD::SMAX;
14213 case Intrinsic::x86_sse41_pminsb:
14214 case Intrinsic::x86_sse2_pmins_w:
14215 case Intrinsic::x86_sse41_pminsd:
14216 case Intrinsic::x86_avx2_pmins_b:
14217 case Intrinsic::x86_avx2_pmins_w:
14218 case Intrinsic::x86_avx2_pmins_d:
14219 Opcode = X86ISD::SMIN;
14222 return DAG.getNode(Opcode, dl, Op.getValueType(),
14223 Op.getOperand(1), Op.getOperand(2));
14226 // SSE/SSE2/AVX floating point max/min intrinsics.
14227 case Intrinsic::x86_sse_max_ps:
14228 case Intrinsic::x86_sse2_max_pd:
14229 case Intrinsic::x86_avx_max_ps_256:
14230 case Intrinsic::x86_avx_max_pd_256:
14231 case Intrinsic::x86_sse_min_ps:
14232 case Intrinsic::x86_sse2_min_pd:
14233 case Intrinsic::x86_avx_min_ps_256:
14234 case Intrinsic::x86_avx_min_pd_256: {
14237 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14238 case Intrinsic::x86_sse_max_ps:
14239 case Intrinsic::x86_sse2_max_pd:
14240 case Intrinsic::x86_avx_max_ps_256:
14241 case Intrinsic::x86_avx_max_pd_256:
14242 Opcode = X86ISD::FMAX;
14244 case Intrinsic::x86_sse_min_ps:
14245 case Intrinsic::x86_sse2_min_pd:
14246 case Intrinsic::x86_avx_min_ps_256:
14247 case Intrinsic::x86_avx_min_pd_256:
14248 Opcode = X86ISD::FMIN;
14251 return DAG.getNode(Opcode, dl, Op.getValueType(),
14252 Op.getOperand(1), Op.getOperand(2));
14255 // AVX2 variable shift intrinsics
14256 case Intrinsic::x86_avx2_psllv_d:
14257 case Intrinsic::x86_avx2_psllv_q:
14258 case Intrinsic::x86_avx2_psllv_d_256:
14259 case Intrinsic::x86_avx2_psllv_q_256:
14260 case Intrinsic::x86_avx2_psrlv_d:
14261 case Intrinsic::x86_avx2_psrlv_q:
14262 case Intrinsic::x86_avx2_psrlv_d_256:
14263 case Intrinsic::x86_avx2_psrlv_q_256:
14264 case Intrinsic::x86_avx2_psrav_d:
14265 case Intrinsic::x86_avx2_psrav_d_256: {
14268 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14269 case Intrinsic::x86_avx2_psllv_d:
14270 case Intrinsic::x86_avx2_psllv_q:
14271 case Intrinsic::x86_avx2_psllv_d_256:
14272 case Intrinsic::x86_avx2_psllv_q_256:
14275 case Intrinsic::x86_avx2_psrlv_d:
14276 case Intrinsic::x86_avx2_psrlv_q:
14277 case Intrinsic::x86_avx2_psrlv_d_256:
14278 case Intrinsic::x86_avx2_psrlv_q_256:
14281 case Intrinsic::x86_avx2_psrav_d:
14282 case Intrinsic::x86_avx2_psrav_d_256:
14286 return DAG.getNode(Opcode, dl, Op.getValueType(),
14287 Op.getOperand(1), Op.getOperand(2));
14290 case Intrinsic::x86_sse2_packssdw_128:
14291 case Intrinsic::x86_sse2_packsswb_128:
14292 case Intrinsic::x86_avx2_packssdw:
14293 case Intrinsic::x86_avx2_packsswb:
14294 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14295 Op.getOperand(1), Op.getOperand(2));
14297 case Intrinsic::x86_sse2_packuswb_128:
14298 case Intrinsic::x86_sse41_packusdw:
14299 case Intrinsic::x86_avx2_packuswb:
14300 case Intrinsic::x86_avx2_packusdw:
14301 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14302 Op.getOperand(1), Op.getOperand(2));
14304 case Intrinsic::x86_ssse3_pshuf_b_128:
14305 case Intrinsic::x86_avx2_pshuf_b:
14306 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14307 Op.getOperand(1), Op.getOperand(2));
14309 case Intrinsic::x86_sse2_pshuf_d:
14310 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14311 Op.getOperand(1), Op.getOperand(2));
14313 case Intrinsic::x86_sse2_pshufl_w:
14314 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14315 Op.getOperand(1), Op.getOperand(2));
14317 case Intrinsic::x86_sse2_pshufh_w:
14318 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14319 Op.getOperand(1), Op.getOperand(2));
14321 case Intrinsic::x86_ssse3_psign_b_128:
14322 case Intrinsic::x86_ssse3_psign_w_128:
14323 case Intrinsic::x86_ssse3_psign_d_128:
14324 case Intrinsic::x86_avx2_psign_b:
14325 case Intrinsic::x86_avx2_psign_w:
14326 case Intrinsic::x86_avx2_psign_d:
14327 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14328 Op.getOperand(1), Op.getOperand(2));
14330 case Intrinsic::x86_sse41_insertps:
14331 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14332 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14334 case Intrinsic::x86_avx_vperm2f128_ps_256:
14335 case Intrinsic::x86_avx_vperm2f128_pd_256:
14336 case Intrinsic::x86_avx_vperm2f128_si_256:
14337 case Intrinsic::x86_avx2_vperm2i128:
14338 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14339 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14341 case Intrinsic::x86_avx2_permd:
14342 case Intrinsic::x86_avx2_permps:
14343 // Operands intentionally swapped. Mask is last operand to intrinsic,
14344 // but second operand for node/instruction.
14345 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14346 Op.getOperand(2), Op.getOperand(1));
14348 case Intrinsic::x86_sse_sqrt_ps:
14349 case Intrinsic::x86_sse2_sqrt_pd:
14350 case Intrinsic::x86_avx_sqrt_ps_256:
14351 case Intrinsic::x86_avx_sqrt_pd_256:
14352 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14354 // ptest and testp intrinsics. The intrinsic these come from are designed to
14355 // return an integer value, not just an instruction so lower it to the ptest
14356 // or testp pattern and a setcc for the result.
14357 case Intrinsic::x86_sse41_ptestz:
14358 case Intrinsic::x86_sse41_ptestc:
14359 case Intrinsic::x86_sse41_ptestnzc:
14360 case Intrinsic::x86_avx_ptestz_256:
14361 case Intrinsic::x86_avx_ptestc_256:
14362 case Intrinsic::x86_avx_ptestnzc_256:
14363 case Intrinsic::x86_avx_vtestz_ps:
14364 case Intrinsic::x86_avx_vtestc_ps:
14365 case Intrinsic::x86_avx_vtestnzc_ps:
14366 case Intrinsic::x86_avx_vtestz_pd:
14367 case Intrinsic::x86_avx_vtestc_pd:
14368 case Intrinsic::x86_avx_vtestnzc_pd:
14369 case Intrinsic::x86_avx_vtestz_ps_256:
14370 case Intrinsic::x86_avx_vtestc_ps_256:
14371 case Intrinsic::x86_avx_vtestnzc_ps_256:
14372 case Intrinsic::x86_avx_vtestz_pd_256:
14373 case Intrinsic::x86_avx_vtestc_pd_256:
14374 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14375 bool IsTestPacked = false;
14378 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14379 case Intrinsic::x86_avx_vtestz_ps:
14380 case Intrinsic::x86_avx_vtestz_pd:
14381 case Intrinsic::x86_avx_vtestz_ps_256:
14382 case Intrinsic::x86_avx_vtestz_pd_256:
14383 IsTestPacked = true; // Fallthrough
14384 case Intrinsic::x86_sse41_ptestz:
14385 case Intrinsic::x86_avx_ptestz_256:
14387 X86CC = X86::COND_E;
14389 case Intrinsic::x86_avx_vtestc_ps:
14390 case Intrinsic::x86_avx_vtestc_pd:
14391 case Intrinsic::x86_avx_vtestc_ps_256:
14392 case Intrinsic::x86_avx_vtestc_pd_256:
14393 IsTestPacked = true; // Fallthrough
14394 case Intrinsic::x86_sse41_ptestc:
14395 case Intrinsic::x86_avx_ptestc_256:
14397 X86CC = X86::COND_B;
14399 case Intrinsic::x86_avx_vtestnzc_ps:
14400 case Intrinsic::x86_avx_vtestnzc_pd:
14401 case Intrinsic::x86_avx_vtestnzc_ps_256:
14402 case Intrinsic::x86_avx_vtestnzc_pd_256:
14403 IsTestPacked = true; // Fallthrough
14404 case Intrinsic::x86_sse41_ptestnzc:
14405 case Intrinsic::x86_avx_ptestnzc_256:
14407 X86CC = X86::COND_A;
14411 SDValue LHS = Op.getOperand(1);
14412 SDValue RHS = Op.getOperand(2);
14413 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14414 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14415 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14416 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14417 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14419 case Intrinsic::x86_avx512_kortestz_w:
14420 case Intrinsic::x86_avx512_kortestc_w: {
14421 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14422 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14423 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14424 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14425 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14426 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14427 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14430 // SSE/AVX shift intrinsics
14431 case Intrinsic::x86_sse2_psll_w:
14432 case Intrinsic::x86_sse2_psll_d:
14433 case Intrinsic::x86_sse2_psll_q:
14434 case Intrinsic::x86_avx2_psll_w:
14435 case Intrinsic::x86_avx2_psll_d:
14436 case Intrinsic::x86_avx2_psll_q:
14437 case Intrinsic::x86_sse2_psrl_w:
14438 case Intrinsic::x86_sse2_psrl_d:
14439 case Intrinsic::x86_sse2_psrl_q:
14440 case Intrinsic::x86_avx2_psrl_w:
14441 case Intrinsic::x86_avx2_psrl_d:
14442 case Intrinsic::x86_avx2_psrl_q:
14443 case Intrinsic::x86_sse2_psra_w:
14444 case Intrinsic::x86_sse2_psra_d:
14445 case Intrinsic::x86_avx2_psra_w:
14446 case Intrinsic::x86_avx2_psra_d: {
14449 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14450 case Intrinsic::x86_sse2_psll_w:
14451 case Intrinsic::x86_sse2_psll_d:
14452 case Intrinsic::x86_sse2_psll_q:
14453 case Intrinsic::x86_avx2_psll_w:
14454 case Intrinsic::x86_avx2_psll_d:
14455 case Intrinsic::x86_avx2_psll_q:
14456 Opcode = X86ISD::VSHL;
14458 case Intrinsic::x86_sse2_psrl_w:
14459 case Intrinsic::x86_sse2_psrl_d:
14460 case Intrinsic::x86_sse2_psrl_q:
14461 case Intrinsic::x86_avx2_psrl_w:
14462 case Intrinsic::x86_avx2_psrl_d:
14463 case Intrinsic::x86_avx2_psrl_q:
14464 Opcode = X86ISD::VSRL;
14466 case Intrinsic::x86_sse2_psra_w:
14467 case Intrinsic::x86_sse2_psra_d:
14468 case Intrinsic::x86_avx2_psra_w:
14469 case Intrinsic::x86_avx2_psra_d:
14470 Opcode = X86ISD::VSRA;
14473 return DAG.getNode(Opcode, dl, Op.getValueType(),
14474 Op.getOperand(1), Op.getOperand(2));
14477 // SSE/AVX immediate shift intrinsics
14478 case Intrinsic::x86_sse2_pslli_w:
14479 case Intrinsic::x86_sse2_pslli_d:
14480 case Intrinsic::x86_sse2_pslli_q:
14481 case Intrinsic::x86_avx2_pslli_w:
14482 case Intrinsic::x86_avx2_pslli_d:
14483 case Intrinsic::x86_avx2_pslli_q:
14484 case Intrinsic::x86_sse2_psrli_w:
14485 case Intrinsic::x86_sse2_psrli_d:
14486 case Intrinsic::x86_sse2_psrli_q:
14487 case Intrinsic::x86_avx2_psrli_w:
14488 case Intrinsic::x86_avx2_psrli_d:
14489 case Intrinsic::x86_avx2_psrli_q:
14490 case Intrinsic::x86_sse2_psrai_w:
14491 case Intrinsic::x86_sse2_psrai_d:
14492 case Intrinsic::x86_avx2_psrai_w:
14493 case Intrinsic::x86_avx2_psrai_d: {
14496 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14497 case Intrinsic::x86_sse2_pslli_w:
14498 case Intrinsic::x86_sse2_pslli_d:
14499 case Intrinsic::x86_sse2_pslli_q:
14500 case Intrinsic::x86_avx2_pslli_w:
14501 case Intrinsic::x86_avx2_pslli_d:
14502 case Intrinsic::x86_avx2_pslli_q:
14503 Opcode = X86ISD::VSHLI;
14505 case Intrinsic::x86_sse2_psrli_w:
14506 case Intrinsic::x86_sse2_psrli_d:
14507 case Intrinsic::x86_sse2_psrli_q:
14508 case Intrinsic::x86_avx2_psrli_w:
14509 case Intrinsic::x86_avx2_psrli_d:
14510 case Intrinsic::x86_avx2_psrli_q:
14511 Opcode = X86ISD::VSRLI;
14513 case Intrinsic::x86_sse2_psrai_w:
14514 case Intrinsic::x86_sse2_psrai_d:
14515 case Intrinsic::x86_avx2_psrai_w:
14516 case Intrinsic::x86_avx2_psrai_d:
14517 Opcode = X86ISD::VSRAI;
14520 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14521 Op.getOperand(1), Op.getOperand(2), DAG);
14524 case Intrinsic::x86_sse42_pcmpistria128:
14525 case Intrinsic::x86_sse42_pcmpestria128:
14526 case Intrinsic::x86_sse42_pcmpistric128:
14527 case Intrinsic::x86_sse42_pcmpestric128:
14528 case Intrinsic::x86_sse42_pcmpistrio128:
14529 case Intrinsic::x86_sse42_pcmpestrio128:
14530 case Intrinsic::x86_sse42_pcmpistris128:
14531 case Intrinsic::x86_sse42_pcmpestris128:
14532 case Intrinsic::x86_sse42_pcmpistriz128:
14533 case Intrinsic::x86_sse42_pcmpestriz128: {
14537 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14538 case Intrinsic::x86_sse42_pcmpistria128:
14539 Opcode = X86ISD::PCMPISTRI;
14540 X86CC = X86::COND_A;
14542 case Intrinsic::x86_sse42_pcmpestria128:
14543 Opcode = X86ISD::PCMPESTRI;
14544 X86CC = X86::COND_A;
14546 case Intrinsic::x86_sse42_pcmpistric128:
14547 Opcode = X86ISD::PCMPISTRI;
14548 X86CC = X86::COND_B;
14550 case Intrinsic::x86_sse42_pcmpestric128:
14551 Opcode = X86ISD::PCMPESTRI;
14552 X86CC = X86::COND_B;
14554 case Intrinsic::x86_sse42_pcmpistrio128:
14555 Opcode = X86ISD::PCMPISTRI;
14556 X86CC = X86::COND_O;
14558 case Intrinsic::x86_sse42_pcmpestrio128:
14559 Opcode = X86ISD::PCMPESTRI;
14560 X86CC = X86::COND_O;
14562 case Intrinsic::x86_sse42_pcmpistris128:
14563 Opcode = X86ISD::PCMPISTRI;
14564 X86CC = X86::COND_S;
14566 case Intrinsic::x86_sse42_pcmpestris128:
14567 Opcode = X86ISD::PCMPESTRI;
14568 X86CC = X86::COND_S;
14570 case Intrinsic::x86_sse42_pcmpistriz128:
14571 Opcode = X86ISD::PCMPISTRI;
14572 X86CC = X86::COND_E;
14574 case Intrinsic::x86_sse42_pcmpestriz128:
14575 Opcode = X86ISD::PCMPESTRI;
14576 X86CC = X86::COND_E;
14579 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14580 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14581 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14582 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14583 DAG.getConstant(X86CC, MVT::i8),
14584 SDValue(PCMP.getNode(), 1));
14585 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14588 case Intrinsic::x86_sse42_pcmpistri128:
14589 case Intrinsic::x86_sse42_pcmpestri128: {
14591 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14592 Opcode = X86ISD::PCMPISTRI;
14594 Opcode = X86ISD::PCMPESTRI;
14596 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14597 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14598 return DAG.getNode(Opcode, dl, VTs, NewOps);
14600 case Intrinsic::x86_fma_vfmadd_ps:
14601 case Intrinsic::x86_fma_vfmadd_pd:
14602 case Intrinsic::x86_fma_vfmsub_ps:
14603 case Intrinsic::x86_fma_vfmsub_pd:
14604 case Intrinsic::x86_fma_vfnmadd_ps:
14605 case Intrinsic::x86_fma_vfnmadd_pd:
14606 case Intrinsic::x86_fma_vfnmsub_ps:
14607 case Intrinsic::x86_fma_vfnmsub_pd:
14608 case Intrinsic::x86_fma_vfmaddsub_ps:
14609 case Intrinsic::x86_fma_vfmaddsub_pd:
14610 case Intrinsic::x86_fma_vfmsubadd_ps:
14611 case Intrinsic::x86_fma_vfmsubadd_pd:
14612 case Intrinsic::x86_fma_vfmadd_ps_256:
14613 case Intrinsic::x86_fma_vfmadd_pd_256:
14614 case Intrinsic::x86_fma_vfmsub_ps_256:
14615 case Intrinsic::x86_fma_vfmsub_pd_256:
14616 case Intrinsic::x86_fma_vfnmadd_ps_256:
14617 case Intrinsic::x86_fma_vfnmadd_pd_256:
14618 case Intrinsic::x86_fma_vfnmsub_ps_256:
14619 case Intrinsic::x86_fma_vfnmsub_pd_256:
14620 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14621 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14622 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14623 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14624 case Intrinsic::x86_fma_vfmadd_ps_512:
14625 case Intrinsic::x86_fma_vfmadd_pd_512:
14626 case Intrinsic::x86_fma_vfmsub_ps_512:
14627 case Intrinsic::x86_fma_vfmsub_pd_512:
14628 case Intrinsic::x86_fma_vfnmadd_ps_512:
14629 case Intrinsic::x86_fma_vfnmadd_pd_512:
14630 case Intrinsic::x86_fma_vfnmsub_ps_512:
14631 case Intrinsic::x86_fma_vfnmsub_pd_512:
14632 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14633 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14634 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14635 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14638 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14639 case Intrinsic::x86_fma_vfmadd_ps:
14640 case Intrinsic::x86_fma_vfmadd_pd:
14641 case Intrinsic::x86_fma_vfmadd_ps_256:
14642 case Intrinsic::x86_fma_vfmadd_pd_256:
14643 case Intrinsic::x86_fma_vfmadd_ps_512:
14644 case Intrinsic::x86_fma_vfmadd_pd_512:
14645 Opc = X86ISD::FMADD;
14647 case Intrinsic::x86_fma_vfmsub_ps:
14648 case Intrinsic::x86_fma_vfmsub_pd:
14649 case Intrinsic::x86_fma_vfmsub_ps_256:
14650 case Intrinsic::x86_fma_vfmsub_pd_256:
14651 case Intrinsic::x86_fma_vfmsub_ps_512:
14652 case Intrinsic::x86_fma_vfmsub_pd_512:
14653 Opc = X86ISD::FMSUB;
14655 case Intrinsic::x86_fma_vfnmadd_ps:
14656 case Intrinsic::x86_fma_vfnmadd_pd:
14657 case Intrinsic::x86_fma_vfnmadd_ps_256:
14658 case Intrinsic::x86_fma_vfnmadd_pd_256:
14659 case Intrinsic::x86_fma_vfnmadd_ps_512:
14660 case Intrinsic::x86_fma_vfnmadd_pd_512:
14661 Opc = X86ISD::FNMADD;
14663 case Intrinsic::x86_fma_vfnmsub_ps:
14664 case Intrinsic::x86_fma_vfnmsub_pd:
14665 case Intrinsic::x86_fma_vfnmsub_ps_256:
14666 case Intrinsic::x86_fma_vfnmsub_pd_256:
14667 case Intrinsic::x86_fma_vfnmsub_ps_512:
14668 case Intrinsic::x86_fma_vfnmsub_pd_512:
14669 Opc = X86ISD::FNMSUB;
14671 case Intrinsic::x86_fma_vfmaddsub_ps:
14672 case Intrinsic::x86_fma_vfmaddsub_pd:
14673 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14674 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14675 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14676 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14677 Opc = X86ISD::FMADDSUB;
14679 case Intrinsic::x86_fma_vfmsubadd_ps:
14680 case Intrinsic::x86_fma_vfmsubadd_pd:
14681 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14682 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14683 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14684 case Intrinsic::x86_fma_vfmsubadd_pd_512:
14685 Opc = X86ISD::FMSUBADD;
14689 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14690 Op.getOperand(2), Op.getOperand(3));
14695 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14696 SDValue Src, SDValue Mask, SDValue Base,
14697 SDValue Index, SDValue ScaleOp, SDValue Chain,
14698 const X86Subtarget * Subtarget) {
14700 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14701 assert(C && "Invalid scale type");
14702 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14703 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14704 Index.getSimpleValueType().getVectorNumElements());
14706 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14708 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14710 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14711 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14712 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14713 SDValue Segment = DAG.getRegister(0, MVT::i32);
14714 if (Src.getOpcode() == ISD::UNDEF)
14715 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14716 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14717 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14718 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14719 return DAG.getMergeValues(RetOps, dl);
14722 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14723 SDValue Src, SDValue Mask, SDValue Base,
14724 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14726 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14727 assert(C && "Invalid scale type");
14728 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14729 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14730 SDValue Segment = DAG.getRegister(0, MVT::i32);
14731 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14732 Index.getSimpleValueType().getVectorNumElements());
14734 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14736 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14738 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14739 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14740 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14741 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14742 return SDValue(Res, 1);
14745 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14746 SDValue Mask, SDValue Base, SDValue Index,
14747 SDValue ScaleOp, SDValue Chain) {
14749 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14750 assert(C && "Invalid scale type");
14751 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14752 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14753 SDValue Segment = DAG.getRegister(0, MVT::i32);
14755 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14757 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14759 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14761 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14762 //SDVTList VTs = DAG.getVTList(MVT::Other);
14763 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14764 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14765 return SDValue(Res, 0);
14768 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14769 // read performance monitor counters (x86_rdpmc).
14770 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14771 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14772 SmallVectorImpl<SDValue> &Results) {
14773 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14774 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14777 // The ECX register is used to select the index of the performance counter
14779 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14781 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14783 // Reads the content of a 64-bit performance counter and returns it in the
14784 // registers EDX:EAX.
14785 if (Subtarget->is64Bit()) {
14786 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14787 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14790 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14791 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14794 Chain = HI.getValue(1);
14796 if (Subtarget->is64Bit()) {
14797 // The EAX register is loaded with the low-order 32 bits. The EDX register
14798 // is loaded with the supported high-order bits of the counter.
14799 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14800 DAG.getConstant(32, MVT::i8));
14801 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14802 Results.push_back(Chain);
14806 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14807 SDValue Ops[] = { LO, HI };
14808 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14809 Results.push_back(Pair);
14810 Results.push_back(Chain);
14813 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14814 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14815 // also used to custom lower READCYCLECOUNTER nodes.
14816 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14817 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14818 SmallVectorImpl<SDValue> &Results) {
14819 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14820 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14823 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14824 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14825 // and the EAX register is loaded with the low-order 32 bits.
14826 if (Subtarget->is64Bit()) {
14827 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14828 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14831 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14832 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14835 SDValue Chain = HI.getValue(1);
14837 if (Opcode == X86ISD::RDTSCP_DAG) {
14838 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14840 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14841 // the ECX register. Add 'ecx' explicitly to the chain.
14842 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14844 // Explicitly store the content of ECX at the location passed in input
14845 // to the 'rdtscp' intrinsic.
14846 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14847 MachinePointerInfo(), false, false, 0);
14850 if (Subtarget->is64Bit()) {
14851 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14852 // the EAX register is loaded with the low-order 32 bits.
14853 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14854 DAG.getConstant(32, MVT::i8));
14855 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14856 Results.push_back(Chain);
14860 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14861 SDValue Ops[] = { LO, HI };
14862 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14863 Results.push_back(Pair);
14864 Results.push_back(Chain);
14867 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14868 SelectionDAG &DAG) {
14869 SmallVector<SDValue, 2> Results;
14871 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14873 return DAG.getMergeValues(Results, DL);
14876 enum IntrinsicType {
14877 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14880 struct IntrinsicData {
14881 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14882 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14883 IntrinsicType Type;
14888 std::map < unsigned, IntrinsicData> IntrMap;
14889 static void InitIntinsicsMap() {
14890 static bool Initialized = false;
14893 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14894 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14895 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14896 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14897 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14898 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14899 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14900 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14901 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14902 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14903 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
14904 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14905 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
14906 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14907 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
14908 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14909 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
14910 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14912 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14913 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14914 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
14915 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14916 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
14917 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14918 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
14919 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14920 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
14921 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14922 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
14923 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14924 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
14925 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14926 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
14927 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14929 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
14930 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14931 X86::VGATHERPF1QPSm)));
14932 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
14933 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14934 X86::VGATHERPF1QPDm)));
14935 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
14936 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14937 X86::VGATHERPF1DPDm)));
14938 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
14939 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14940 X86::VGATHERPF1DPSm)));
14941 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
14942 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14943 X86::VSCATTERPF1QPSm)));
14944 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
14945 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14946 X86::VSCATTERPF1QPDm)));
14947 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
14948 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14949 X86::VSCATTERPF1DPDm)));
14950 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
14951 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14952 X86::VSCATTERPF1DPSm)));
14953 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14954 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14955 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14956 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14957 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14958 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14959 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14960 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14961 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14962 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14963 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14964 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14965 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14966 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
14967 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14968 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
14969 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14970 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
14971 IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14972 IntrinsicData(RDPMC, X86ISD::RDPMC_DAG, 0)));
14973 Initialized = true;
14976 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14977 SelectionDAG &DAG) {
14978 InitIntinsicsMap();
14979 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14980 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14981 if (itr == IntrMap.end())
14985 IntrinsicData Intr = itr->second;
14986 switch(Intr.Type) {
14989 // Emit the node with the right value type.
14990 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14991 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14993 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14994 // Otherwise return the value from Rand, which is always 0, casted to i32.
14995 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14996 DAG.getConstant(1, Op->getValueType(1)),
14997 DAG.getConstant(X86::COND_B, MVT::i32),
14998 SDValue(Result.getNode(), 1) };
14999 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15000 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15003 // Return { result, isValid, chain }.
15004 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15005 SDValue(Result.getNode(), 2));
15008 //gather(v1, mask, index, base, scale);
15009 SDValue Chain = Op.getOperand(0);
15010 SDValue Src = Op.getOperand(2);
15011 SDValue Base = Op.getOperand(3);
15012 SDValue Index = Op.getOperand(4);
15013 SDValue Mask = Op.getOperand(5);
15014 SDValue Scale = Op.getOperand(6);
15015 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15019 //scatter(base, mask, index, v1, scale);
15020 SDValue Chain = Op.getOperand(0);
15021 SDValue Base = Op.getOperand(2);
15022 SDValue Mask = Op.getOperand(3);
15023 SDValue Index = Op.getOperand(4);
15024 SDValue Src = Op.getOperand(5);
15025 SDValue Scale = Op.getOperand(6);
15026 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15029 SDValue Hint = Op.getOperand(6);
15031 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15032 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15033 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15034 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
15035 SDValue Chain = Op.getOperand(0);
15036 SDValue Mask = Op.getOperand(2);
15037 SDValue Index = Op.getOperand(3);
15038 SDValue Base = Op.getOperand(4);
15039 SDValue Scale = Op.getOperand(5);
15040 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15042 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15044 SmallVector<SDValue, 2> Results;
15045 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
15046 return DAG.getMergeValues(Results, dl);
15048 // Read Performance Monitoring Counters.
15050 SmallVector<SDValue, 2> Results;
15051 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15052 return DAG.getMergeValues(Results, dl);
15054 // XTEST intrinsics.
15056 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15057 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
15058 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15059 DAG.getConstant(X86::COND_NE, MVT::i8),
15061 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15062 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15063 Ret, SDValue(InTrans.getNode(), 1));
15066 llvm_unreachable("Unknown Intrinsic Type");
15069 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15070 SelectionDAG &DAG) const {
15071 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15072 MFI->setReturnAddressIsTaken(true);
15074 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15077 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15079 EVT PtrVT = getPointerTy();
15082 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15083 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15084 DAG.getSubtarget().getRegisterInfo());
15085 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15086 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15087 DAG.getNode(ISD::ADD, dl, PtrVT,
15088 FrameAddr, Offset),
15089 MachinePointerInfo(), false, false, false, 0);
15092 // Just load the return address.
15093 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15094 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15095 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15098 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15099 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15100 MFI->setFrameAddressIsTaken(true);
15102 EVT VT = Op.getValueType();
15103 SDLoc dl(Op); // FIXME probably not meaningful
15104 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15105 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15106 DAG.getSubtarget().getRegisterInfo());
15107 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15108 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15109 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15110 "Invalid Frame Register!");
15111 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15113 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15114 MachinePointerInfo(),
15115 false, false, false, 0);
15119 // FIXME? Maybe this could be a TableGen attribute on some registers and
15120 // this table could be generated automatically from RegInfo.
15121 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15123 unsigned Reg = StringSwitch<unsigned>(RegName)
15124 .Case("esp", X86::ESP)
15125 .Case("rsp", X86::RSP)
15129 report_fatal_error("Invalid register name global variable");
15132 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15133 SelectionDAG &DAG) const {
15134 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15135 DAG.getSubtarget().getRegisterInfo());
15136 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15139 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15140 SDValue Chain = Op.getOperand(0);
15141 SDValue Offset = Op.getOperand(1);
15142 SDValue Handler = Op.getOperand(2);
15145 EVT PtrVT = getPointerTy();
15146 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15147 DAG.getSubtarget().getRegisterInfo());
15148 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15149 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15150 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15151 "Invalid Frame Register!");
15152 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15153 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15155 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15156 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15157 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15158 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15160 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15162 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15163 DAG.getRegister(StoreAddrReg, PtrVT));
15166 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15167 SelectionDAG &DAG) const {
15169 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15170 DAG.getVTList(MVT::i32, MVT::Other),
15171 Op.getOperand(0), Op.getOperand(1));
15174 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15175 SelectionDAG &DAG) const {
15177 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15178 Op.getOperand(0), Op.getOperand(1));
15181 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15182 return Op.getOperand(0);
15185 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15186 SelectionDAG &DAG) const {
15187 SDValue Root = Op.getOperand(0);
15188 SDValue Trmp = Op.getOperand(1); // trampoline
15189 SDValue FPtr = Op.getOperand(2); // nested function
15190 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15193 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15194 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15196 if (Subtarget->is64Bit()) {
15197 SDValue OutChains[6];
15199 // Large code-model.
15200 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15201 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15203 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15204 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15206 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15208 // Load the pointer to the nested function into R11.
15209 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15210 SDValue Addr = Trmp;
15211 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15212 Addr, MachinePointerInfo(TrmpAddr),
15215 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15216 DAG.getConstant(2, MVT::i64));
15217 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15218 MachinePointerInfo(TrmpAddr, 2),
15221 // Load the 'nest' parameter value into R10.
15222 // R10 is specified in X86CallingConv.td
15223 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15224 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15225 DAG.getConstant(10, MVT::i64));
15226 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15227 Addr, MachinePointerInfo(TrmpAddr, 10),
15230 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15231 DAG.getConstant(12, MVT::i64));
15232 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15233 MachinePointerInfo(TrmpAddr, 12),
15236 // Jump to the nested function.
15237 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15238 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15239 DAG.getConstant(20, MVT::i64));
15240 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15241 Addr, MachinePointerInfo(TrmpAddr, 20),
15244 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15245 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15246 DAG.getConstant(22, MVT::i64));
15247 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15248 MachinePointerInfo(TrmpAddr, 22),
15251 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15253 const Function *Func =
15254 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15255 CallingConv::ID CC = Func->getCallingConv();
15260 llvm_unreachable("Unsupported calling convention");
15261 case CallingConv::C:
15262 case CallingConv::X86_StdCall: {
15263 // Pass 'nest' parameter in ECX.
15264 // Must be kept in sync with X86CallingConv.td
15265 NestReg = X86::ECX;
15267 // Check that ECX wasn't needed by an 'inreg' parameter.
15268 FunctionType *FTy = Func->getFunctionType();
15269 const AttributeSet &Attrs = Func->getAttributes();
15271 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15272 unsigned InRegCount = 0;
15275 for (FunctionType::param_iterator I = FTy->param_begin(),
15276 E = FTy->param_end(); I != E; ++I, ++Idx)
15277 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15278 // FIXME: should only count parameters that are lowered to integers.
15279 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15281 if (InRegCount > 2) {
15282 report_fatal_error("Nest register in use - reduce number of inreg"
15288 case CallingConv::X86_FastCall:
15289 case CallingConv::X86_ThisCall:
15290 case CallingConv::Fast:
15291 // Pass 'nest' parameter in EAX.
15292 // Must be kept in sync with X86CallingConv.td
15293 NestReg = X86::EAX;
15297 SDValue OutChains[4];
15298 SDValue Addr, Disp;
15300 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15301 DAG.getConstant(10, MVT::i32));
15302 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15304 // This is storing the opcode for MOV32ri.
15305 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15306 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15307 OutChains[0] = DAG.getStore(Root, dl,
15308 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15309 Trmp, MachinePointerInfo(TrmpAddr),
15312 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15313 DAG.getConstant(1, MVT::i32));
15314 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15315 MachinePointerInfo(TrmpAddr, 1),
15318 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15319 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15320 DAG.getConstant(5, MVT::i32));
15321 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15322 MachinePointerInfo(TrmpAddr, 5),
15325 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15326 DAG.getConstant(6, MVT::i32));
15327 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15328 MachinePointerInfo(TrmpAddr, 6),
15331 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15335 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15336 SelectionDAG &DAG) const {
15338 The rounding mode is in bits 11:10 of FPSR, and has the following
15340 00 Round to nearest
15345 FLT_ROUNDS, on the other hand, expects the following:
15352 To perform the conversion, we do:
15353 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15356 MachineFunction &MF = DAG.getMachineFunction();
15357 const TargetMachine &TM = MF.getTarget();
15358 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15359 unsigned StackAlignment = TFI.getStackAlignment();
15360 MVT VT = Op.getSimpleValueType();
15363 // Save FP Control Word to stack slot
15364 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15365 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15367 MachineMemOperand *MMO =
15368 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15369 MachineMemOperand::MOStore, 2, 2);
15371 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15372 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15373 DAG.getVTList(MVT::Other),
15374 Ops, MVT::i16, MMO);
15376 // Load FP Control Word from stack slot
15377 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15378 MachinePointerInfo(), false, false, false, 0);
15380 // Transform as necessary
15382 DAG.getNode(ISD::SRL, DL, MVT::i16,
15383 DAG.getNode(ISD::AND, DL, MVT::i16,
15384 CWD, DAG.getConstant(0x800, MVT::i16)),
15385 DAG.getConstant(11, MVT::i8));
15387 DAG.getNode(ISD::SRL, DL, MVT::i16,
15388 DAG.getNode(ISD::AND, DL, MVT::i16,
15389 CWD, DAG.getConstant(0x400, MVT::i16)),
15390 DAG.getConstant(9, MVT::i8));
15393 DAG.getNode(ISD::AND, DL, MVT::i16,
15394 DAG.getNode(ISD::ADD, DL, MVT::i16,
15395 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15396 DAG.getConstant(1, MVT::i16)),
15397 DAG.getConstant(3, MVT::i16));
15399 return DAG.getNode((VT.getSizeInBits() < 16 ?
15400 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15403 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15404 MVT VT = Op.getSimpleValueType();
15406 unsigned NumBits = VT.getSizeInBits();
15409 Op = Op.getOperand(0);
15410 if (VT == MVT::i8) {
15411 // Zero extend to i32 since there is not an i8 bsr.
15413 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15416 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15417 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15418 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15420 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15423 DAG.getConstant(NumBits+NumBits-1, OpVT),
15424 DAG.getConstant(X86::COND_E, MVT::i8),
15427 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15429 // Finally xor with NumBits-1.
15430 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15433 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15437 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15438 MVT VT = Op.getSimpleValueType();
15440 unsigned NumBits = VT.getSizeInBits();
15443 Op = Op.getOperand(0);
15444 if (VT == MVT::i8) {
15445 // Zero extend to i32 since there is not an i8 bsr.
15447 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15450 // Issue a bsr (scan bits in reverse).
15451 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15452 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15454 // And xor with NumBits-1.
15455 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15458 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15462 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15463 MVT VT = Op.getSimpleValueType();
15464 unsigned NumBits = VT.getSizeInBits();
15466 Op = Op.getOperand(0);
15468 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15469 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15470 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15472 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15475 DAG.getConstant(NumBits, VT),
15476 DAG.getConstant(X86::COND_E, MVT::i8),
15479 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15482 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15483 // ones, and then concatenate the result back.
15484 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15485 MVT VT = Op.getSimpleValueType();
15487 assert(VT.is256BitVector() && VT.isInteger() &&
15488 "Unsupported value type for operation");
15490 unsigned NumElems = VT.getVectorNumElements();
15493 // Extract the LHS vectors
15494 SDValue LHS = Op.getOperand(0);
15495 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15496 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15498 // Extract the RHS vectors
15499 SDValue RHS = Op.getOperand(1);
15500 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15501 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15503 MVT EltVT = VT.getVectorElementType();
15504 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15506 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15507 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15508 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15511 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15512 assert(Op.getSimpleValueType().is256BitVector() &&
15513 Op.getSimpleValueType().isInteger() &&
15514 "Only handle AVX 256-bit vector integer operation");
15515 return Lower256IntArith(Op, DAG);
15518 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15519 assert(Op.getSimpleValueType().is256BitVector() &&
15520 Op.getSimpleValueType().isInteger() &&
15521 "Only handle AVX 256-bit vector integer operation");
15522 return Lower256IntArith(Op, DAG);
15525 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15526 SelectionDAG &DAG) {
15528 MVT VT = Op.getSimpleValueType();
15530 // Decompose 256-bit ops into smaller 128-bit ops.
15531 if (VT.is256BitVector() && !Subtarget->hasInt256())
15532 return Lower256IntArith(Op, DAG);
15534 SDValue A = Op.getOperand(0);
15535 SDValue B = Op.getOperand(1);
15537 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15538 if (VT == MVT::v4i32) {
15539 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15540 "Should not custom lower when pmuldq is available!");
15542 // Extract the odd parts.
15543 static const int UnpackMask[] = { 1, -1, 3, -1 };
15544 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15545 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15547 // Multiply the even parts.
15548 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15549 // Now multiply odd parts.
15550 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15552 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15553 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15555 // Merge the two vectors back together with a shuffle. This expands into 2
15557 static const int ShufMask[] = { 0, 4, 2, 6 };
15558 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15561 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15562 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15564 // Ahi = psrlqi(a, 32);
15565 // Bhi = psrlqi(b, 32);
15567 // AloBlo = pmuludq(a, b);
15568 // AloBhi = pmuludq(a, Bhi);
15569 // AhiBlo = pmuludq(Ahi, b);
15571 // AloBhi = psllqi(AloBhi, 32);
15572 // AhiBlo = psllqi(AhiBlo, 32);
15573 // return AloBlo + AloBhi + AhiBlo;
15575 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15576 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15578 // Bit cast to 32-bit vectors for MULUDQ
15579 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15580 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15581 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15582 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15583 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15584 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15586 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15587 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15588 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15590 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15591 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15593 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15594 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15597 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15598 assert(Subtarget->isTargetWin64() && "Unexpected target");
15599 EVT VT = Op.getValueType();
15600 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15601 "Unexpected return type for lowering");
15605 switch (Op->getOpcode()) {
15606 default: llvm_unreachable("Unexpected request for libcall!");
15607 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15608 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15609 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15610 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15611 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15612 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15616 SDValue InChain = DAG.getEntryNode();
15618 TargetLowering::ArgListTy Args;
15619 TargetLowering::ArgListEntry Entry;
15620 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15621 EVT ArgVT = Op->getOperand(i).getValueType();
15622 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15623 "Unexpected argument type for lowering");
15624 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15625 Entry.Node = StackPtr;
15626 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15628 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15629 Entry.Ty = PointerType::get(ArgTy,0);
15630 Entry.isSExt = false;
15631 Entry.isZExt = false;
15632 Args.push_back(Entry);
15635 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15638 TargetLowering::CallLoweringInfo CLI(DAG);
15639 CLI.setDebugLoc(dl).setChain(InChain)
15640 .setCallee(getLibcallCallingConv(LC),
15641 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15642 Callee, std::move(Args), 0)
15643 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15645 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15646 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15649 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15650 SelectionDAG &DAG) {
15651 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15652 EVT VT = Op0.getValueType();
15655 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15656 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15658 // PMULxD operations multiply each even value (starting at 0) of LHS with
15659 // the related value of RHS and produce a widen result.
15660 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15661 // => <2 x i64> <ae|cg>
15663 // In other word, to have all the results, we need to perform two PMULxD:
15664 // 1. one with the even values.
15665 // 2. one with the odd values.
15666 // To achieve #2, with need to place the odd values at an even position.
15668 // Place the odd value at an even position (basically, shift all values 1
15669 // step to the left):
15670 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15671 // <a|b|c|d> => <b|undef|d|undef>
15672 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15673 // <e|f|g|h> => <f|undef|h|undef>
15674 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15676 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15678 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15679 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15681 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15682 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15683 // => <2 x i64> <ae|cg>
15684 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15685 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15686 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15687 // => <2 x i64> <bf|dh>
15688 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15689 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15691 // Shuffle it back into the right order.
15692 SDValue Highs, Lows;
15693 if (VT == MVT::v8i32) {
15694 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15695 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15696 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15697 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15699 const int HighMask[] = {1, 5, 3, 7};
15700 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15701 const int LowMask[] = {1, 4, 2, 6};
15702 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15705 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15706 // unsigned multiply.
15707 if (IsSigned && !Subtarget->hasSSE41()) {
15709 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15710 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15711 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15712 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15713 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15715 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15716 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15719 // The first result of MUL_LOHI is actually the low value, followed by the
15721 SDValue Ops[] = {Lows, Highs};
15722 return DAG.getMergeValues(Ops, dl);
15725 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15726 const X86Subtarget *Subtarget) {
15727 MVT VT = Op.getSimpleValueType();
15729 SDValue R = Op.getOperand(0);
15730 SDValue Amt = Op.getOperand(1);
15732 // Optimize shl/srl/sra with constant shift amount.
15733 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15734 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15735 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15737 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15738 (Subtarget->hasInt256() &&
15739 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15740 (Subtarget->hasAVX512() &&
15741 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15742 if (Op.getOpcode() == ISD::SHL)
15743 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15745 if (Op.getOpcode() == ISD::SRL)
15746 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15748 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15749 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15753 if (VT == MVT::v16i8) {
15754 if (Op.getOpcode() == ISD::SHL) {
15755 // Make a large shift.
15756 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15757 MVT::v8i16, R, ShiftAmt,
15759 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15760 // Zero out the rightmost bits.
15761 SmallVector<SDValue, 16> V(16,
15762 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15764 return DAG.getNode(ISD::AND, dl, VT, SHL,
15765 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15767 if (Op.getOpcode() == ISD::SRL) {
15768 // Make a large shift.
15769 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15770 MVT::v8i16, R, ShiftAmt,
15772 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15773 // Zero out the leftmost bits.
15774 SmallVector<SDValue, 16> V(16,
15775 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15777 return DAG.getNode(ISD::AND, dl, VT, SRL,
15778 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15780 if (Op.getOpcode() == ISD::SRA) {
15781 if (ShiftAmt == 7) {
15782 // R s>> 7 === R s< 0
15783 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15784 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15787 // R s>> a === ((R u>> a) ^ m) - m
15788 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15789 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15791 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15792 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15793 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15796 llvm_unreachable("Unknown shift opcode.");
15799 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15800 if (Op.getOpcode() == ISD::SHL) {
15801 // Make a large shift.
15802 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15803 MVT::v16i16, R, ShiftAmt,
15805 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15806 // Zero out the rightmost bits.
15807 SmallVector<SDValue, 32> V(32,
15808 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15810 return DAG.getNode(ISD::AND, dl, VT, SHL,
15811 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15813 if (Op.getOpcode() == ISD::SRL) {
15814 // Make a large shift.
15815 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15816 MVT::v16i16, R, ShiftAmt,
15818 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15819 // Zero out the leftmost bits.
15820 SmallVector<SDValue, 32> V(32,
15821 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15823 return DAG.getNode(ISD::AND, dl, VT, SRL,
15824 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15826 if (Op.getOpcode() == ISD::SRA) {
15827 if (ShiftAmt == 7) {
15828 // R s>> 7 === R s< 0
15829 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15830 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15833 // R s>> a === ((R u>> a) ^ m) - m
15834 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15835 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15837 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15838 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15839 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15842 llvm_unreachable("Unknown shift opcode.");
15847 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15848 if (!Subtarget->is64Bit() &&
15849 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15850 Amt.getOpcode() == ISD::BITCAST &&
15851 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15852 Amt = Amt.getOperand(0);
15853 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15854 VT.getVectorNumElements();
15855 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15856 uint64_t ShiftAmt = 0;
15857 for (unsigned i = 0; i != Ratio; ++i) {
15858 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15862 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15864 // Check remaining shift amounts.
15865 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15866 uint64_t ShAmt = 0;
15867 for (unsigned j = 0; j != Ratio; ++j) {
15868 ConstantSDNode *C =
15869 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15873 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15875 if (ShAmt != ShiftAmt)
15878 switch (Op.getOpcode()) {
15880 llvm_unreachable("Unknown shift opcode!");
15882 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15885 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15888 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15896 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15897 const X86Subtarget* Subtarget) {
15898 MVT VT = Op.getSimpleValueType();
15900 SDValue R = Op.getOperand(0);
15901 SDValue Amt = Op.getOperand(1);
15903 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15904 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15905 (Subtarget->hasInt256() &&
15906 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15907 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15908 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15910 EVT EltVT = VT.getVectorElementType();
15912 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15913 unsigned NumElts = VT.getVectorNumElements();
15915 for (i = 0; i != NumElts; ++i) {
15916 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15920 for (j = i; j != NumElts; ++j) {
15921 SDValue Arg = Amt.getOperand(j);
15922 if (Arg.getOpcode() == ISD::UNDEF) continue;
15923 if (Arg != Amt.getOperand(i))
15926 if (i != NumElts && j == NumElts)
15927 BaseShAmt = Amt.getOperand(i);
15929 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15930 Amt = Amt.getOperand(0);
15931 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15932 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15933 SDValue InVec = Amt.getOperand(0);
15934 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15935 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15937 for (; i != NumElts; ++i) {
15938 SDValue Arg = InVec.getOperand(i);
15939 if (Arg.getOpcode() == ISD::UNDEF) continue;
15943 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15944 if (ConstantSDNode *C =
15945 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15946 unsigned SplatIdx =
15947 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15948 if (C->getZExtValue() == SplatIdx)
15949 BaseShAmt = InVec.getOperand(1);
15952 if (!BaseShAmt.getNode())
15953 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15954 DAG.getIntPtrConstant(0));
15958 if (BaseShAmt.getNode()) {
15959 if (EltVT.bitsGT(MVT::i32))
15960 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15961 else if (EltVT.bitsLT(MVT::i32))
15962 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15964 switch (Op.getOpcode()) {
15966 llvm_unreachable("Unknown shift opcode!");
15968 switch (VT.SimpleTy) {
15969 default: return SDValue();
15978 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15981 switch (VT.SimpleTy) {
15982 default: return SDValue();
15989 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15992 switch (VT.SimpleTy) {
15993 default: return SDValue();
16002 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16008 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16009 if (!Subtarget->is64Bit() &&
16010 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16011 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16012 Amt.getOpcode() == ISD::BITCAST &&
16013 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16014 Amt = Amt.getOperand(0);
16015 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16016 VT.getVectorNumElements();
16017 std::vector<SDValue> Vals(Ratio);
16018 for (unsigned i = 0; i != Ratio; ++i)
16019 Vals[i] = Amt.getOperand(i);
16020 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16021 for (unsigned j = 0; j != Ratio; ++j)
16022 if (Vals[j] != Amt.getOperand(i + j))
16025 switch (Op.getOpcode()) {
16027 llvm_unreachable("Unknown shift opcode!");
16029 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16031 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16033 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16040 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16041 SelectionDAG &DAG) {
16042 MVT VT = Op.getSimpleValueType();
16044 SDValue R = Op.getOperand(0);
16045 SDValue Amt = Op.getOperand(1);
16048 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16049 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16051 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16055 V = LowerScalarVariableShift(Op, DAG, Subtarget);
16059 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16061 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16062 if (Subtarget->hasInt256()) {
16063 if (Op.getOpcode() == ISD::SRL &&
16064 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16065 VT == MVT::v4i64 || VT == MVT::v8i32))
16067 if (Op.getOpcode() == ISD::SHL &&
16068 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16069 VT == MVT::v4i64 || VT == MVT::v8i32))
16071 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16075 // If possible, lower this packed shift into a vector multiply instead of
16076 // expanding it into a sequence of scalar shifts.
16077 // Do this only if the vector shift count is a constant build_vector.
16078 if (Op.getOpcode() == ISD::SHL &&
16079 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16080 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16081 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16082 SmallVector<SDValue, 8> Elts;
16083 EVT SVT = VT.getScalarType();
16084 unsigned SVTBits = SVT.getSizeInBits();
16085 const APInt &One = APInt(SVTBits, 1);
16086 unsigned NumElems = VT.getVectorNumElements();
16088 for (unsigned i=0; i !=NumElems; ++i) {
16089 SDValue Op = Amt->getOperand(i);
16090 if (Op->getOpcode() == ISD::UNDEF) {
16091 Elts.push_back(Op);
16095 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16096 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16097 uint64_t ShAmt = C.getZExtValue();
16098 if (ShAmt >= SVTBits) {
16099 Elts.push_back(DAG.getUNDEF(SVT));
16102 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16104 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16105 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16108 // Lower SHL with variable shift amount.
16109 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16110 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16112 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16113 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16114 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16115 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16118 // If possible, lower this shift as a sequence of two shifts by
16119 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16121 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16123 // Could be rewritten as:
16124 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16126 // The advantage is that the two shifts from the example would be
16127 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16128 // the vector shift into four scalar shifts plus four pairs of vector
16130 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16131 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16132 unsigned TargetOpcode = X86ISD::MOVSS;
16133 bool CanBeSimplified;
16134 // The splat value for the first packed shift (the 'X' from the example).
16135 SDValue Amt1 = Amt->getOperand(0);
16136 // The splat value for the second packed shift (the 'Y' from the example).
16137 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16138 Amt->getOperand(2);
16140 // See if it is possible to replace this node with a sequence of
16141 // two shifts followed by a MOVSS/MOVSD
16142 if (VT == MVT::v4i32) {
16143 // Check if it is legal to use a MOVSS.
16144 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16145 Amt2 == Amt->getOperand(3);
16146 if (!CanBeSimplified) {
16147 // Otherwise, check if we can still simplify this node using a MOVSD.
16148 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16149 Amt->getOperand(2) == Amt->getOperand(3);
16150 TargetOpcode = X86ISD::MOVSD;
16151 Amt2 = Amt->getOperand(2);
16154 // Do similar checks for the case where the machine value type
16156 CanBeSimplified = Amt1 == Amt->getOperand(1);
16157 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16158 CanBeSimplified = Amt2 == Amt->getOperand(i);
16160 if (!CanBeSimplified) {
16161 TargetOpcode = X86ISD::MOVSD;
16162 CanBeSimplified = true;
16163 Amt2 = Amt->getOperand(4);
16164 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16165 CanBeSimplified = Amt1 == Amt->getOperand(i);
16166 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16167 CanBeSimplified = Amt2 == Amt->getOperand(j);
16171 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16172 isa<ConstantSDNode>(Amt2)) {
16173 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16174 EVT CastVT = MVT::v4i32;
16176 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16177 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16179 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16180 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16181 if (TargetOpcode == X86ISD::MOVSD)
16182 CastVT = MVT::v2i64;
16183 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16184 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16185 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16187 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16191 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16192 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16195 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16196 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16198 // Turn 'a' into a mask suitable for VSELECT
16199 SDValue VSelM = DAG.getConstant(0x80, VT);
16200 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16201 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16203 SDValue CM1 = DAG.getConstant(0x0f, VT);
16204 SDValue CM2 = DAG.getConstant(0x3f, VT);
16206 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16207 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16208 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16209 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16210 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16213 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16214 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16215 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16217 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16218 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16219 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, 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 // return VSELECT(r, r+r, a);
16229 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16230 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16234 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16235 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16236 // solution better.
16237 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16238 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16240 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16241 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16242 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16243 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16244 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16247 // Decompose 256-bit shifts into smaller 128-bit shifts.
16248 if (VT.is256BitVector()) {
16249 unsigned NumElems = VT.getVectorNumElements();
16250 MVT EltVT = VT.getVectorElementType();
16251 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16253 // Extract the two vectors
16254 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16255 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16257 // Recreate the shift amount vectors
16258 SDValue Amt1, Amt2;
16259 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16260 // Constant shift amount
16261 SmallVector<SDValue, 4> Amt1Csts;
16262 SmallVector<SDValue, 4> Amt2Csts;
16263 for (unsigned i = 0; i != NumElems/2; ++i)
16264 Amt1Csts.push_back(Amt->getOperand(i));
16265 for (unsigned i = NumElems/2; i != NumElems; ++i)
16266 Amt2Csts.push_back(Amt->getOperand(i));
16268 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16269 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16271 // Variable shift amount
16272 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16273 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16276 // Issue new vector shifts for the smaller types
16277 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16278 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16280 // Concatenate the result back
16281 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16287 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16288 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16289 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16290 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16291 // has only one use.
16292 SDNode *N = Op.getNode();
16293 SDValue LHS = N->getOperand(0);
16294 SDValue RHS = N->getOperand(1);
16295 unsigned BaseOp = 0;
16298 switch (Op.getOpcode()) {
16299 default: llvm_unreachable("Unknown ovf instruction!");
16301 // A subtract of one will be selected as a INC. Note that INC doesn't
16302 // set CF, so we can't do this for UADDO.
16303 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16305 BaseOp = X86ISD::INC;
16306 Cond = X86::COND_O;
16309 BaseOp = X86ISD::ADD;
16310 Cond = X86::COND_O;
16313 BaseOp = X86ISD::ADD;
16314 Cond = X86::COND_B;
16317 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16318 // set CF, so we can't do this for USUBO.
16319 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16321 BaseOp = X86ISD::DEC;
16322 Cond = X86::COND_O;
16325 BaseOp = X86ISD::SUB;
16326 Cond = X86::COND_O;
16329 BaseOp = X86ISD::SUB;
16330 Cond = X86::COND_B;
16333 BaseOp = X86ISD::SMUL;
16334 Cond = X86::COND_O;
16336 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16337 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16339 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16342 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16343 DAG.getConstant(X86::COND_O, MVT::i32),
16344 SDValue(Sum.getNode(), 2));
16346 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16350 // Also sets EFLAGS.
16351 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16352 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16355 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16356 DAG.getConstant(Cond, MVT::i32),
16357 SDValue(Sum.getNode(), 1));
16359 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16362 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16363 SelectionDAG &DAG) const {
16365 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16366 MVT VT = Op.getSimpleValueType();
16368 if (!Subtarget->hasSSE2() || !VT.isVector())
16371 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16372 ExtraVT.getScalarType().getSizeInBits();
16374 switch (VT.SimpleTy) {
16375 default: return SDValue();
16378 if (!Subtarget->hasFp256())
16380 if (!Subtarget->hasInt256()) {
16381 // needs to be split
16382 unsigned NumElems = VT.getVectorNumElements();
16384 // Extract the LHS vectors
16385 SDValue LHS = Op.getOperand(0);
16386 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16387 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16389 MVT EltVT = VT.getVectorElementType();
16390 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16392 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16393 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16394 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16396 SDValue Extra = DAG.getValueType(ExtraVT);
16398 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16399 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16401 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16406 SDValue Op0 = Op.getOperand(0);
16407 SDValue Op00 = Op0.getOperand(0);
16409 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16410 if (Op0.getOpcode() == ISD::BITCAST &&
16411 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16412 // (sext (vzext x)) -> (vsext x)
16413 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16414 if (Tmp1.getNode()) {
16415 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16416 // This folding is only valid when the in-reg type is a vector of i8,
16418 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16419 ExtraEltVT == MVT::i32) {
16420 SDValue Tmp1Op0 = Tmp1.getOperand(0);
16421 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16422 "This optimization is invalid without a VZEXT.");
16423 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16429 // If the above didn't work, then just use Shift-Left + Shift-Right.
16430 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16432 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16438 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16439 SelectionDAG &DAG) {
16441 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16442 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16443 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16444 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16446 // The only fence that needs an instruction is a sequentially-consistent
16447 // cross-thread fence.
16448 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16449 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16450 // no-sse2). There isn't any reason to disable it if the target processor
16452 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16453 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16455 SDValue Chain = Op.getOperand(0);
16456 SDValue Zero = DAG.getConstant(0, MVT::i32);
16458 DAG.getRegister(X86::ESP, MVT::i32), // Base
16459 DAG.getTargetConstant(1, MVT::i8), // Scale
16460 DAG.getRegister(0, MVT::i32), // Index
16461 DAG.getTargetConstant(0, MVT::i32), // Disp
16462 DAG.getRegister(0, MVT::i32), // Segment.
16466 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16467 return SDValue(Res, 0);
16470 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16471 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16474 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16475 SelectionDAG &DAG) {
16476 MVT T = Op.getSimpleValueType();
16480 switch(T.SimpleTy) {
16481 default: llvm_unreachable("Invalid value type!");
16482 case MVT::i8: Reg = X86::AL; size = 1; break;
16483 case MVT::i16: Reg = X86::AX; size = 2; break;
16484 case MVT::i32: Reg = X86::EAX; size = 4; break;
16486 assert(Subtarget->is64Bit() && "Node not type legal!");
16487 Reg = X86::RAX; size = 8;
16490 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16491 Op.getOperand(2), SDValue());
16492 SDValue Ops[] = { cpIn.getValue(0),
16495 DAG.getTargetConstant(size, MVT::i8),
16496 cpIn.getValue(1) };
16497 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16498 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16499 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16503 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16504 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16505 MVT::i32, cpOut.getValue(2));
16506 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16507 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16509 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16510 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16511 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16515 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16516 SelectionDAG &DAG) {
16517 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16518 MVT DstVT = Op.getSimpleValueType();
16520 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16521 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16522 if (DstVT != MVT::f64)
16523 // This conversion needs to be expanded.
16526 SDValue InVec = Op->getOperand(0);
16528 unsigned NumElts = SrcVT.getVectorNumElements();
16529 EVT SVT = SrcVT.getVectorElementType();
16531 // Widen the vector in input in the case of MVT::v2i32.
16532 // Example: from MVT::v2i32 to MVT::v4i32.
16533 SmallVector<SDValue, 16> Elts;
16534 for (unsigned i = 0, e = NumElts; i != e; ++i)
16535 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16536 DAG.getIntPtrConstant(i)));
16538 // Explicitly mark the extra elements as Undef.
16539 SDValue Undef = DAG.getUNDEF(SVT);
16540 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16541 Elts.push_back(Undef);
16543 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16544 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16545 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16546 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16547 DAG.getIntPtrConstant(0));
16550 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16551 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16552 assert((DstVT == MVT::i64 ||
16553 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16554 "Unexpected custom BITCAST");
16555 // i64 <=> MMX conversions are Legal.
16556 if (SrcVT==MVT::i64 && DstVT.isVector())
16558 if (DstVT==MVT::i64 && SrcVT.isVector())
16560 // MMX <=> MMX conversions are Legal.
16561 if (SrcVT.isVector() && DstVT.isVector())
16563 // All other conversions need to be expanded.
16567 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16568 SDNode *Node = Op.getNode();
16570 EVT T = Node->getValueType(0);
16571 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16572 DAG.getConstant(0, T), Node->getOperand(2));
16573 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16574 cast<AtomicSDNode>(Node)->getMemoryVT(),
16575 Node->getOperand(0),
16576 Node->getOperand(1), negOp,
16577 cast<AtomicSDNode>(Node)->getMemOperand(),
16578 cast<AtomicSDNode>(Node)->getOrdering(),
16579 cast<AtomicSDNode>(Node)->getSynchScope());
16582 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16583 SDNode *Node = Op.getNode();
16585 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16587 // Convert seq_cst store -> xchg
16588 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16589 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16590 // (The only way to get a 16-byte store is cmpxchg16b)
16591 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16592 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16593 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16594 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16595 cast<AtomicSDNode>(Node)->getMemoryVT(),
16596 Node->getOperand(0),
16597 Node->getOperand(1), Node->getOperand(2),
16598 cast<AtomicSDNode>(Node)->getMemOperand(),
16599 cast<AtomicSDNode>(Node)->getOrdering(),
16600 cast<AtomicSDNode>(Node)->getSynchScope());
16601 return Swap.getValue(1);
16603 // Other atomic stores have a simple pattern.
16607 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16608 EVT VT = Op.getNode()->getSimpleValueType(0);
16610 // Let legalize expand this if it isn't a legal type yet.
16611 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16614 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16617 bool ExtraOp = false;
16618 switch (Op.getOpcode()) {
16619 default: llvm_unreachable("Invalid code");
16620 case ISD::ADDC: Opc = X86ISD::ADD; break;
16621 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16622 case ISD::SUBC: Opc = X86ISD::SUB; break;
16623 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16627 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16629 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16630 Op.getOperand(1), Op.getOperand(2));
16633 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16634 SelectionDAG &DAG) {
16635 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16637 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16638 // which returns the values as { float, float } (in XMM0) or
16639 // { double, double } (which is returned in XMM0, XMM1).
16641 SDValue Arg = Op.getOperand(0);
16642 EVT ArgVT = Arg.getValueType();
16643 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16645 TargetLowering::ArgListTy Args;
16646 TargetLowering::ArgListEntry Entry;
16650 Entry.isSExt = false;
16651 Entry.isZExt = false;
16652 Args.push_back(Entry);
16654 bool isF64 = ArgVT == MVT::f64;
16655 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16656 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16657 // the results are returned via SRet in memory.
16658 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16659 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16660 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16662 Type *RetTy = isF64
16663 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16664 : (Type*)VectorType::get(ArgTy, 4);
16666 TargetLowering::CallLoweringInfo CLI(DAG);
16667 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16668 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16670 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16673 // Returned in xmm0 and xmm1.
16674 return CallResult.first;
16676 // Returned in bits 0:31 and 32:64 xmm0.
16677 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16678 CallResult.first, DAG.getIntPtrConstant(0));
16679 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16680 CallResult.first, DAG.getIntPtrConstant(1));
16681 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16682 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16685 /// LowerOperation - Provide custom lowering hooks for some operations.
16687 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16688 switch (Op.getOpcode()) {
16689 default: llvm_unreachable("Should not custom lower this!");
16690 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16691 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16692 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16693 return LowerCMP_SWAP(Op, Subtarget, DAG);
16694 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16695 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16696 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16697 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16698 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16699 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16700 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16701 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16702 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16703 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16704 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16705 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16706 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16707 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16708 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16709 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16710 case ISD::SHL_PARTS:
16711 case ISD::SRA_PARTS:
16712 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16713 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16714 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16715 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16716 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16717 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16718 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16719 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16720 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16721 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16722 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
16723 case ISD::FABS: return LowerFABS(Op, DAG);
16724 case ISD::FNEG: return LowerFNEG(Op, DAG);
16725 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16726 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16727 case ISD::SETCC: return LowerSETCC(Op, DAG);
16728 case ISD::SELECT: return LowerSELECT(Op, DAG);
16729 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16730 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16731 case ISD::VASTART: return LowerVASTART(Op, DAG);
16732 case ISD::VAARG: return LowerVAARG(Op, DAG);
16733 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16734 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16735 case ISD::INTRINSIC_VOID:
16736 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16737 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16738 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16739 case ISD::FRAME_TO_ARGS_OFFSET:
16740 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16741 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16742 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16743 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16744 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16745 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16746 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16747 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16748 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16749 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16750 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16751 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16752 case ISD::UMUL_LOHI:
16753 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16756 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16762 case ISD::UMULO: return LowerXALUO(Op, DAG);
16763 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16764 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16768 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16769 case ISD::ADD: return LowerADD(Op, DAG);
16770 case ISD::SUB: return LowerSUB(Op, DAG);
16771 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16775 static void ReplaceATOMIC_LOAD(SDNode *Node,
16776 SmallVectorImpl<SDValue> &Results,
16777 SelectionDAG &DAG) {
16779 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16781 // Convert wide load -> cmpxchg8b/cmpxchg16b
16782 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16783 // (The only way to get a 16-byte load is cmpxchg16b)
16784 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16785 SDValue Zero = DAG.getConstant(0, VT);
16786 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16788 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16789 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16790 cast<AtomicSDNode>(Node)->getMemOperand(),
16791 cast<AtomicSDNode>(Node)->getOrdering(),
16792 cast<AtomicSDNode>(Node)->getOrdering(),
16793 cast<AtomicSDNode>(Node)->getSynchScope());
16794 Results.push_back(Swap.getValue(0));
16795 Results.push_back(Swap.getValue(2));
16798 /// ReplaceNodeResults - Replace a node with an illegal result type
16799 /// with a new node built out of custom code.
16800 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16801 SmallVectorImpl<SDValue>&Results,
16802 SelectionDAG &DAG) const {
16804 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16805 switch (N->getOpcode()) {
16807 llvm_unreachable("Do not know how to custom type legalize this operation!");
16808 case ISD::SIGN_EXTEND_INREG:
16813 // We don't want to expand or promote these.
16820 case ISD::UDIVREM: {
16821 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16822 Results.push_back(V);
16825 case ISD::FP_TO_SINT:
16826 case ISD::FP_TO_UINT: {
16827 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16829 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16832 std::pair<SDValue,SDValue> Vals =
16833 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16834 SDValue FIST = Vals.first, StackSlot = Vals.second;
16835 if (FIST.getNode()) {
16836 EVT VT = N->getValueType(0);
16837 // Return a load from the stack slot.
16838 if (StackSlot.getNode())
16839 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16840 MachinePointerInfo(),
16841 false, false, false, 0));
16843 Results.push_back(FIST);
16847 case ISD::UINT_TO_FP: {
16848 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16849 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16850 N->getValueType(0) != MVT::v2f32)
16852 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16854 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16856 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16857 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16858 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16859 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16860 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16861 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16864 case ISD::FP_ROUND: {
16865 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16867 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16868 Results.push_back(V);
16871 case ISD::INTRINSIC_W_CHAIN: {
16872 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16874 default : llvm_unreachable("Do not know how to custom type "
16875 "legalize this intrinsic operation!");
16876 case Intrinsic::x86_rdtsc:
16877 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16879 case Intrinsic::x86_rdtscp:
16880 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16882 case Intrinsic::x86_rdpmc:
16883 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16886 case ISD::READCYCLECOUNTER: {
16887 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16890 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16891 EVT T = N->getValueType(0);
16892 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16893 bool Regs64bit = T == MVT::i128;
16894 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16895 SDValue cpInL, cpInH;
16896 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16897 DAG.getConstant(0, HalfT));
16898 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16899 DAG.getConstant(1, HalfT));
16900 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16901 Regs64bit ? X86::RAX : X86::EAX,
16903 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16904 Regs64bit ? X86::RDX : X86::EDX,
16905 cpInH, cpInL.getValue(1));
16906 SDValue swapInL, swapInH;
16907 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16908 DAG.getConstant(0, HalfT));
16909 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16910 DAG.getConstant(1, HalfT));
16911 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16912 Regs64bit ? X86::RBX : X86::EBX,
16913 swapInL, cpInH.getValue(1));
16914 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16915 Regs64bit ? X86::RCX : X86::ECX,
16916 swapInH, swapInL.getValue(1));
16917 SDValue Ops[] = { swapInH.getValue(0),
16919 swapInH.getValue(1) };
16920 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16921 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16922 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16923 X86ISD::LCMPXCHG8_DAG;
16924 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16925 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16926 Regs64bit ? X86::RAX : X86::EAX,
16927 HalfT, Result.getValue(1));
16928 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16929 Regs64bit ? X86::RDX : X86::EDX,
16930 HalfT, cpOutL.getValue(2));
16931 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16933 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16934 MVT::i32, cpOutH.getValue(2));
16936 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16937 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16938 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16940 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16941 Results.push_back(Success);
16942 Results.push_back(EFLAGS.getValue(1));
16945 case ISD::ATOMIC_SWAP:
16946 case ISD::ATOMIC_LOAD_ADD:
16947 case ISD::ATOMIC_LOAD_SUB:
16948 case ISD::ATOMIC_LOAD_AND:
16949 case ISD::ATOMIC_LOAD_OR:
16950 case ISD::ATOMIC_LOAD_XOR:
16951 case ISD::ATOMIC_LOAD_NAND:
16952 case ISD::ATOMIC_LOAD_MIN:
16953 case ISD::ATOMIC_LOAD_MAX:
16954 case ISD::ATOMIC_LOAD_UMIN:
16955 case ISD::ATOMIC_LOAD_UMAX:
16956 // Delegate to generic TypeLegalization. Situations we can really handle
16957 // should have already been dealt with by X86AtomicExpand.cpp.
16959 case ISD::ATOMIC_LOAD: {
16960 ReplaceATOMIC_LOAD(N, Results, DAG);
16963 case ISD::BITCAST: {
16964 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16965 EVT DstVT = N->getValueType(0);
16966 EVT SrcVT = N->getOperand(0)->getValueType(0);
16968 if (SrcVT != MVT::f64 ||
16969 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16972 unsigned NumElts = DstVT.getVectorNumElements();
16973 EVT SVT = DstVT.getVectorElementType();
16974 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16975 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16976 MVT::v2f64, N->getOperand(0));
16977 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16979 if (ExperimentalVectorWideningLegalization) {
16980 // If we are legalizing vectors by widening, we already have the desired
16981 // legal vector type, just return it.
16982 Results.push_back(ToVecInt);
16986 SmallVector<SDValue, 8> Elts;
16987 for (unsigned i = 0, e = NumElts; i != e; ++i)
16988 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16989 ToVecInt, DAG.getIntPtrConstant(i)));
16991 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16996 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16998 default: return nullptr;
16999 case X86ISD::BSF: return "X86ISD::BSF";
17000 case X86ISD::BSR: return "X86ISD::BSR";
17001 case X86ISD::SHLD: return "X86ISD::SHLD";
17002 case X86ISD::SHRD: return "X86ISD::SHRD";
17003 case X86ISD::FAND: return "X86ISD::FAND";
17004 case X86ISD::FANDN: return "X86ISD::FANDN";
17005 case X86ISD::FOR: return "X86ISD::FOR";
17006 case X86ISD::FXOR: return "X86ISD::FXOR";
17007 case X86ISD::FSRL: return "X86ISD::FSRL";
17008 case X86ISD::FILD: return "X86ISD::FILD";
17009 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17010 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17011 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17012 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17013 case X86ISD::FLD: return "X86ISD::FLD";
17014 case X86ISD::FST: return "X86ISD::FST";
17015 case X86ISD::CALL: return "X86ISD::CALL";
17016 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17017 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17018 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17019 case X86ISD::BT: return "X86ISD::BT";
17020 case X86ISD::CMP: return "X86ISD::CMP";
17021 case X86ISD::COMI: return "X86ISD::COMI";
17022 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17023 case X86ISD::CMPM: return "X86ISD::CMPM";
17024 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17025 case X86ISD::SETCC: return "X86ISD::SETCC";
17026 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17027 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17028 case X86ISD::CMOV: return "X86ISD::CMOV";
17029 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17030 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17031 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17032 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17033 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17034 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17035 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17036 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17037 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17038 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17039 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17040 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17041 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17042 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17043 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17044 case X86ISD::BLENDV: return "X86ISD::BLENDV";
17045 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17046 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17047 case X86ISD::HADD: return "X86ISD::HADD";
17048 case X86ISD::HSUB: return "X86ISD::HSUB";
17049 case X86ISD::FHADD: return "X86ISD::FHADD";
17050 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17051 case X86ISD::UMAX: return "X86ISD::UMAX";
17052 case X86ISD::UMIN: return "X86ISD::UMIN";
17053 case X86ISD::SMAX: return "X86ISD::SMAX";
17054 case X86ISD::SMIN: return "X86ISD::SMIN";
17055 case X86ISD::FMAX: return "X86ISD::FMAX";
17056 case X86ISD::FMIN: return "X86ISD::FMIN";
17057 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17058 case X86ISD::FMINC: return "X86ISD::FMINC";
17059 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17060 case X86ISD::FRCP: return "X86ISD::FRCP";
17061 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17062 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17063 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17064 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17065 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17066 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17067 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17068 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17069 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17070 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17071 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17072 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17073 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17074 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17075 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17076 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17077 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17078 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17079 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17080 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17081 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17082 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17083 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17084 case X86ISD::VSHL: return "X86ISD::VSHL";
17085 case X86ISD::VSRL: return "X86ISD::VSRL";
17086 case X86ISD::VSRA: return "X86ISD::VSRA";
17087 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17088 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17089 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17090 case X86ISD::CMPP: return "X86ISD::CMPP";
17091 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17092 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17093 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17094 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17095 case X86ISD::ADD: return "X86ISD::ADD";
17096 case X86ISD::SUB: return "X86ISD::SUB";
17097 case X86ISD::ADC: return "X86ISD::ADC";
17098 case X86ISD::SBB: return "X86ISD::SBB";
17099 case X86ISD::SMUL: return "X86ISD::SMUL";
17100 case X86ISD::UMUL: return "X86ISD::UMUL";
17101 case X86ISD::INC: return "X86ISD::INC";
17102 case X86ISD::DEC: return "X86ISD::DEC";
17103 case X86ISD::OR: return "X86ISD::OR";
17104 case X86ISD::XOR: return "X86ISD::XOR";
17105 case X86ISD::AND: return "X86ISD::AND";
17106 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17107 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17108 case X86ISD::PTEST: return "X86ISD::PTEST";
17109 case X86ISD::TESTP: return "X86ISD::TESTP";
17110 case X86ISD::TESTM: return "X86ISD::TESTM";
17111 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17112 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17113 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17114 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17115 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17116 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17117 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17118 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17119 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17120 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17121 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17122 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17123 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17124 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17125 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17126 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17127 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17128 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17129 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17130 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17131 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17132 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17133 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17134 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
17135 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17136 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
17137 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17138 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17139 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17140 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17141 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17142 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17143 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17144 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17145 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17146 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17147 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17148 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17149 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17150 case X86ISD::SAHF: return "X86ISD::SAHF";
17151 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17152 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17153 case X86ISD::FMADD: return "X86ISD::FMADD";
17154 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17155 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17156 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17157 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17158 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17159 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17160 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17161 case X86ISD::XTEST: return "X86ISD::XTEST";
17165 // isLegalAddressingMode - Return true if the addressing mode represented
17166 // by AM is legal for this target, for a load/store of the specified type.
17167 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17169 // X86 supports extremely general addressing modes.
17170 CodeModel::Model M = getTargetMachine().getCodeModel();
17171 Reloc::Model R = getTargetMachine().getRelocationModel();
17173 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17174 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17179 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17181 // If a reference to this global requires an extra load, we can't fold it.
17182 if (isGlobalStubReference(GVFlags))
17185 // If BaseGV requires a register for the PIC base, we cannot also have a
17186 // BaseReg specified.
17187 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17190 // If lower 4G is not available, then we must use rip-relative addressing.
17191 if ((M != CodeModel::Small || R != Reloc::Static) &&
17192 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17196 switch (AM.Scale) {
17202 // These scales always work.
17207 // These scales are formed with basereg+scalereg. Only accept if there is
17212 default: // Other stuff never works.
17219 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17220 unsigned Bits = Ty->getScalarSizeInBits();
17222 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17223 // particularly cheaper than those without.
17227 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17228 // variable shifts just as cheap as scalar ones.
17229 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17232 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17233 // fully general vector.
17237 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17238 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17240 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17241 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17242 return NumBits1 > NumBits2;
17245 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17246 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17249 if (!isTypeLegal(EVT::getEVT(Ty1)))
17252 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17254 // Assuming the caller doesn't have a zeroext or signext return parameter,
17255 // truncation all the way down to i1 is valid.
17259 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17260 return isInt<32>(Imm);
17263 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17264 // Can also use sub to handle negated immediates.
17265 return isInt<32>(Imm);
17268 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17269 if (!VT1.isInteger() || !VT2.isInteger())
17271 unsigned NumBits1 = VT1.getSizeInBits();
17272 unsigned NumBits2 = VT2.getSizeInBits();
17273 return NumBits1 > NumBits2;
17276 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17277 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17278 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17281 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17282 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17283 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17286 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17287 EVT VT1 = Val.getValueType();
17288 if (isZExtFree(VT1, VT2))
17291 if (Val.getOpcode() != ISD::LOAD)
17294 if (!VT1.isSimple() || !VT1.isInteger() ||
17295 !VT2.isSimple() || !VT2.isInteger())
17298 switch (VT1.getSimpleVT().SimpleTy) {
17303 // X86 has 8, 16, and 32-bit zero-extending loads.
17311 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17312 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17315 VT = VT.getScalarType();
17317 if (!VT.isSimple())
17320 switch (VT.getSimpleVT().SimpleTy) {
17331 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17332 // i16 instructions are longer (0x66 prefix) and potentially slower.
17333 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17336 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17337 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17338 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17339 /// are assumed to be legal.
17341 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17343 if (!VT.isSimple())
17346 MVT SVT = VT.getSimpleVT();
17348 // Very little shuffling can be done for 64-bit vectors right now.
17349 if (VT.getSizeInBits() == 64)
17352 // If this is a single-input shuffle with no 128 bit lane crossings we can
17353 // lower it into pshufb.
17354 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17355 (SVT.is256BitVector() && Subtarget->hasInt256())) {
17356 bool isLegal = true;
17357 for (unsigned I = 0, E = M.size(); I != E; ++I) {
17358 if (M[I] >= (int)SVT.getVectorNumElements() ||
17359 ShuffleCrosses128bitLane(SVT, I, M[I])) {
17368 // FIXME: blends, shifts.
17369 return (SVT.getVectorNumElements() == 2 ||
17370 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17371 isMOVLMask(M, SVT) ||
17372 isMOVHLPSMask(M, SVT) ||
17373 isSHUFPMask(M, SVT) ||
17374 isPSHUFDMask(M, SVT) ||
17375 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17376 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17377 isPALIGNRMask(M, SVT, Subtarget) ||
17378 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17379 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17380 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17381 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17382 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17386 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17388 if (!VT.isSimple())
17391 MVT SVT = VT.getSimpleVT();
17392 unsigned NumElts = SVT.getVectorNumElements();
17393 // FIXME: This collection of masks seems suspect.
17396 if (NumElts == 4 && SVT.is128BitVector()) {
17397 return (isMOVLMask(Mask, SVT) ||
17398 isCommutedMOVLMask(Mask, SVT, true) ||
17399 isSHUFPMask(Mask, SVT) ||
17400 isSHUFPMask(Mask, SVT, /* Commuted */ true));
17405 //===----------------------------------------------------------------------===//
17406 // X86 Scheduler Hooks
17407 //===----------------------------------------------------------------------===//
17409 /// Utility function to emit xbegin specifying the start of an RTM region.
17410 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17411 const TargetInstrInfo *TII) {
17412 DebugLoc DL = MI->getDebugLoc();
17414 const BasicBlock *BB = MBB->getBasicBlock();
17415 MachineFunction::iterator I = MBB;
17418 // For the v = xbegin(), we generate
17429 MachineBasicBlock *thisMBB = MBB;
17430 MachineFunction *MF = MBB->getParent();
17431 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17432 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17433 MF->insert(I, mainMBB);
17434 MF->insert(I, sinkMBB);
17436 // Transfer the remainder of BB and its successor edges to sinkMBB.
17437 sinkMBB->splice(sinkMBB->begin(), MBB,
17438 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17439 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17443 // # fallthrough to mainMBB
17444 // # abortion to sinkMBB
17445 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17446 thisMBB->addSuccessor(mainMBB);
17447 thisMBB->addSuccessor(sinkMBB);
17451 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17452 mainMBB->addSuccessor(sinkMBB);
17455 // EAX is live into the sinkMBB
17456 sinkMBB->addLiveIn(X86::EAX);
17457 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17458 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17461 MI->eraseFromParent();
17465 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17466 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17467 // in the .td file.
17468 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17469 const TargetInstrInfo *TII) {
17471 switch (MI->getOpcode()) {
17472 default: llvm_unreachable("illegal opcode!");
17473 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17474 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17475 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17476 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17477 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17478 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17479 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17480 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17483 DebugLoc dl = MI->getDebugLoc();
17484 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17486 unsigned NumArgs = MI->getNumOperands();
17487 for (unsigned i = 1; i < NumArgs; ++i) {
17488 MachineOperand &Op = MI->getOperand(i);
17489 if (!(Op.isReg() && Op.isImplicit()))
17490 MIB.addOperand(Op);
17492 if (MI->hasOneMemOperand())
17493 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17495 BuildMI(*BB, MI, dl,
17496 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17497 .addReg(X86::XMM0);
17499 MI->eraseFromParent();
17503 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17504 // defs in an instruction pattern
17505 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17506 const TargetInstrInfo *TII) {
17508 switch (MI->getOpcode()) {
17509 default: llvm_unreachable("illegal opcode!");
17510 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17511 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17512 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17513 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17514 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17515 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17516 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17517 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17520 DebugLoc dl = MI->getDebugLoc();
17521 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17523 unsigned NumArgs = MI->getNumOperands(); // remove the results
17524 for (unsigned i = 1; i < NumArgs; ++i) {
17525 MachineOperand &Op = MI->getOperand(i);
17526 if (!(Op.isReg() && Op.isImplicit()))
17527 MIB.addOperand(Op);
17529 if (MI->hasOneMemOperand())
17530 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17532 BuildMI(*BB, MI, dl,
17533 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17536 MI->eraseFromParent();
17540 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17541 const TargetInstrInfo *TII,
17542 const X86Subtarget* Subtarget) {
17543 DebugLoc dl = MI->getDebugLoc();
17545 // Address into RAX/EAX, other two args into ECX, EDX.
17546 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17547 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17548 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17549 for (int i = 0; i < X86::AddrNumOperands; ++i)
17550 MIB.addOperand(MI->getOperand(i));
17552 unsigned ValOps = X86::AddrNumOperands;
17553 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17554 .addReg(MI->getOperand(ValOps).getReg());
17555 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17556 .addReg(MI->getOperand(ValOps+1).getReg());
17558 // The instruction doesn't actually take any operands though.
17559 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17561 MI->eraseFromParent(); // The pseudo is gone now.
17565 MachineBasicBlock *
17566 X86TargetLowering::EmitVAARG64WithCustomInserter(
17568 MachineBasicBlock *MBB) const {
17569 // Emit va_arg instruction on X86-64.
17571 // Operands to this pseudo-instruction:
17572 // 0 ) Output : destination address (reg)
17573 // 1-5) Input : va_list address (addr, i64mem)
17574 // 6 ) ArgSize : Size (in bytes) of vararg type
17575 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17576 // 8 ) Align : Alignment of type
17577 // 9 ) EFLAGS (implicit-def)
17579 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17580 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17582 unsigned DestReg = MI->getOperand(0).getReg();
17583 MachineOperand &Base = MI->getOperand(1);
17584 MachineOperand &Scale = MI->getOperand(2);
17585 MachineOperand &Index = MI->getOperand(3);
17586 MachineOperand &Disp = MI->getOperand(4);
17587 MachineOperand &Segment = MI->getOperand(5);
17588 unsigned ArgSize = MI->getOperand(6).getImm();
17589 unsigned ArgMode = MI->getOperand(7).getImm();
17590 unsigned Align = MI->getOperand(8).getImm();
17592 // Memory Reference
17593 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17594 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17595 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17597 // Machine Information
17598 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17599 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17600 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17601 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17602 DebugLoc DL = MI->getDebugLoc();
17604 // struct va_list {
17607 // i64 overflow_area (address)
17608 // i64 reg_save_area (address)
17610 // sizeof(va_list) = 24
17611 // alignment(va_list) = 8
17613 unsigned TotalNumIntRegs = 6;
17614 unsigned TotalNumXMMRegs = 8;
17615 bool UseGPOffset = (ArgMode == 1);
17616 bool UseFPOffset = (ArgMode == 2);
17617 unsigned MaxOffset = TotalNumIntRegs * 8 +
17618 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17620 /* Align ArgSize to a multiple of 8 */
17621 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17622 bool NeedsAlign = (Align > 8);
17624 MachineBasicBlock *thisMBB = MBB;
17625 MachineBasicBlock *overflowMBB;
17626 MachineBasicBlock *offsetMBB;
17627 MachineBasicBlock *endMBB;
17629 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17630 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17631 unsigned OffsetReg = 0;
17633 if (!UseGPOffset && !UseFPOffset) {
17634 // If we only pull from the overflow region, we don't create a branch.
17635 // We don't need to alter control flow.
17636 OffsetDestReg = 0; // unused
17637 OverflowDestReg = DestReg;
17639 offsetMBB = nullptr;
17640 overflowMBB = thisMBB;
17643 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17644 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17645 // If not, pull from overflow_area. (branch to overflowMBB)
17650 // offsetMBB overflowMBB
17655 // Registers for the PHI in endMBB
17656 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17657 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17659 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17660 MachineFunction *MF = MBB->getParent();
17661 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17662 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17663 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17665 MachineFunction::iterator MBBIter = MBB;
17668 // Insert the new basic blocks
17669 MF->insert(MBBIter, offsetMBB);
17670 MF->insert(MBBIter, overflowMBB);
17671 MF->insert(MBBIter, endMBB);
17673 // Transfer the remainder of MBB and its successor edges to endMBB.
17674 endMBB->splice(endMBB->begin(), thisMBB,
17675 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17676 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17678 // Make offsetMBB and overflowMBB successors of thisMBB
17679 thisMBB->addSuccessor(offsetMBB);
17680 thisMBB->addSuccessor(overflowMBB);
17682 // endMBB is a successor of both offsetMBB and overflowMBB
17683 offsetMBB->addSuccessor(endMBB);
17684 overflowMBB->addSuccessor(endMBB);
17686 // Load the offset value into a register
17687 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17688 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17692 .addDisp(Disp, UseFPOffset ? 4 : 0)
17693 .addOperand(Segment)
17694 .setMemRefs(MMOBegin, MMOEnd);
17696 // Check if there is enough room left to pull this argument.
17697 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17699 .addImm(MaxOffset + 8 - ArgSizeA8);
17701 // Branch to "overflowMBB" if offset >= max
17702 // Fall through to "offsetMBB" otherwise
17703 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17704 .addMBB(overflowMBB);
17707 // In offsetMBB, emit code to use the reg_save_area.
17709 assert(OffsetReg != 0);
17711 // Read the reg_save_area address.
17712 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17713 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17718 .addOperand(Segment)
17719 .setMemRefs(MMOBegin, MMOEnd);
17721 // Zero-extend the offset
17722 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17723 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17726 .addImm(X86::sub_32bit);
17728 // Add the offset to the reg_save_area to get the final address.
17729 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17730 .addReg(OffsetReg64)
17731 .addReg(RegSaveReg);
17733 // Compute the offset for the next argument
17734 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17735 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17737 .addImm(UseFPOffset ? 16 : 8);
17739 // Store it back into the va_list.
17740 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17744 .addDisp(Disp, UseFPOffset ? 4 : 0)
17745 .addOperand(Segment)
17746 .addReg(NextOffsetReg)
17747 .setMemRefs(MMOBegin, MMOEnd);
17750 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17755 // Emit code to use overflow area
17758 // Load the overflow_area address into a register.
17759 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17760 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17765 .addOperand(Segment)
17766 .setMemRefs(MMOBegin, MMOEnd);
17768 // If we need to align it, do so. Otherwise, just copy the address
17769 // to OverflowDestReg.
17771 // Align the overflow address
17772 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17773 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17775 // aligned_addr = (addr + (align-1)) & ~(align-1)
17776 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17777 .addReg(OverflowAddrReg)
17780 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17782 .addImm(~(uint64_t)(Align-1));
17784 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17785 .addReg(OverflowAddrReg);
17788 // Compute the next overflow address after this argument.
17789 // (the overflow address should be kept 8-byte aligned)
17790 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17791 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17792 .addReg(OverflowDestReg)
17793 .addImm(ArgSizeA8);
17795 // Store the new overflow address.
17796 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17801 .addOperand(Segment)
17802 .addReg(NextAddrReg)
17803 .setMemRefs(MMOBegin, MMOEnd);
17805 // If we branched, emit the PHI to the front of endMBB.
17807 BuildMI(*endMBB, endMBB->begin(), DL,
17808 TII->get(X86::PHI), DestReg)
17809 .addReg(OffsetDestReg).addMBB(offsetMBB)
17810 .addReg(OverflowDestReg).addMBB(overflowMBB);
17813 // Erase the pseudo instruction
17814 MI->eraseFromParent();
17819 MachineBasicBlock *
17820 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17822 MachineBasicBlock *MBB) const {
17823 // Emit code to save XMM registers to the stack. The ABI says that the
17824 // number of registers to save is given in %al, so it's theoretically
17825 // possible to do an indirect jump trick to avoid saving all of them,
17826 // however this code takes a simpler approach and just executes all
17827 // of the stores if %al is non-zero. It's less code, and it's probably
17828 // easier on the hardware branch predictor, and stores aren't all that
17829 // expensive anyway.
17831 // Create the new basic blocks. One block contains all the XMM stores,
17832 // and one block is the final destination regardless of whether any
17833 // stores were performed.
17834 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17835 MachineFunction *F = MBB->getParent();
17836 MachineFunction::iterator MBBIter = MBB;
17838 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17839 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17840 F->insert(MBBIter, XMMSaveMBB);
17841 F->insert(MBBIter, EndMBB);
17843 // Transfer the remainder of MBB and its successor edges to EndMBB.
17844 EndMBB->splice(EndMBB->begin(), MBB,
17845 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17846 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17848 // The original block will now fall through to the XMM save block.
17849 MBB->addSuccessor(XMMSaveMBB);
17850 // The XMMSaveMBB will fall through to the end block.
17851 XMMSaveMBB->addSuccessor(EndMBB);
17853 // Now add the instructions.
17854 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17855 DebugLoc DL = MI->getDebugLoc();
17857 unsigned CountReg = MI->getOperand(0).getReg();
17858 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17859 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17861 if (!Subtarget->isTargetWin64()) {
17862 // If %al is 0, branch around the XMM save block.
17863 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17864 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17865 MBB->addSuccessor(EndMBB);
17868 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17869 // that was just emitted, but clearly shouldn't be "saved".
17870 assert((MI->getNumOperands() <= 3 ||
17871 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17872 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17873 && "Expected last argument to be EFLAGS");
17874 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17875 // In the XMM save block, save all the XMM argument registers.
17876 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17877 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17878 MachineMemOperand *MMO =
17879 F->getMachineMemOperand(
17880 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17881 MachineMemOperand::MOStore,
17882 /*Size=*/16, /*Align=*/16);
17883 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17884 .addFrameIndex(RegSaveFrameIndex)
17885 .addImm(/*Scale=*/1)
17886 .addReg(/*IndexReg=*/0)
17887 .addImm(/*Disp=*/Offset)
17888 .addReg(/*Segment=*/0)
17889 .addReg(MI->getOperand(i).getReg())
17890 .addMemOperand(MMO);
17893 MI->eraseFromParent(); // The pseudo instruction is gone now.
17898 // The EFLAGS operand of SelectItr might be missing a kill marker
17899 // because there were multiple uses of EFLAGS, and ISel didn't know
17900 // which to mark. Figure out whether SelectItr should have had a
17901 // kill marker, and set it if it should. Returns the correct kill
17903 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17904 MachineBasicBlock* BB,
17905 const TargetRegisterInfo* TRI) {
17906 // Scan forward through BB for a use/def of EFLAGS.
17907 MachineBasicBlock::iterator miI(std::next(SelectItr));
17908 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17909 const MachineInstr& mi = *miI;
17910 if (mi.readsRegister(X86::EFLAGS))
17912 if (mi.definesRegister(X86::EFLAGS))
17913 break; // Should have kill-flag - update below.
17916 // If we hit the end of the block, check whether EFLAGS is live into a
17918 if (miI == BB->end()) {
17919 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17920 sEnd = BB->succ_end();
17921 sItr != sEnd; ++sItr) {
17922 MachineBasicBlock* succ = *sItr;
17923 if (succ->isLiveIn(X86::EFLAGS))
17928 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17929 // out. SelectMI should have a kill flag on EFLAGS.
17930 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17934 MachineBasicBlock *
17935 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17936 MachineBasicBlock *BB) const {
17937 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
17938 DebugLoc DL = MI->getDebugLoc();
17940 // To "insert" a SELECT_CC instruction, we actually have to insert the
17941 // diamond control-flow pattern. The incoming instruction knows the
17942 // destination vreg to set, the condition code register to branch on, the
17943 // true/false values to select between, and a branch opcode to use.
17944 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17945 MachineFunction::iterator It = BB;
17951 // cmpTY ccX, r1, r2
17953 // fallthrough --> copy0MBB
17954 MachineBasicBlock *thisMBB = BB;
17955 MachineFunction *F = BB->getParent();
17956 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17957 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17958 F->insert(It, copy0MBB);
17959 F->insert(It, sinkMBB);
17961 // If the EFLAGS register isn't dead in the terminator, then claim that it's
17962 // live into the sink and copy blocks.
17963 const TargetRegisterInfo *TRI =
17964 BB->getParent()->getSubtarget().getRegisterInfo();
17965 if (!MI->killsRegister(X86::EFLAGS) &&
17966 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17967 copy0MBB->addLiveIn(X86::EFLAGS);
17968 sinkMBB->addLiveIn(X86::EFLAGS);
17971 // Transfer the remainder of BB and its successor edges to sinkMBB.
17972 sinkMBB->splice(sinkMBB->begin(), BB,
17973 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17974 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17976 // Add the true and fallthrough blocks as its successors.
17977 BB->addSuccessor(copy0MBB);
17978 BB->addSuccessor(sinkMBB);
17980 // Create the conditional branch instruction.
17982 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17983 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17986 // %FalseValue = ...
17987 // # fallthrough to sinkMBB
17988 copy0MBB->addSuccessor(sinkMBB);
17991 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17993 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17994 TII->get(X86::PHI), MI->getOperand(0).getReg())
17995 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17996 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17998 MI->eraseFromParent(); // The pseudo instruction is gone now.
18002 MachineBasicBlock *
18003 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18004 bool Is64Bit) const {
18005 MachineFunction *MF = BB->getParent();
18006 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18007 DebugLoc DL = MI->getDebugLoc();
18008 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18010 assert(MF->shouldSplitStack());
18012 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18013 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18016 // ... [Till the alloca]
18017 // If stacklet is not large enough, jump to mallocMBB
18020 // Allocate by subtracting from RSP
18021 // Jump to continueMBB
18024 // Allocate by call to runtime
18028 // [rest of original BB]
18031 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18032 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18033 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18035 MachineRegisterInfo &MRI = MF->getRegInfo();
18036 const TargetRegisterClass *AddrRegClass =
18037 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18039 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18040 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18041 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18042 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18043 sizeVReg = MI->getOperand(1).getReg(),
18044 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18046 MachineFunction::iterator MBBIter = BB;
18049 MF->insert(MBBIter, bumpMBB);
18050 MF->insert(MBBIter, mallocMBB);
18051 MF->insert(MBBIter, continueMBB);
18053 continueMBB->splice(continueMBB->begin(), BB,
18054 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18055 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18057 // Add code to the main basic block to check if the stack limit has been hit,
18058 // and if so, jump to mallocMBB otherwise to bumpMBB.
18059 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18060 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18061 .addReg(tmpSPVReg).addReg(sizeVReg);
18062 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18063 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18064 .addReg(SPLimitVReg);
18065 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18067 // bumpMBB simply decreases the stack pointer, since we know the current
18068 // stacklet has enough space.
18069 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18070 .addReg(SPLimitVReg);
18071 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18072 .addReg(SPLimitVReg);
18073 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18075 // Calls into a routine in libgcc to allocate more space from the heap.
18076 const uint32_t *RegMask = MF->getTarget()
18077 .getSubtargetImpl()
18078 ->getRegisterInfo()
18079 ->getCallPreservedMask(CallingConv::C);
18081 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18083 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18084 .addExternalSymbol("__morestack_allocate_stack_space")
18085 .addRegMask(RegMask)
18086 .addReg(X86::RDI, RegState::Implicit)
18087 .addReg(X86::RAX, RegState::ImplicitDefine);
18089 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18091 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18092 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18093 .addExternalSymbol("__morestack_allocate_stack_space")
18094 .addRegMask(RegMask)
18095 .addReg(X86::EAX, RegState::ImplicitDefine);
18099 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18102 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18103 .addReg(Is64Bit ? X86::RAX : X86::EAX);
18104 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18106 // Set up the CFG correctly.
18107 BB->addSuccessor(bumpMBB);
18108 BB->addSuccessor(mallocMBB);
18109 mallocMBB->addSuccessor(continueMBB);
18110 bumpMBB->addSuccessor(continueMBB);
18112 // Take care of the PHI nodes.
18113 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18114 MI->getOperand(0).getReg())
18115 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18116 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18118 // Delete the original pseudo instruction.
18119 MI->eraseFromParent();
18122 return continueMBB;
18125 MachineBasicBlock *
18126 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18127 MachineBasicBlock *BB) const {
18128 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18129 DebugLoc DL = MI->getDebugLoc();
18131 assert(!Subtarget->isTargetMacho());
18133 // The lowering is pretty easy: we're just emitting the call to _alloca. The
18134 // non-trivial part is impdef of ESP.
18136 if (Subtarget->isTargetWin64()) {
18137 if (Subtarget->isTargetCygMing()) {
18138 // ___chkstk(Mingw64):
18139 // Clobbers R10, R11, RAX and EFLAGS.
18141 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18142 .addExternalSymbol("___chkstk")
18143 .addReg(X86::RAX, RegState::Implicit)
18144 .addReg(X86::RSP, RegState::Implicit)
18145 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18146 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18147 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18149 // __chkstk(MSVCRT): does not update stack pointer.
18150 // Clobbers R10, R11 and EFLAGS.
18151 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18152 .addExternalSymbol("__chkstk")
18153 .addReg(X86::RAX, RegState::Implicit)
18154 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18155 // RAX has the offset to be subtracted from RSP.
18156 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18161 const char *StackProbeSymbol =
18162 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18164 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18165 .addExternalSymbol(StackProbeSymbol)
18166 .addReg(X86::EAX, RegState::Implicit)
18167 .addReg(X86::ESP, RegState::Implicit)
18168 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18169 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18170 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18173 MI->eraseFromParent(); // The pseudo instruction is gone now.
18177 MachineBasicBlock *
18178 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18179 MachineBasicBlock *BB) const {
18180 // This is pretty easy. We're taking the value that we received from
18181 // our load from the relocation, sticking it in either RDI (x86-64)
18182 // or EAX and doing an indirect call. The return value will then
18183 // be in the normal return register.
18184 MachineFunction *F = BB->getParent();
18185 const X86InstrInfo *TII =
18186 static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18187 DebugLoc DL = MI->getDebugLoc();
18189 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18190 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18192 // Get a register mask for the lowered call.
18193 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18194 // proper register mask.
18195 const uint32_t *RegMask = F->getTarget()
18196 .getSubtargetImpl()
18197 ->getRegisterInfo()
18198 ->getCallPreservedMask(CallingConv::C);
18199 if (Subtarget->is64Bit()) {
18200 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18201 TII->get(X86::MOV64rm), X86::RDI)
18203 .addImm(0).addReg(0)
18204 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18205 MI->getOperand(3).getTargetFlags())
18207 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18208 addDirectMem(MIB, X86::RDI);
18209 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18210 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18211 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18212 TII->get(X86::MOV32rm), X86::EAX)
18214 .addImm(0).addReg(0)
18215 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18216 MI->getOperand(3).getTargetFlags())
18218 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18219 addDirectMem(MIB, X86::EAX);
18220 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18222 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18223 TII->get(X86::MOV32rm), X86::EAX)
18224 .addReg(TII->getGlobalBaseReg(F))
18225 .addImm(0).addReg(0)
18226 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18227 MI->getOperand(3).getTargetFlags())
18229 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18230 addDirectMem(MIB, X86::EAX);
18231 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18234 MI->eraseFromParent(); // The pseudo instruction is gone now.
18238 MachineBasicBlock *
18239 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18240 MachineBasicBlock *MBB) const {
18241 DebugLoc DL = MI->getDebugLoc();
18242 MachineFunction *MF = MBB->getParent();
18243 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18244 MachineRegisterInfo &MRI = MF->getRegInfo();
18246 const BasicBlock *BB = MBB->getBasicBlock();
18247 MachineFunction::iterator I = MBB;
18250 // Memory Reference
18251 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18252 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18255 unsigned MemOpndSlot = 0;
18257 unsigned CurOp = 0;
18259 DstReg = MI->getOperand(CurOp++).getReg();
18260 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18261 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18262 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18263 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18265 MemOpndSlot = CurOp;
18267 MVT PVT = getPointerTy();
18268 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18269 "Invalid Pointer Size!");
18271 // For v = setjmp(buf), we generate
18274 // buf[LabelOffset] = restoreMBB
18275 // SjLjSetup restoreMBB
18281 // v = phi(main, restore)
18286 MachineBasicBlock *thisMBB = MBB;
18287 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18288 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18289 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18290 MF->insert(I, mainMBB);
18291 MF->insert(I, sinkMBB);
18292 MF->push_back(restoreMBB);
18294 MachineInstrBuilder MIB;
18296 // Transfer the remainder of BB and its successor edges to sinkMBB.
18297 sinkMBB->splice(sinkMBB->begin(), MBB,
18298 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18299 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18302 unsigned PtrStoreOpc = 0;
18303 unsigned LabelReg = 0;
18304 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18305 Reloc::Model RM = MF->getTarget().getRelocationModel();
18306 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18307 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18309 // Prepare IP either in reg or imm.
18310 if (!UseImmLabel) {
18311 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18312 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18313 LabelReg = MRI.createVirtualRegister(PtrRC);
18314 if (Subtarget->is64Bit()) {
18315 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18319 .addMBB(restoreMBB)
18322 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18323 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18324 .addReg(XII->getGlobalBaseReg(MF))
18327 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18331 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18333 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18334 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18335 if (i == X86::AddrDisp)
18336 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18338 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18341 MIB.addReg(LabelReg);
18343 MIB.addMBB(restoreMBB);
18344 MIB.setMemRefs(MMOBegin, MMOEnd);
18346 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18347 .addMBB(restoreMBB);
18349 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18350 MF->getSubtarget().getRegisterInfo());
18351 MIB.addRegMask(RegInfo->getNoPreservedMask());
18352 thisMBB->addSuccessor(mainMBB);
18353 thisMBB->addSuccessor(restoreMBB);
18357 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18358 mainMBB->addSuccessor(sinkMBB);
18361 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18362 TII->get(X86::PHI), DstReg)
18363 .addReg(mainDstReg).addMBB(mainMBB)
18364 .addReg(restoreDstReg).addMBB(restoreMBB);
18367 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18368 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18369 restoreMBB->addSuccessor(sinkMBB);
18371 MI->eraseFromParent();
18375 MachineBasicBlock *
18376 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18377 MachineBasicBlock *MBB) const {
18378 DebugLoc DL = MI->getDebugLoc();
18379 MachineFunction *MF = MBB->getParent();
18380 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18381 MachineRegisterInfo &MRI = MF->getRegInfo();
18383 // Memory Reference
18384 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18385 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18387 MVT PVT = getPointerTy();
18388 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18389 "Invalid Pointer Size!");
18391 const TargetRegisterClass *RC =
18392 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18393 unsigned Tmp = MRI.createVirtualRegister(RC);
18394 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18395 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18396 MF->getSubtarget().getRegisterInfo());
18397 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18398 unsigned SP = RegInfo->getStackRegister();
18400 MachineInstrBuilder MIB;
18402 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18403 const int64_t SPOffset = 2 * PVT.getStoreSize();
18405 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18406 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18409 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18410 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18411 MIB.addOperand(MI->getOperand(i));
18412 MIB.setMemRefs(MMOBegin, MMOEnd);
18414 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18415 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18416 if (i == X86::AddrDisp)
18417 MIB.addDisp(MI->getOperand(i), LabelOffset);
18419 MIB.addOperand(MI->getOperand(i));
18421 MIB.setMemRefs(MMOBegin, MMOEnd);
18423 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18424 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18425 if (i == X86::AddrDisp)
18426 MIB.addDisp(MI->getOperand(i), SPOffset);
18428 MIB.addOperand(MI->getOperand(i));
18430 MIB.setMemRefs(MMOBegin, MMOEnd);
18432 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18434 MI->eraseFromParent();
18438 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18439 // accumulator loops. Writing back to the accumulator allows the coalescer
18440 // to remove extra copies in the loop.
18441 MachineBasicBlock *
18442 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18443 MachineBasicBlock *MBB) const {
18444 MachineOperand &AddendOp = MI->getOperand(3);
18446 // Bail out early if the addend isn't a register - we can't switch these.
18447 if (!AddendOp.isReg())
18450 MachineFunction &MF = *MBB->getParent();
18451 MachineRegisterInfo &MRI = MF.getRegInfo();
18453 // Check whether the addend is defined by a PHI:
18454 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18455 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18456 if (!AddendDef.isPHI())
18459 // Look for the following pattern:
18461 // %addend = phi [%entry, 0], [%loop, %result]
18463 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18467 // %addend = phi [%entry, 0], [%loop, %result]
18469 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18471 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18472 assert(AddendDef.getOperand(i).isReg());
18473 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18474 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18475 if (&PHISrcInst == MI) {
18476 // Found a matching instruction.
18477 unsigned NewFMAOpc = 0;
18478 switch (MI->getOpcode()) {
18479 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18480 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18481 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18482 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18483 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18484 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18485 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18486 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18487 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18488 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18489 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18490 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18491 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18492 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18493 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18494 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18495 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18496 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18497 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18498 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18499 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18500 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18501 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18502 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18503 default: llvm_unreachable("Unrecognized FMA variant.");
18506 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18507 MachineInstrBuilder MIB =
18508 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18509 .addOperand(MI->getOperand(0))
18510 .addOperand(MI->getOperand(3))
18511 .addOperand(MI->getOperand(2))
18512 .addOperand(MI->getOperand(1));
18513 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18514 MI->eraseFromParent();
18521 MachineBasicBlock *
18522 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18523 MachineBasicBlock *BB) const {
18524 switch (MI->getOpcode()) {
18525 default: llvm_unreachable("Unexpected instr type to insert");
18526 case X86::TAILJMPd64:
18527 case X86::TAILJMPr64:
18528 case X86::TAILJMPm64:
18529 llvm_unreachable("TAILJMP64 would not be touched here.");
18530 case X86::TCRETURNdi64:
18531 case X86::TCRETURNri64:
18532 case X86::TCRETURNmi64:
18534 case X86::WIN_ALLOCA:
18535 return EmitLoweredWinAlloca(MI, BB);
18536 case X86::SEG_ALLOCA_32:
18537 return EmitLoweredSegAlloca(MI, BB, false);
18538 case X86::SEG_ALLOCA_64:
18539 return EmitLoweredSegAlloca(MI, BB, true);
18540 case X86::TLSCall_32:
18541 case X86::TLSCall_64:
18542 return EmitLoweredTLSCall(MI, BB);
18543 case X86::CMOV_GR8:
18544 case X86::CMOV_FR32:
18545 case X86::CMOV_FR64:
18546 case X86::CMOV_V4F32:
18547 case X86::CMOV_V2F64:
18548 case X86::CMOV_V2I64:
18549 case X86::CMOV_V8F32:
18550 case X86::CMOV_V4F64:
18551 case X86::CMOV_V4I64:
18552 case X86::CMOV_V16F32:
18553 case X86::CMOV_V8F64:
18554 case X86::CMOV_V8I64:
18555 case X86::CMOV_GR16:
18556 case X86::CMOV_GR32:
18557 case X86::CMOV_RFP32:
18558 case X86::CMOV_RFP64:
18559 case X86::CMOV_RFP80:
18560 return EmitLoweredSelect(MI, BB);
18562 case X86::FP32_TO_INT16_IN_MEM:
18563 case X86::FP32_TO_INT32_IN_MEM:
18564 case X86::FP32_TO_INT64_IN_MEM:
18565 case X86::FP64_TO_INT16_IN_MEM:
18566 case X86::FP64_TO_INT32_IN_MEM:
18567 case X86::FP64_TO_INT64_IN_MEM:
18568 case X86::FP80_TO_INT16_IN_MEM:
18569 case X86::FP80_TO_INT32_IN_MEM:
18570 case X86::FP80_TO_INT64_IN_MEM: {
18571 MachineFunction *F = BB->getParent();
18572 const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18573 DebugLoc DL = MI->getDebugLoc();
18575 // Change the floating point control register to use "round towards zero"
18576 // mode when truncating to an integer value.
18577 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18578 addFrameReference(BuildMI(*BB, MI, DL,
18579 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18581 // Load the old value of the high byte of the control word...
18583 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18584 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18587 // Set the high part to be round to zero...
18588 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18591 // Reload the modified control word now...
18592 addFrameReference(BuildMI(*BB, MI, DL,
18593 TII->get(X86::FLDCW16m)), CWFrameIdx);
18595 // Restore the memory image of control word to original value
18596 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18599 // Get the X86 opcode to use.
18601 switch (MI->getOpcode()) {
18602 default: llvm_unreachable("illegal opcode!");
18603 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18604 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18605 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18606 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18607 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18608 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18609 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18610 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18611 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18615 MachineOperand &Op = MI->getOperand(0);
18617 AM.BaseType = X86AddressMode::RegBase;
18618 AM.Base.Reg = Op.getReg();
18620 AM.BaseType = X86AddressMode::FrameIndexBase;
18621 AM.Base.FrameIndex = Op.getIndex();
18623 Op = MI->getOperand(1);
18625 AM.Scale = Op.getImm();
18626 Op = MI->getOperand(2);
18628 AM.IndexReg = Op.getImm();
18629 Op = MI->getOperand(3);
18630 if (Op.isGlobal()) {
18631 AM.GV = Op.getGlobal();
18633 AM.Disp = Op.getImm();
18635 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18636 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18638 // Reload the original control word now.
18639 addFrameReference(BuildMI(*BB, MI, DL,
18640 TII->get(X86::FLDCW16m)), CWFrameIdx);
18642 MI->eraseFromParent(); // The pseudo instruction is gone now.
18645 // String/text processing lowering.
18646 case X86::PCMPISTRM128REG:
18647 case X86::VPCMPISTRM128REG:
18648 case X86::PCMPISTRM128MEM:
18649 case X86::VPCMPISTRM128MEM:
18650 case X86::PCMPESTRM128REG:
18651 case X86::VPCMPESTRM128REG:
18652 case X86::PCMPESTRM128MEM:
18653 case X86::VPCMPESTRM128MEM:
18654 assert(Subtarget->hasSSE42() &&
18655 "Target must have SSE4.2 or AVX features enabled");
18656 return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18658 // String/text processing lowering.
18659 case X86::PCMPISTRIREG:
18660 case X86::VPCMPISTRIREG:
18661 case X86::PCMPISTRIMEM:
18662 case X86::VPCMPISTRIMEM:
18663 case X86::PCMPESTRIREG:
18664 case X86::VPCMPESTRIREG:
18665 case X86::PCMPESTRIMEM:
18666 case X86::VPCMPESTRIMEM:
18667 assert(Subtarget->hasSSE42() &&
18668 "Target must have SSE4.2 or AVX features enabled");
18669 return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18671 // Thread synchronization.
18673 return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
18678 return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18680 case X86::VASTART_SAVE_XMM_REGS:
18681 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18683 case X86::VAARG_64:
18684 return EmitVAARG64WithCustomInserter(MI, BB);
18686 case X86::EH_SjLj_SetJmp32:
18687 case X86::EH_SjLj_SetJmp64:
18688 return emitEHSjLjSetJmp(MI, BB);
18690 case X86::EH_SjLj_LongJmp32:
18691 case X86::EH_SjLj_LongJmp64:
18692 return emitEHSjLjLongJmp(MI, BB);
18694 case TargetOpcode::STACKMAP:
18695 case TargetOpcode::PATCHPOINT:
18696 return emitPatchPoint(MI, BB);
18698 case X86::VFMADDPDr213r:
18699 case X86::VFMADDPSr213r:
18700 case X86::VFMADDSDr213r:
18701 case X86::VFMADDSSr213r:
18702 case X86::VFMSUBPDr213r:
18703 case X86::VFMSUBPSr213r:
18704 case X86::VFMSUBSDr213r:
18705 case X86::VFMSUBSSr213r:
18706 case X86::VFNMADDPDr213r:
18707 case X86::VFNMADDPSr213r:
18708 case X86::VFNMADDSDr213r:
18709 case X86::VFNMADDSSr213r:
18710 case X86::VFNMSUBPDr213r:
18711 case X86::VFNMSUBPSr213r:
18712 case X86::VFNMSUBSDr213r:
18713 case X86::VFNMSUBSSr213r:
18714 case X86::VFMADDPDr213rY:
18715 case X86::VFMADDPSr213rY:
18716 case X86::VFMSUBPDr213rY:
18717 case X86::VFMSUBPSr213rY:
18718 case X86::VFNMADDPDr213rY:
18719 case X86::VFNMADDPSr213rY:
18720 case X86::VFNMSUBPDr213rY:
18721 case X86::VFNMSUBPSr213rY:
18722 return emitFMA3Instr(MI, BB);
18726 //===----------------------------------------------------------------------===//
18727 // X86 Optimization Hooks
18728 //===----------------------------------------------------------------------===//
18730 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18733 const SelectionDAG &DAG,
18734 unsigned Depth) const {
18735 unsigned BitWidth = KnownZero.getBitWidth();
18736 unsigned Opc = Op.getOpcode();
18737 assert((Opc >= ISD::BUILTIN_OP_END ||
18738 Opc == ISD::INTRINSIC_WO_CHAIN ||
18739 Opc == ISD::INTRINSIC_W_CHAIN ||
18740 Opc == ISD::INTRINSIC_VOID) &&
18741 "Should use MaskedValueIsZero if you don't know whether Op"
18742 " is a target node!");
18744 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18758 // These nodes' second result is a boolean.
18759 if (Op.getResNo() == 0)
18762 case X86ISD::SETCC:
18763 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18765 case ISD::INTRINSIC_WO_CHAIN: {
18766 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18767 unsigned NumLoBits = 0;
18770 case Intrinsic::x86_sse_movmsk_ps:
18771 case Intrinsic::x86_avx_movmsk_ps_256:
18772 case Intrinsic::x86_sse2_movmsk_pd:
18773 case Intrinsic::x86_avx_movmsk_pd_256:
18774 case Intrinsic::x86_mmx_pmovmskb:
18775 case Intrinsic::x86_sse2_pmovmskb_128:
18776 case Intrinsic::x86_avx2_pmovmskb: {
18777 // High bits of movmskp{s|d}, pmovmskb are known zero.
18779 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18780 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18781 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18782 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18783 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18784 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18785 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18786 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18788 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18797 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18799 const SelectionDAG &,
18800 unsigned Depth) const {
18801 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18802 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18803 return Op.getValueType().getScalarType().getSizeInBits();
18809 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18810 /// node is a GlobalAddress + offset.
18811 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18812 const GlobalValue* &GA,
18813 int64_t &Offset) const {
18814 if (N->getOpcode() == X86ISD::Wrapper) {
18815 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18816 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18817 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18821 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18824 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18825 /// same as extracting the high 128-bit part of 256-bit vector and then
18826 /// inserting the result into the low part of a new 256-bit vector
18827 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18828 EVT VT = SVOp->getValueType(0);
18829 unsigned NumElems = VT.getVectorNumElements();
18831 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18832 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18833 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18834 SVOp->getMaskElt(j) >= 0)
18840 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18841 /// same as extracting the low 128-bit part of 256-bit vector and then
18842 /// inserting the result into the high part of a new 256-bit vector
18843 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18844 EVT VT = SVOp->getValueType(0);
18845 unsigned NumElems = VT.getVectorNumElements();
18847 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18848 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18849 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18850 SVOp->getMaskElt(j) >= 0)
18856 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18857 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18858 TargetLowering::DAGCombinerInfo &DCI,
18859 const X86Subtarget* Subtarget) {
18861 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18862 SDValue V1 = SVOp->getOperand(0);
18863 SDValue V2 = SVOp->getOperand(1);
18864 EVT VT = SVOp->getValueType(0);
18865 unsigned NumElems = VT.getVectorNumElements();
18867 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18868 V2.getOpcode() == ISD::CONCAT_VECTORS) {
18872 // V UNDEF BUILD_VECTOR UNDEF
18874 // CONCAT_VECTOR CONCAT_VECTOR
18877 // RESULT: V + zero extended
18879 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18880 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18881 V1.getOperand(1).getOpcode() != ISD::UNDEF)
18884 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18887 // To match the shuffle mask, the first half of the mask should
18888 // be exactly the first vector, and all the rest a splat with the
18889 // first element of the second one.
18890 for (unsigned i = 0; i != NumElems/2; ++i)
18891 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18892 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18895 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18896 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18897 if (Ld->hasNUsesOfValue(1, 0)) {
18898 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18899 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18901 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18903 Ld->getPointerInfo(),
18904 Ld->getAlignment(),
18905 false/*isVolatile*/, true/*ReadMem*/,
18906 false/*WriteMem*/);
18908 // Make sure the newly-created LOAD is in the same position as Ld in
18909 // terms of dependency. We create a TokenFactor for Ld and ResNode,
18910 // and update uses of Ld's output chain to use the TokenFactor.
18911 if (Ld->hasAnyUseOfValue(1)) {
18912 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18913 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18914 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18915 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18916 SDValue(ResNode.getNode(), 1));
18919 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18923 // Emit a zeroed vector and insert the desired subvector on its
18925 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18926 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18927 return DCI.CombineTo(N, InsV);
18930 //===--------------------------------------------------------------------===//
18931 // Combine some shuffles into subvector extracts and inserts:
18934 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18935 if (isShuffleHigh128VectorInsertLow(SVOp)) {
18936 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18937 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18938 return DCI.CombineTo(N, InsV);
18941 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18942 if (isShuffleLow128VectorInsertHigh(SVOp)) {
18943 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18944 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18945 return DCI.CombineTo(N, InsV);
18951 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
18954 /// This is the leaf of the recursive combinine below. When we have found some
18955 /// chain of single-use x86 shuffle instructions and accumulated the combined
18956 /// shuffle mask represented by them, this will try to pattern match that mask
18957 /// into either a single instruction if there is a special purpose instruction
18958 /// for this operation, or into a PSHUFB instruction which is a fully general
18959 /// instruction but should only be used to replace chains over a certain depth.
18960 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
18961 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
18962 TargetLowering::DAGCombinerInfo &DCI,
18963 const X86Subtarget *Subtarget) {
18964 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
18966 // Find the operand that enters the chain. Note that multiple uses are OK
18967 // here, we're not going to remove the operand we find.
18968 SDValue Input = Op.getOperand(0);
18969 while (Input.getOpcode() == ISD::BITCAST)
18970 Input = Input.getOperand(0);
18972 MVT VT = Input.getSimpleValueType();
18973 MVT RootVT = Root.getSimpleValueType();
18976 // Just remove no-op shuffle masks.
18977 if (Mask.size() == 1) {
18978 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
18983 // Use the float domain if the operand type is a floating point type.
18984 bool FloatDomain = VT.isFloatingPoint();
18986 // If we don't have access to VEX encodings, the generic PSHUF instructions
18987 // are preferable to some of the specialized forms despite requiring one more
18988 // byte to encode because they can implicitly copy.
18990 // IF we *do* have VEX encodings, than we can use shorter, more specific
18991 // shuffle instructions freely as they can copy due to the extra register
18993 if (Subtarget->hasAVX()) {
18994 // We have both floating point and integer variants of shuffles that dup
18995 // either the low or high half of the vector.
18996 if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
18997 bool Lo = Mask.equals(0, 0);
18998 unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
18999 : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19000 if (Depth == 1 && Root->getOpcode() == Shuffle)
19001 return false; // Nothing to do!
19002 MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19003 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19004 DCI.AddToWorklist(Op.getNode());
19005 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19006 DCI.AddToWorklist(Op.getNode());
19007 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19012 // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19014 // For the integer domain we have specialized instructions for duplicating
19015 // any element size from the low or high half.
19016 if (!FloatDomain &&
19017 (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19018 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19019 Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19020 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19021 Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19023 bool Lo = Mask[0] == 0;
19024 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19025 if (Depth == 1 && Root->getOpcode() == Shuffle)
19026 return false; // Nothing to do!
19028 switch (Mask.size()) {
19029 case 4: ShuffleVT = MVT::v4i32; break;
19030 case 8: ShuffleVT = MVT::v8i16; break;
19031 case 16: ShuffleVT = MVT::v16i8; break;
19033 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19034 DCI.AddToWorklist(Op.getNode());
19035 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19036 DCI.AddToWorklist(Op.getNode());
19037 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19043 // Don't try to re-form single instruction chains under any circumstances now
19044 // that we've done encoding canonicalization for them.
19048 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19049 // can replace them with a single PSHUFB instruction profitably. Intel's
19050 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19051 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19052 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19053 SmallVector<SDValue, 16> PSHUFBMask;
19054 assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19055 int Ratio = 16 / Mask.size();
19056 for (unsigned i = 0; i < 16; ++i) {
19057 int M = Ratio * Mask[i / Ratio] + i % Ratio;
19058 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19060 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19061 DCI.AddToWorklist(Op.getNode());
19062 SDValue PSHUFBMaskOp =
19063 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19064 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19065 Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19066 DCI.AddToWorklist(Op.getNode());
19067 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19072 // Failed to find any combines.
19076 /// \brief Fully generic combining of x86 shuffle instructions.
19078 /// This should be the last combine run over the x86 shuffle instructions. Once
19079 /// they have been fully optimized, this will recursively consdier all chains
19080 /// of single-use shuffle instructions, build a generic model of the cumulative
19081 /// shuffle operation, and check for simpler instructions which implement this
19082 /// operation. We use this primarily for two purposes:
19084 /// 1) Collapse generic shuffles to specialized single instructions when
19085 /// equivalent. In most cases, this is just an encoding size win, but
19086 /// sometimes we will collapse multiple generic shuffles into a single
19087 /// special-purpose shuffle.
19088 /// 2) Look for sequences of shuffle instructions with 3 or more total
19089 /// instructions, and replace them with the slightly more expensive SSSE3
19090 /// PSHUFB instruction if available. We do this as the last combining step
19091 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
19092 /// a suitable short sequence of other instructions. The PHUFB will either
19093 /// use a register or have to read from memory and so is slightly (but only
19094 /// slightly) more expensive than the other shuffle instructions.
19096 /// Because this is inherently a quadratic operation (for each shuffle in
19097 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19098 /// This should never be an issue in practice as the shuffle lowering doesn't
19099 /// produce sequences of more than 8 instructions.
19101 /// FIXME: We will currently miss some cases where the redundant shuffling
19102 /// would simplify under the threshold for PSHUFB formation because of
19103 /// combine-ordering. To fix this, we should do the redundant instruction
19104 /// combining in this recursive walk.
19105 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19106 ArrayRef<int> IncomingMask, int Depth,
19107 bool HasPSHUFB, SelectionDAG &DAG,
19108 TargetLowering::DAGCombinerInfo &DCI,
19109 const X86Subtarget *Subtarget) {
19110 // Bound the depth of our recursive combine because this is ultimately
19111 // quadratic in nature.
19115 // Directly rip through bitcasts to find the underlying operand.
19116 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19117 Op = Op.getOperand(0);
19119 MVT VT = Op.getSimpleValueType();
19120 if (!VT.isVector())
19121 return false; // Bail if we hit a non-vector.
19122 // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19123 // version should be added.
19124 if (VT.getSizeInBits() != 128)
19127 assert(Root.getSimpleValueType().isVector() &&
19128 "Shuffles operate on vector types!");
19129 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19130 "Can only combine shuffles of the same vector register size.");
19132 if (!isTargetShuffle(Op.getOpcode()))
19134 SmallVector<int, 16> OpMask;
19136 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19137 // We only can combine unary shuffles which we can decode the mask for.
19138 if (!HaveMask || !IsUnary)
19141 assert(VT.getVectorNumElements() == OpMask.size() &&
19142 "Different mask size from vector size!");
19144 SmallVector<int, 16> Mask;
19145 Mask.reserve(std::max(OpMask.size(), IncomingMask.size()));
19147 // Merge this shuffle operation's mask into our accumulated mask. This is
19148 // a bit tricky as the shuffle may have a different size from the root.
19149 if (OpMask.size() == IncomingMask.size()) {
19150 for (int M : IncomingMask)
19151 Mask.push_back(OpMask[M]);
19152 } else if (OpMask.size() < IncomingMask.size()) {
19153 assert(IncomingMask.size() % OpMask.size() == 0 &&
19154 "The smaller number of elements must divide the larger.");
19155 int Ratio = IncomingMask.size() / OpMask.size();
19156 for (int M : IncomingMask)
19157 Mask.push_back(Ratio * OpMask[M / Ratio] + M % Ratio);
19159 assert(OpMask.size() > IncomingMask.size() && "All other cases handled!");
19160 assert(OpMask.size() % IncomingMask.size() == 0 &&
19161 "The smaller number of elements must divide the larger.");
19162 int Ratio = OpMask.size() / IncomingMask.size();
19163 for (int i = 0, e = OpMask.size(); i < e; ++i)
19164 Mask.push_back(OpMask[Ratio * IncomingMask[i / Ratio] + i % Ratio]);
19167 // See if we can recurse into the operand to combine more things.
19168 switch (Op.getOpcode()) {
19169 case X86ISD::PSHUFB:
19171 case X86ISD::PSHUFD:
19172 case X86ISD::PSHUFHW:
19173 case X86ISD::PSHUFLW:
19174 if (Op.getOperand(0).hasOneUse() &&
19175 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19176 HasPSHUFB, DAG, DCI, Subtarget))
19180 case X86ISD::UNPCKL:
19181 case X86ISD::UNPCKH:
19182 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19183 // We can't check for single use, we have to check that this shuffle is the only user.
19184 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19185 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19186 HasPSHUFB, DAG, DCI, Subtarget))
19191 // Minor canonicalization of the accumulated shuffle mask to make it easier
19192 // to match below. All this does is detect masks with squential pairs of
19193 // elements, and shrink them to the half-width mask. It does this in a loop
19194 // so it will reduce the size of the mask to the minimal width mask which
19195 // performs an equivalent shuffle.
19196 while (Mask.size() > 1) {
19197 SmallVector<int, 16> NewMask;
19198 for (int i = 0, e = Mask.size()/2; i < e; ++i) {
19199 if (Mask[2*i] % 2 != 0 || Mask[2*i] != Mask[2*i + 1] + 1) {
19203 NewMask.push_back(Mask[2*i] / 2);
19205 if (NewMask.empty())
19207 Mask.swap(NewMask);
19210 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19214 /// \brief Get the PSHUF-style mask from PSHUF node.
19216 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19217 /// PSHUF-style masks that can be reused with such instructions.
19218 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19219 SmallVector<int, 4> Mask;
19221 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19225 switch (N.getOpcode()) {
19226 case X86ISD::PSHUFD:
19228 case X86ISD::PSHUFLW:
19231 case X86ISD::PSHUFHW:
19232 Mask.erase(Mask.begin(), Mask.begin() + 4);
19233 for (int &M : Mask)
19237 llvm_unreachable("No valid shuffle instruction found!");
19241 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19243 /// We walk up the chain and look for a combinable shuffle, skipping over
19244 /// shuffles that we could hoist this shuffle's transformation past without
19245 /// altering anything.
19246 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19248 TargetLowering::DAGCombinerInfo &DCI) {
19249 assert(N.getOpcode() == X86ISD::PSHUFD &&
19250 "Called with something other than an x86 128-bit half shuffle!");
19253 // Walk up a single-use chain looking for a combinable shuffle.
19254 SDValue V = N.getOperand(0);
19255 for (; V.hasOneUse(); V = V.getOperand(0)) {
19256 switch (V.getOpcode()) {
19258 return false; // Nothing combined!
19261 // Skip bitcasts as we always know the type for the target specific
19265 case X86ISD::PSHUFD:
19266 // Found another dword shuffle.
19269 case X86ISD::PSHUFLW:
19270 // Check that the low words (being shuffled) are the identity in the
19271 // dword shuffle, and the high words are self-contained.
19272 if (Mask[0] != 0 || Mask[1] != 1 ||
19273 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19278 case X86ISD::PSHUFHW:
19279 // Check that the high words (being shuffled) are the identity in the
19280 // dword shuffle, and the low words are self-contained.
19281 if (Mask[2] != 2 || Mask[3] != 3 ||
19282 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19287 case X86ISD::UNPCKL:
19288 case X86ISD::UNPCKH:
19289 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19290 // shuffle into a preceding word shuffle.
19291 if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19294 // Search for a half-shuffle which we can combine with.
19295 unsigned CombineOp =
19296 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19297 if (V.getOperand(0) != V.getOperand(1) ||
19298 !V->isOnlyUserOf(V.getOperand(0).getNode()))
19300 V = V.getOperand(0);
19302 switch (V.getOpcode()) {
19304 return false; // Nothing to combine.
19306 case X86ISD::PSHUFLW:
19307 case X86ISD::PSHUFHW:
19308 if (V.getOpcode() == CombineOp)
19313 V = V.getOperand(0);
19317 } while (V.hasOneUse());
19320 // Break out of the loop if we break out of the switch.
19324 if (!V.hasOneUse())
19325 // We fell out of the loop without finding a viable combining instruction.
19328 // Record the old value to use in RAUW-ing.
19331 // Merge this node's mask and our incoming mask.
19332 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19333 for (int &M : Mask)
19335 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19336 getV4X86ShuffleImm8ForMask(Mask, DAG));
19338 // It is possible that one of the combinable shuffles was completely absorbed
19339 // by the other, just replace it and revisit all users in that case.
19340 if (Old.getNode() == V.getNode()) {
19341 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19345 // Replace N with its operand as we're going to combine that shuffle away.
19346 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19348 // Replace the combinable shuffle with the combined one, updating all users
19349 // so that we re-evaluate the chain here.
19350 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19354 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19356 /// We walk up the chain, skipping shuffles of the other half and looking
19357 /// through shuffles which switch halves trying to find a shuffle of the same
19358 /// pair of dwords.
19359 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19361 TargetLowering::DAGCombinerInfo &DCI) {
19363 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19364 "Called with something other than an x86 128-bit half shuffle!");
19366 unsigned CombineOpcode = N.getOpcode();
19368 // Walk up a single-use chain looking for a combinable shuffle.
19369 SDValue V = N.getOperand(0);
19370 for (; V.hasOneUse(); V = V.getOperand(0)) {
19371 switch (V.getOpcode()) {
19373 return false; // Nothing combined!
19376 // Skip bitcasts as we always know the type for the target specific
19380 case X86ISD::PSHUFLW:
19381 case X86ISD::PSHUFHW:
19382 if (V.getOpcode() == CombineOpcode)
19385 // Other-half shuffles are no-ops.
19388 case X86ISD::PSHUFD: {
19389 // We can only handle pshufd if the half we are combining either stays in
19390 // its half, or switches to the other half. Bail if one of these isn't
19392 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19393 int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
19394 if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
19395 (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
19398 // Map the mask through the pshufd and keep walking up the chain.
19399 for (int i = 0; i < 4; ++i)
19400 Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
19402 // Switch halves if the pshufd does.
19404 VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19408 // Break out of the loop if we break out of the switch.
19412 if (!V.hasOneUse())
19413 // We fell out of the loop without finding a viable combining instruction.
19416 // Record the old value to use in RAUW-ing.
19419 // Merge this node's mask and our incoming mask (adjusted to account for all
19420 // the pshufd instructions encountered).
19421 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19422 for (int &M : Mask)
19424 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19425 getV4X86ShuffleImm8ForMask(Mask, DAG));
19427 // Replace N with its operand as we're going to combine that shuffle away.
19428 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19430 // Replace the combinable shuffle with the combined one, updating all users
19431 // so that we re-evaluate the chain here.
19432 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19436 /// \brief Try to combine x86 target specific shuffles.
19437 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19438 TargetLowering::DAGCombinerInfo &DCI,
19439 const X86Subtarget *Subtarget) {
19441 MVT VT = N.getSimpleValueType();
19442 SmallVector<int, 4> Mask;
19444 switch (N.getOpcode()) {
19445 case X86ISD::PSHUFD:
19446 case X86ISD::PSHUFLW:
19447 case X86ISD::PSHUFHW:
19448 Mask = getPSHUFShuffleMask(N);
19449 assert(Mask.size() == 4);
19455 // Nuke no-op shuffles that show up after combining.
19456 if (isNoopShuffleMask(Mask))
19457 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19459 // Look for simplifications involving one or two shuffle instructions.
19460 SDValue V = N.getOperand(0);
19461 switch (N.getOpcode()) {
19464 case X86ISD::PSHUFLW:
19465 case X86ISD::PSHUFHW:
19466 assert(VT == MVT::v8i16);
19469 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19470 return SDValue(); // We combined away this shuffle, so we're done.
19472 // See if this reduces to a PSHUFD which is no more expensive and can
19473 // combine with more operations.
19474 if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
19475 areAdjacentMasksSequential(Mask)) {
19476 int DMask[] = {-1, -1, -1, -1};
19477 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19478 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19479 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19480 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19481 DCI.AddToWorklist(V.getNode());
19482 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19483 getV4X86ShuffleImm8ForMask(DMask, DAG));
19484 DCI.AddToWorklist(V.getNode());
19485 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19488 // Look for shuffle patterns which can be implemented as a single unpack.
19489 // FIXME: This doesn't handle the location of the PSHUFD generically, and
19490 // only works when we have a PSHUFD followed by two half-shuffles.
19491 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19492 (V.getOpcode() == X86ISD::PSHUFLW ||
19493 V.getOpcode() == X86ISD::PSHUFHW) &&
19494 V.getOpcode() != N.getOpcode() &&
19496 SDValue D = V.getOperand(0);
19497 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19498 D = D.getOperand(0);
19499 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19500 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19501 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19502 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19503 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19505 for (int i = 0; i < 4; ++i) {
19506 WordMask[i + NOffset] = Mask[i] + NOffset;
19507 WordMask[i + VOffset] = VMask[i] + VOffset;
19509 // Map the word mask through the DWord mask.
19511 for (int i = 0; i < 8; ++i)
19512 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19513 const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19514 const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19515 if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19516 std::begin(UnpackLoMask)) ||
19517 std::equal(std::begin(MappedMask), std::end(MappedMask),
19518 std::begin(UnpackHiMask))) {
19519 // We can replace all three shuffles with an unpack.
19520 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19521 DCI.AddToWorklist(V.getNode());
19522 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19524 DL, MVT::v8i16, V, V);
19531 case X86ISD::PSHUFD:
19532 if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19533 return SDValue(); // We combined away this shuffle.
19541 /// PerformShuffleCombine - Performs several different shuffle combines.
19542 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19543 TargetLowering::DAGCombinerInfo &DCI,
19544 const X86Subtarget *Subtarget) {
19546 SDValue N0 = N->getOperand(0);
19547 SDValue N1 = N->getOperand(1);
19548 EVT VT = N->getValueType(0);
19550 // Don't create instructions with illegal types after legalize types has run.
19551 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19552 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19555 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19556 if (Subtarget->hasFp256() && VT.is256BitVector() &&
19557 N->getOpcode() == ISD::VECTOR_SHUFFLE)
19558 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19560 // During Type Legalization, when promoting illegal vector types,
19561 // the backend might introduce new shuffle dag nodes and bitcasts.
19563 // This code performs the following transformation:
19564 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19565 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19567 // We do this only if both the bitcast and the BINOP dag nodes have
19568 // one use. Also, perform this transformation only if the new binary
19569 // operation is legal. This is to avoid introducing dag nodes that
19570 // potentially need to be further expanded (or custom lowered) into a
19571 // less optimal sequence of dag nodes.
19572 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19573 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19574 N0.getOpcode() == ISD::BITCAST) {
19575 SDValue BC0 = N0.getOperand(0);
19576 EVT SVT = BC0.getValueType();
19577 unsigned Opcode = BC0.getOpcode();
19578 unsigned NumElts = VT.getVectorNumElements();
19580 if (BC0.hasOneUse() && SVT.isVector() &&
19581 SVT.getVectorNumElements() * 2 == NumElts &&
19582 TLI.isOperationLegal(Opcode, VT)) {
19583 bool CanFold = false;
19595 unsigned SVTNumElts = SVT.getVectorNumElements();
19596 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19597 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19598 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19599 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19600 CanFold = SVOp->getMaskElt(i) < 0;
19603 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19604 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19605 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19606 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19611 // Only handle 128 wide vector from here on.
19612 if (!VT.is128BitVector())
19615 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19616 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19617 // consecutive, non-overlapping, and in the right order.
19618 SmallVector<SDValue, 16> Elts;
19619 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19620 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19622 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19626 if (isTargetShuffle(N->getOpcode())) {
19628 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19629 if (Shuffle.getNode())
19632 // Try recursively combining arbitrary sequences of x86 shuffle
19633 // instructions into higher-order shuffles. We do this after combining
19634 // specific PSHUF instruction sequences into their minimal form so that we
19635 // can evaluate how many specialized shuffle instructions are involved in
19636 // a particular chain.
19637 SmallVector<int, 1> NonceMask; // Just a placeholder.
19638 NonceMask.push_back(0);
19639 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19640 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19642 return SDValue(); // This routine will use CombineTo to replace N.
19648 /// PerformTruncateCombine - Converts truncate operation to
19649 /// a sequence of vector shuffle operations.
19650 /// It is possible when we truncate 256-bit vector to 128-bit vector
19651 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19652 TargetLowering::DAGCombinerInfo &DCI,
19653 const X86Subtarget *Subtarget) {
19657 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19658 /// specific shuffle of a load can be folded into a single element load.
19659 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19660 /// shuffles have been customed lowered so we need to handle those here.
19661 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19662 TargetLowering::DAGCombinerInfo &DCI) {
19663 if (DCI.isBeforeLegalizeOps())
19666 SDValue InVec = N->getOperand(0);
19667 SDValue EltNo = N->getOperand(1);
19669 if (!isa<ConstantSDNode>(EltNo))
19672 EVT VT = InVec.getValueType();
19674 bool HasShuffleIntoBitcast = false;
19675 if (InVec.getOpcode() == ISD::BITCAST) {
19676 // Don't duplicate a load with other uses.
19677 if (!InVec.hasOneUse())
19679 EVT BCVT = InVec.getOperand(0).getValueType();
19680 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19682 InVec = InVec.getOperand(0);
19683 HasShuffleIntoBitcast = true;
19686 if (!isTargetShuffle(InVec.getOpcode()))
19689 // Don't duplicate a load with other uses.
19690 if (!InVec.hasOneUse())
19693 SmallVector<int, 16> ShuffleMask;
19695 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19699 // Select the input vector, guarding against out of range extract vector.
19700 unsigned NumElems = VT.getVectorNumElements();
19701 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19702 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19703 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19704 : InVec.getOperand(1);
19706 // If inputs to shuffle are the same for both ops, then allow 2 uses
19707 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19709 if (LdNode.getOpcode() == ISD::BITCAST) {
19710 // Don't duplicate a load with other uses.
19711 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19714 AllowedUses = 1; // only allow 1 load use if we have a bitcast
19715 LdNode = LdNode.getOperand(0);
19718 if (!ISD::isNormalLoad(LdNode.getNode()))
19721 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19723 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19726 if (HasShuffleIntoBitcast) {
19727 // If there's a bitcast before the shuffle, check if the load type and
19728 // alignment is valid.
19729 unsigned Align = LN0->getAlignment();
19730 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19731 unsigned NewAlign = TLI.getDataLayout()->
19732 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19734 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19738 // All checks match so transform back to vector_shuffle so that DAG combiner
19739 // can finish the job
19742 // Create shuffle node taking into account the case that its a unary shuffle
19743 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19744 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19745 InVec.getOperand(0), Shuffle,
19747 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19748 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19752 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19753 /// generation and convert it from being a bunch of shuffles and extracts
19754 /// to a simple store and scalar loads to extract the elements.
19755 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19756 TargetLowering::DAGCombinerInfo &DCI) {
19757 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19758 if (NewOp.getNode())
19761 SDValue InputVector = N->getOperand(0);
19763 // Detect whether we are trying to convert from mmx to i32 and the bitcast
19764 // from mmx to v2i32 has a single usage.
19765 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19766 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19767 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19768 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19769 N->getValueType(0),
19770 InputVector.getNode()->getOperand(0));
19772 // Only operate on vectors of 4 elements, where the alternative shuffling
19773 // gets to be more expensive.
19774 if (InputVector.getValueType() != MVT::v4i32)
19777 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19778 // single use which is a sign-extend or zero-extend, and all elements are
19780 SmallVector<SDNode *, 4> Uses;
19781 unsigned ExtractedElements = 0;
19782 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19783 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19784 if (UI.getUse().getResNo() != InputVector.getResNo())
19787 SDNode *Extract = *UI;
19788 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19791 if (Extract->getValueType(0) != MVT::i32)
19793 if (!Extract->hasOneUse())
19795 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19796 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19798 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19801 // Record which element was extracted.
19802 ExtractedElements |=
19803 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19805 Uses.push_back(Extract);
19808 // If not all the elements were used, this may not be worthwhile.
19809 if (ExtractedElements != 15)
19812 // Ok, we've now decided to do the transformation.
19813 SDLoc dl(InputVector);
19815 // Store the value to a temporary stack slot.
19816 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19817 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19818 MachinePointerInfo(), false, false, 0);
19820 // Replace each use (extract) with a load of the appropriate element.
19821 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19822 UE = Uses.end(); UI != UE; ++UI) {
19823 SDNode *Extract = *UI;
19825 // cOMpute the element's address.
19826 SDValue Idx = Extract->getOperand(1);
19828 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19829 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19830 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19831 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19833 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19834 StackPtr, OffsetVal);
19836 // Load the scalar.
19837 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19838 ScalarAddr, MachinePointerInfo(),
19839 false, false, false, 0);
19841 // Replace the exact with the load.
19842 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19845 // The replacement was made in place; don't return anything.
19849 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19850 static std::pair<unsigned, bool>
19851 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19852 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19853 if (!VT.isVector())
19854 return std::make_pair(0, false);
19856 bool NeedSplit = false;
19857 switch (VT.getSimpleVT().SimpleTy) {
19858 default: return std::make_pair(0, false);
19862 if (!Subtarget->hasAVX2())
19864 if (!Subtarget->hasAVX())
19865 return std::make_pair(0, false);
19870 if (!Subtarget->hasSSE2())
19871 return std::make_pair(0, false);
19874 // SSE2 has only a small subset of the operations.
19875 bool hasUnsigned = Subtarget->hasSSE41() ||
19876 (Subtarget->hasSSE2() && VT == MVT::v16i8);
19877 bool hasSigned = Subtarget->hasSSE41() ||
19878 (Subtarget->hasSSE2() && VT == MVT::v8i16);
19880 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19883 // Check for x CC y ? x : y.
19884 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19885 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19890 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19893 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19896 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19899 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19901 // Check for x CC y ? y : x -- a min/max with reversed arms.
19902 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19903 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19908 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19911 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19914 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19917 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19921 return std::make_pair(Opc, NeedSplit);
19925 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19926 const X86Subtarget *Subtarget) {
19928 SDValue Cond = N->getOperand(0);
19929 SDValue LHS = N->getOperand(1);
19930 SDValue RHS = N->getOperand(2);
19932 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19933 SDValue CondSrc = Cond->getOperand(0);
19934 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19935 Cond = CondSrc->getOperand(0);
19938 MVT VT = N->getSimpleValueType(0);
19939 MVT EltVT = VT.getVectorElementType();
19940 unsigned NumElems = VT.getVectorNumElements();
19941 // There is no blend with immediate in AVX-512.
19942 if (VT.is512BitVector())
19945 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19947 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19950 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19953 unsigned MaskValue = 0;
19954 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19957 SmallVector<int, 8> ShuffleMask(NumElems, -1);
19958 for (unsigned i = 0; i < NumElems; ++i) {
19959 // Be sure we emit undef where we can.
19960 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19961 ShuffleMask[i] = -1;
19963 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19966 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19969 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19971 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19972 TargetLowering::DAGCombinerInfo &DCI,
19973 const X86Subtarget *Subtarget) {
19975 SDValue Cond = N->getOperand(0);
19976 // Get the LHS/RHS of the select.
19977 SDValue LHS = N->getOperand(1);
19978 SDValue RHS = N->getOperand(2);
19979 EVT VT = LHS.getValueType();
19980 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19982 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19983 // instructions match the semantics of the common C idiom x<y?x:y but not
19984 // x<=y?x:y, because of how they handle negative zero (which can be
19985 // ignored in unsafe-math mode).
19986 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19987 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19988 (Subtarget->hasSSE2() ||
19989 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19990 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19992 unsigned Opcode = 0;
19993 // Check for x CC y ? x : y.
19994 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19995 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19999 // Converting this to a min would handle NaNs incorrectly, and swapping
20000 // the operands would cause it to handle comparisons between positive
20001 // and negative zero incorrectly.
20002 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20003 if (!DAG.getTarget().Options.UnsafeFPMath &&
20004 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20006 std::swap(LHS, RHS);
20008 Opcode = X86ISD::FMIN;
20011 // Converting this to a min would handle comparisons between positive
20012 // and negative zero incorrectly.
20013 if (!DAG.getTarget().Options.UnsafeFPMath &&
20014 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20016 Opcode = X86ISD::FMIN;
20019 // Converting this to a min would handle both negative zeros and NaNs
20020 // incorrectly, but we can swap the operands to fix both.
20021 std::swap(LHS, RHS);
20025 Opcode = X86ISD::FMIN;
20029 // Converting this to a max would handle comparisons between positive
20030 // and negative zero incorrectly.
20031 if (!DAG.getTarget().Options.UnsafeFPMath &&
20032 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20034 Opcode = X86ISD::FMAX;
20037 // Converting this to a max would handle NaNs incorrectly, and swapping
20038 // the operands would cause it to handle comparisons between positive
20039 // and negative zero incorrectly.
20040 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20041 if (!DAG.getTarget().Options.UnsafeFPMath &&
20042 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20044 std::swap(LHS, RHS);
20046 Opcode = X86ISD::FMAX;
20049 // Converting this to a max would handle both negative zeros and NaNs
20050 // incorrectly, but we can swap the operands to fix both.
20051 std::swap(LHS, RHS);
20055 Opcode = X86ISD::FMAX;
20058 // Check for x CC y ? y : x -- a min/max with reversed arms.
20059 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20060 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20064 // Converting this to a min would handle comparisons between positive
20065 // and negative zero incorrectly, and swapping the operands would
20066 // cause it to handle NaNs incorrectly.
20067 if (!DAG.getTarget().Options.UnsafeFPMath &&
20068 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20069 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20071 std::swap(LHS, RHS);
20073 Opcode = X86ISD::FMIN;
20076 // Converting this to a min would handle NaNs incorrectly.
20077 if (!DAG.getTarget().Options.UnsafeFPMath &&
20078 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20080 Opcode = X86ISD::FMIN;
20083 // Converting this to a min would handle both negative zeros and NaNs
20084 // incorrectly, but we can swap the operands to fix both.
20085 std::swap(LHS, RHS);
20089 Opcode = X86ISD::FMIN;
20093 // Converting this to a max would handle NaNs incorrectly.
20094 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20096 Opcode = X86ISD::FMAX;
20099 // Converting this to a max would handle comparisons between positive
20100 // and negative zero incorrectly, and swapping the operands would
20101 // cause it to handle NaNs incorrectly.
20102 if (!DAG.getTarget().Options.UnsafeFPMath &&
20103 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20104 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20106 std::swap(LHS, RHS);
20108 Opcode = X86ISD::FMAX;
20111 // Converting this to a max would handle both negative zeros and NaNs
20112 // incorrectly, but we can swap the operands to fix both.
20113 std::swap(LHS, RHS);
20117 Opcode = X86ISD::FMAX;
20123 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20126 EVT CondVT = Cond.getValueType();
20127 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20128 CondVT.getVectorElementType() == MVT::i1) {
20129 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20130 // lowering on AVX-512. In this case we convert it to
20131 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20132 // The same situation for all 128 and 256-bit vectors of i8 and i16
20133 EVT OpVT = LHS.getValueType();
20134 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20135 (OpVT.getVectorElementType() == MVT::i8 ||
20136 OpVT.getVectorElementType() == MVT::i16)) {
20137 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20138 DCI.AddToWorklist(Cond.getNode());
20139 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20142 // If this is a select between two integer constants, try to do some
20144 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20145 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20146 // Don't do this for crazy integer types.
20147 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20148 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20149 // so that TrueC (the true value) is larger than FalseC.
20150 bool NeedsCondInvert = false;
20152 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20153 // Efficiently invertible.
20154 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20155 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20156 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20157 NeedsCondInvert = true;
20158 std::swap(TrueC, FalseC);
20161 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20162 if (FalseC->getAPIntValue() == 0 &&
20163 TrueC->getAPIntValue().isPowerOf2()) {
20164 if (NeedsCondInvert) // Invert the condition if needed.
20165 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20166 DAG.getConstant(1, Cond.getValueType()));
20168 // Zero extend the condition if needed.
20169 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20171 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20172 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20173 DAG.getConstant(ShAmt, MVT::i8));
20176 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20177 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20178 if (NeedsCondInvert) // Invert the condition if needed.
20179 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20180 DAG.getConstant(1, Cond.getValueType()));
20182 // Zero extend the condition if needed.
20183 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20184 FalseC->getValueType(0), Cond);
20185 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20186 SDValue(FalseC, 0));
20189 // Optimize cases that will turn into an LEA instruction. This requires
20190 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20191 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20192 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20193 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20195 bool isFastMultiplier = false;
20197 switch ((unsigned char)Diff) {
20199 case 1: // result = add base, cond
20200 case 2: // result = lea base( , cond*2)
20201 case 3: // result = lea base(cond, cond*2)
20202 case 4: // result = lea base( , cond*4)
20203 case 5: // result = lea base(cond, cond*4)
20204 case 8: // result = lea base( , cond*8)
20205 case 9: // result = lea base(cond, cond*8)
20206 isFastMultiplier = true;
20211 if (isFastMultiplier) {
20212 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20213 if (NeedsCondInvert) // Invert the condition if needed.
20214 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20215 DAG.getConstant(1, Cond.getValueType()));
20217 // Zero extend the condition if needed.
20218 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20220 // Scale the condition by the difference.
20222 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20223 DAG.getConstant(Diff, Cond.getValueType()));
20225 // Add the base if non-zero.
20226 if (FalseC->getAPIntValue() != 0)
20227 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20228 SDValue(FalseC, 0));
20235 // Canonicalize max and min:
20236 // (x > y) ? x : y -> (x >= y) ? x : y
20237 // (x < y) ? x : y -> (x <= y) ? x : y
20238 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20239 // the need for an extra compare
20240 // against zero. e.g.
20241 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20243 // testl %edi, %edi
20245 // cmovgl %edi, %eax
20249 // cmovsl %eax, %edi
20250 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20251 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20252 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20253 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20258 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20259 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20260 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20261 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20266 // Early exit check
20267 if (!TLI.isTypeLegal(VT))
20270 // Match VSELECTs into subs with unsigned saturation.
20271 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20272 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20273 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20274 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20275 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20277 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20278 // left side invert the predicate to simplify logic below.
20280 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20282 CC = ISD::getSetCCInverse(CC, true);
20283 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20287 if (Other.getNode() && Other->getNumOperands() == 2 &&
20288 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20289 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20290 SDValue CondRHS = Cond->getOperand(1);
20292 // Look for a general sub with unsigned saturation first.
20293 // x >= y ? x-y : 0 --> subus x, y
20294 // x > y ? x-y : 0 --> subus x, y
20295 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20296 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20297 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20299 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20300 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20301 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20302 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20303 // If the RHS is a constant we have to reverse the const
20304 // canonicalization.
20305 // x > C-1 ? x+-C : 0 --> subus x, C
20306 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20307 CondRHSConst->getAPIntValue() ==
20308 (-OpRHSConst->getAPIntValue() - 1))
20309 return DAG.getNode(
20310 X86ISD::SUBUS, DL, VT, OpLHS,
20311 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20313 // Another special case: If C was a sign bit, the sub has been
20314 // canonicalized into a xor.
20315 // FIXME: Would it be better to use computeKnownBits to determine
20316 // whether it's safe to decanonicalize the xor?
20317 // x s< 0 ? x^C : 0 --> subus x, C
20318 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20319 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20320 OpRHSConst->getAPIntValue().isSignBit())
20321 // Note that we have to rebuild the RHS constant here to ensure we
20322 // don't rely on particular values of undef lanes.
20323 return DAG.getNode(
20324 X86ISD::SUBUS, DL, VT, OpLHS,
20325 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20330 // Try to match a min/max vector operation.
20331 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20332 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20333 unsigned Opc = ret.first;
20334 bool NeedSplit = ret.second;
20336 if (Opc && NeedSplit) {
20337 unsigned NumElems = VT.getVectorNumElements();
20338 // Extract the LHS vectors
20339 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20340 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20342 // Extract the RHS vectors
20343 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20344 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20346 // Create min/max for each subvector
20347 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20348 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20350 // Merge the result
20351 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20353 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20356 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20357 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20358 // Check if SETCC has already been promoted
20359 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20360 // Check that condition value type matches vselect operand type
20363 assert(Cond.getValueType().isVector() &&
20364 "vector select expects a vector selector!");
20366 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20367 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20369 if (!TValIsAllOnes && !FValIsAllZeros) {
20370 // Try invert the condition if true value is not all 1s and false value
20372 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20373 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20375 if (TValIsAllZeros || FValIsAllOnes) {
20376 SDValue CC = Cond.getOperand(2);
20377 ISD::CondCode NewCC =
20378 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20379 Cond.getOperand(0).getValueType().isInteger());
20380 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20381 std::swap(LHS, RHS);
20382 TValIsAllOnes = FValIsAllOnes;
20383 FValIsAllZeros = TValIsAllZeros;
20387 if (TValIsAllOnes || FValIsAllZeros) {
20390 if (TValIsAllOnes && FValIsAllZeros)
20392 else if (TValIsAllOnes)
20393 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20394 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20395 else if (FValIsAllZeros)
20396 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20397 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20399 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20403 // Try to fold this VSELECT into a MOVSS/MOVSD
20404 if (N->getOpcode() == ISD::VSELECT &&
20405 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20406 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20407 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20408 bool CanFold = false;
20409 unsigned NumElems = Cond.getNumOperands();
20413 if (isZero(Cond.getOperand(0))) {
20416 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20417 // fold (vselect <0,-1> -> (movsd A, B)
20418 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20419 CanFold = isAllOnes(Cond.getOperand(i));
20420 } else if (isAllOnes(Cond.getOperand(0))) {
20424 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20425 // fold (vselect <-1,0> -> (movsd B, A)
20426 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20427 CanFold = isZero(Cond.getOperand(i));
20431 if (VT == MVT::v4i32 || VT == MVT::v4f32)
20432 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20433 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20436 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20437 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20438 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20439 // (v2i64 (bitcast B)))))
20441 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20442 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20443 // (v2f64 (bitcast B)))))
20445 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20446 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20447 // (v2i64 (bitcast A)))))
20449 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20450 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20451 // (v2f64 (bitcast A)))))
20453 CanFold = (isZero(Cond.getOperand(0)) &&
20454 isZero(Cond.getOperand(1)) &&
20455 isAllOnes(Cond.getOperand(2)) &&
20456 isAllOnes(Cond.getOperand(3)));
20458 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20459 isAllOnes(Cond.getOperand(1)) &&
20460 isZero(Cond.getOperand(2)) &&
20461 isZero(Cond.getOperand(3))) {
20463 std::swap(LHS, RHS);
20467 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20468 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20469 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20470 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20472 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20478 // If we know that this node is legal then we know that it is going to be
20479 // matched by one of the SSE/AVX BLEND instructions. These instructions only
20480 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20481 // to simplify previous instructions.
20482 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20483 !DCI.isBeforeLegalize() &&
20484 // We explicitly check against v8i16 and v16i16 because, although
20485 // they're marked as Custom, they might only be legal when Cond is a
20486 // build_vector of constants. This will be taken care in a later
20488 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20489 VT != MVT::v8i16)) {
20490 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20492 // Don't optimize vector selects that map to mask-registers.
20496 // Check all uses of that condition operand to check whether it will be
20497 // consumed by non-BLEND instructions, which may depend on all bits are set
20499 for (SDNode::use_iterator I = Cond->use_begin(),
20500 E = Cond->use_end(); I != E; ++I)
20501 if (I->getOpcode() != ISD::VSELECT)
20502 // TODO: Add other opcodes eventually lowered into BLEND.
20505 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20506 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20508 APInt KnownZero, KnownOne;
20509 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20510 DCI.isBeforeLegalizeOps());
20511 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20512 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20513 DCI.CommitTargetLoweringOpt(TLO);
20516 // We should generate an X86ISD::BLENDI from a vselect if its argument
20517 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20518 // constants. This specific pattern gets generated when we split a
20519 // selector for a 512 bit vector in a machine without AVX512 (but with
20520 // 256-bit vectors), during legalization:
20522 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20524 // Iff we find this pattern and the build_vectors are built from
20525 // constants, we translate the vselect into a shuffle_vector that we
20526 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20527 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20528 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20529 if (Shuffle.getNode())
20536 // Check whether a boolean test is testing a boolean value generated by
20537 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20540 // Simplify the following patterns:
20541 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20542 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20543 // to (Op EFLAGS Cond)
20545 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20546 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20547 // to (Op EFLAGS !Cond)
20549 // where Op could be BRCOND or CMOV.
20551 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20552 // Quit if not CMP and SUB with its value result used.
20553 if (Cmp.getOpcode() != X86ISD::CMP &&
20554 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20557 // Quit if not used as a boolean value.
20558 if (CC != X86::COND_E && CC != X86::COND_NE)
20561 // Check CMP operands. One of them should be 0 or 1 and the other should be
20562 // an SetCC or extended from it.
20563 SDValue Op1 = Cmp.getOperand(0);
20564 SDValue Op2 = Cmp.getOperand(1);
20567 const ConstantSDNode* C = nullptr;
20568 bool needOppositeCond = (CC == X86::COND_E);
20569 bool checkAgainstTrue = false; // Is it a comparison against 1?
20571 if ((C = dyn_cast<ConstantSDNode>(Op1)))
20573 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20575 else // Quit if all operands are not constants.
20578 if (C->getZExtValue() == 1) {
20579 needOppositeCond = !needOppositeCond;
20580 checkAgainstTrue = true;
20581 } else if (C->getZExtValue() != 0)
20582 // Quit if the constant is neither 0 or 1.
20585 bool truncatedToBoolWithAnd = false;
20586 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20587 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20588 SetCC.getOpcode() == ISD::TRUNCATE ||
20589 SetCC.getOpcode() == ISD::AND) {
20590 if (SetCC.getOpcode() == ISD::AND) {
20592 ConstantSDNode *CS;
20593 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20594 CS->getZExtValue() == 1)
20596 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20597 CS->getZExtValue() == 1)
20601 SetCC = SetCC.getOperand(OpIdx);
20602 truncatedToBoolWithAnd = true;
20604 SetCC = SetCC.getOperand(0);
20607 switch (SetCC.getOpcode()) {
20608 case X86ISD::SETCC_CARRY:
20609 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20610 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20611 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20612 // truncated to i1 using 'and'.
20613 if (checkAgainstTrue && !truncatedToBoolWithAnd)
20615 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20616 "Invalid use of SETCC_CARRY!");
20618 case X86ISD::SETCC:
20619 // Set the condition code or opposite one if necessary.
20620 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20621 if (needOppositeCond)
20622 CC = X86::GetOppositeBranchCondition(CC);
20623 return SetCC.getOperand(1);
20624 case X86ISD::CMOV: {
20625 // Check whether false/true value has canonical one, i.e. 0 or 1.
20626 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20627 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20628 // Quit if true value is not a constant.
20631 // Quit if false value is not a constant.
20633 SDValue Op = SetCC.getOperand(0);
20634 // Skip 'zext' or 'trunc' node.
20635 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20636 Op.getOpcode() == ISD::TRUNCATE)
20637 Op = Op.getOperand(0);
20638 // A special case for rdrand/rdseed, where 0 is set if false cond is
20640 if ((Op.getOpcode() != X86ISD::RDRAND &&
20641 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20644 // Quit if false value is not the constant 0 or 1.
20645 bool FValIsFalse = true;
20646 if (FVal && FVal->getZExtValue() != 0) {
20647 if (FVal->getZExtValue() != 1)
20649 // If FVal is 1, opposite cond is needed.
20650 needOppositeCond = !needOppositeCond;
20651 FValIsFalse = false;
20653 // Quit if TVal is not the constant opposite of FVal.
20654 if (FValIsFalse && TVal->getZExtValue() != 1)
20656 if (!FValIsFalse && TVal->getZExtValue() != 0)
20658 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20659 if (needOppositeCond)
20660 CC = X86::GetOppositeBranchCondition(CC);
20661 return SetCC.getOperand(3);
20668 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20669 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20670 TargetLowering::DAGCombinerInfo &DCI,
20671 const X86Subtarget *Subtarget) {
20674 // If the flag operand isn't dead, don't touch this CMOV.
20675 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20678 SDValue FalseOp = N->getOperand(0);
20679 SDValue TrueOp = N->getOperand(1);
20680 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20681 SDValue Cond = N->getOperand(3);
20683 if (CC == X86::COND_E || CC == X86::COND_NE) {
20684 switch (Cond.getOpcode()) {
20688 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20689 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20690 return (CC == X86::COND_E) ? FalseOp : TrueOp;
20696 Flags = checkBoolTestSetCCCombine(Cond, CC);
20697 if (Flags.getNode() &&
20698 // Extra check as FCMOV only supports a subset of X86 cond.
20699 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20700 SDValue Ops[] = { FalseOp, TrueOp,
20701 DAG.getConstant(CC, MVT::i8), Flags };
20702 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20705 // If this is a select between two integer constants, try to do some
20706 // optimizations. Note that the operands are ordered the opposite of SELECT
20708 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20709 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20710 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20711 // larger than FalseC (the false value).
20712 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20713 CC = X86::GetOppositeBranchCondition(CC);
20714 std::swap(TrueC, FalseC);
20715 std::swap(TrueOp, FalseOp);
20718 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
20719 // This is efficient for any integer data type (including i8/i16) and
20721 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20722 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20723 DAG.getConstant(CC, MVT::i8), Cond);
20725 // Zero extend the condition if needed.
20726 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20728 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20729 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20730 DAG.getConstant(ShAmt, MVT::i8));
20731 if (N->getNumValues() == 2) // Dead flag value?
20732 return DCI.CombineTo(N, Cond, SDValue());
20736 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
20737 // for any integer data type, including i8/i16.
20738 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20739 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20740 DAG.getConstant(CC, MVT::i8), Cond);
20742 // Zero extend the condition if needed.
20743 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20744 FalseC->getValueType(0), Cond);
20745 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20746 SDValue(FalseC, 0));
20748 if (N->getNumValues() == 2) // Dead flag value?
20749 return DCI.CombineTo(N, Cond, SDValue());
20753 // Optimize cases that will turn into an LEA instruction. This requires
20754 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20755 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20756 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20757 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20759 bool isFastMultiplier = false;
20761 switch ((unsigned char)Diff) {
20763 case 1: // result = add base, cond
20764 case 2: // result = lea base( , cond*2)
20765 case 3: // result = lea base(cond, cond*2)
20766 case 4: // result = lea base( , cond*4)
20767 case 5: // result = lea base(cond, cond*4)
20768 case 8: // result = lea base( , cond*8)
20769 case 9: // result = lea base(cond, cond*8)
20770 isFastMultiplier = true;
20775 if (isFastMultiplier) {
20776 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20777 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20778 DAG.getConstant(CC, MVT::i8), Cond);
20779 // Zero extend the condition if needed.
20780 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20782 // Scale the condition by the difference.
20784 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20785 DAG.getConstant(Diff, Cond.getValueType()));
20787 // Add the base if non-zero.
20788 if (FalseC->getAPIntValue() != 0)
20789 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20790 SDValue(FalseC, 0));
20791 if (N->getNumValues() == 2) // Dead flag value?
20792 return DCI.CombineTo(N, Cond, SDValue());
20799 // Handle these cases:
20800 // (select (x != c), e, c) -> select (x != c), e, x),
20801 // (select (x == c), c, e) -> select (x == c), x, e)
20802 // where the c is an integer constant, and the "select" is the combination
20803 // of CMOV and CMP.
20805 // The rationale for this change is that the conditional-move from a constant
20806 // needs two instructions, however, conditional-move from a register needs
20807 // only one instruction.
20809 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20810 // some instruction-combining opportunities. This opt needs to be
20811 // postponed as late as possible.
20813 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20814 // the DCI.xxxx conditions are provided to postpone the optimization as
20815 // late as possible.
20817 ConstantSDNode *CmpAgainst = nullptr;
20818 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20819 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20820 !isa<ConstantSDNode>(Cond.getOperand(0))) {
20822 if (CC == X86::COND_NE &&
20823 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20824 CC = X86::GetOppositeBranchCondition(CC);
20825 std::swap(TrueOp, FalseOp);
20828 if (CC == X86::COND_E &&
20829 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20830 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20831 DAG.getConstant(CC, MVT::i8), Cond };
20832 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20840 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20841 const X86Subtarget *Subtarget) {
20842 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20844 default: return SDValue();
20845 // SSE/AVX/AVX2 blend intrinsics.
20846 case Intrinsic::x86_avx2_pblendvb:
20847 case Intrinsic::x86_avx2_pblendw:
20848 case Intrinsic::x86_avx2_pblendd_128:
20849 case Intrinsic::x86_avx2_pblendd_256:
20850 // Don't try to simplify this intrinsic if we don't have AVX2.
20851 if (!Subtarget->hasAVX2())
20854 case Intrinsic::x86_avx_blend_pd_256:
20855 case Intrinsic::x86_avx_blend_ps_256:
20856 case Intrinsic::x86_avx_blendv_pd_256:
20857 case Intrinsic::x86_avx_blendv_ps_256:
20858 // Don't try to simplify this intrinsic if we don't have AVX.
20859 if (!Subtarget->hasAVX())
20862 case Intrinsic::x86_sse41_pblendw:
20863 case Intrinsic::x86_sse41_blendpd:
20864 case Intrinsic::x86_sse41_blendps:
20865 case Intrinsic::x86_sse41_blendvps:
20866 case Intrinsic::x86_sse41_blendvpd:
20867 case Intrinsic::x86_sse41_pblendvb: {
20868 SDValue Op0 = N->getOperand(1);
20869 SDValue Op1 = N->getOperand(2);
20870 SDValue Mask = N->getOperand(3);
20872 // Don't try to simplify this intrinsic if we don't have SSE4.1.
20873 if (!Subtarget->hasSSE41())
20876 // fold (blend A, A, Mask) -> A
20879 // fold (blend A, B, allZeros) -> A
20880 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20882 // fold (blend A, B, allOnes) -> B
20883 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20886 // Simplify the case where the mask is a constant i32 value.
20887 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20888 if (C->isNullValue())
20890 if (C->isAllOnesValue())
20897 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20898 case Intrinsic::x86_sse2_psrai_w:
20899 case Intrinsic::x86_sse2_psrai_d:
20900 case Intrinsic::x86_avx2_psrai_w:
20901 case Intrinsic::x86_avx2_psrai_d:
20902 case Intrinsic::x86_sse2_psra_w:
20903 case Intrinsic::x86_sse2_psra_d:
20904 case Intrinsic::x86_avx2_psra_w:
20905 case Intrinsic::x86_avx2_psra_d: {
20906 SDValue Op0 = N->getOperand(1);
20907 SDValue Op1 = N->getOperand(2);
20908 EVT VT = Op0.getValueType();
20909 assert(VT.isVector() && "Expected a vector type!");
20911 if (isa<BuildVectorSDNode>(Op1))
20912 Op1 = Op1.getOperand(0);
20914 if (!isa<ConstantSDNode>(Op1))
20917 EVT SVT = VT.getVectorElementType();
20918 unsigned SVTBits = SVT.getSizeInBits();
20920 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20921 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20922 uint64_t ShAmt = C.getZExtValue();
20924 // Don't try to convert this shift into a ISD::SRA if the shift
20925 // count is bigger than or equal to the element size.
20926 if (ShAmt >= SVTBits)
20929 // Trivial case: if the shift count is zero, then fold this
20930 // into the first operand.
20934 // Replace this packed shift intrinsic with a target independent
20936 SDValue Splat = DAG.getConstant(C, VT);
20937 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20942 /// PerformMulCombine - Optimize a single multiply with constant into two
20943 /// in order to implement it with two cheaper instructions, e.g.
20944 /// LEA + SHL, LEA + LEA.
20945 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20946 TargetLowering::DAGCombinerInfo &DCI) {
20947 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20950 EVT VT = N->getValueType(0);
20951 if (VT != MVT::i64)
20954 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20957 uint64_t MulAmt = C->getZExtValue();
20958 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20961 uint64_t MulAmt1 = 0;
20962 uint64_t MulAmt2 = 0;
20963 if ((MulAmt % 9) == 0) {
20965 MulAmt2 = MulAmt / 9;
20966 } else if ((MulAmt % 5) == 0) {
20968 MulAmt2 = MulAmt / 5;
20969 } else if ((MulAmt % 3) == 0) {
20971 MulAmt2 = MulAmt / 3;
20974 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20977 if (isPowerOf2_64(MulAmt2) &&
20978 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20979 // If second multiplifer is pow2, issue it first. We want the multiply by
20980 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20982 std::swap(MulAmt1, MulAmt2);
20985 if (isPowerOf2_64(MulAmt1))
20986 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20987 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20989 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20990 DAG.getConstant(MulAmt1, VT));
20992 if (isPowerOf2_64(MulAmt2))
20993 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20994 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20996 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20997 DAG.getConstant(MulAmt2, VT));
20999 // Do not add new nodes to DAG combiner worklist.
21000 DCI.CombineTo(N, NewMul, false);
21005 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21006 SDValue N0 = N->getOperand(0);
21007 SDValue N1 = N->getOperand(1);
21008 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21009 EVT VT = N0.getValueType();
21011 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21012 // since the result of setcc_c is all zero's or all ones.
21013 if (VT.isInteger() && !VT.isVector() &&
21014 N1C && N0.getOpcode() == ISD::AND &&
21015 N0.getOperand(1).getOpcode() == ISD::Constant) {
21016 SDValue N00 = N0.getOperand(0);
21017 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21018 ((N00.getOpcode() == ISD::ANY_EXTEND ||
21019 N00.getOpcode() == ISD::ZERO_EXTEND) &&
21020 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21021 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21022 APInt ShAmt = N1C->getAPIntValue();
21023 Mask = Mask.shl(ShAmt);
21025 return DAG.getNode(ISD::AND, SDLoc(N), VT,
21026 N00, DAG.getConstant(Mask, VT));
21030 // Hardware support for vector shifts is sparse which makes us scalarize the
21031 // vector operations in many cases. Also, on sandybridge ADD is faster than
21033 // (shl V, 1) -> add V,V
21034 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21035 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21036 assert(N0.getValueType().isVector() && "Invalid vector shift type");
21037 // We shift all of the values by one. In many cases we do not have
21038 // hardware support for this operation. This is better expressed as an ADD
21040 if (N1SplatC->getZExtValue() == 1)
21041 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21047 /// \brief Returns a vector of 0s if the node in input is a vector logical
21048 /// shift by a constant amount which is known to be bigger than or equal
21049 /// to the vector element size in bits.
21050 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21051 const X86Subtarget *Subtarget) {
21052 EVT VT = N->getValueType(0);
21054 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21055 (!Subtarget->hasInt256() ||
21056 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21059 SDValue Amt = N->getOperand(1);
21061 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21062 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21063 APInt ShiftAmt = AmtSplat->getAPIntValue();
21064 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21066 // SSE2/AVX2 logical shifts always return a vector of 0s
21067 // if the shift amount is bigger than or equal to
21068 // the element size. The constant shift amount will be
21069 // encoded as a 8-bit immediate.
21070 if (ShiftAmt.trunc(8).uge(MaxAmount))
21071 return getZeroVector(VT, Subtarget, DAG, DL);
21077 /// PerformShiftCombine - Combine shifts.
21078 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21079 TargetLowering::DAGCombinerInfo &DCI,
21080 const X86Subtarget *Subtarget) {
21081 if (N->getOpcode() == ISD::SHL) {
21082 SDValue V = PerformSHLCombine(N, DAG);
21083 if (V.getNode()) return V;
21086 if (N->getOpcode() != ISD::SRA) {
21087 // Try to fold this logical shift into a zero vector.
21088 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21089 if (V.getNode()) return V;
21095 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
21096 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21097 // and friends. Likewise for OR -> CMPNEQSS.
21098 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21099 TargetLowering::DAGCombinerInfo &DCI,
21100 const X86Subtarget *Subtarget) {
21103 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21104 // we're requiring SSE2 for both.
21105 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21106 SDValue N0 = N->getOperand(0);
21107 SDValue N1 = N->getOperand(1);
21108 SDValue CMP0 = N0->getOperand(1);
21109 SDValue CMP1 = N1->getOperand(1);
21112 // The SETCCs should both refer to the same CMP.
21113 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21116 SDValue CMP00 = CMP0->getOperand(0);
21117 SDValue CMP01 = CMP0->getOperand(1);
21118 EVT VT = CMP00.getValueType();
21120 if (VT == MVT::f32 || VT == MVT::f64) {
21121 bool ExpectingFlags = false;
21122 // Check for any users that want flags:
21123 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21124 !ExpectingFlags && UI != UE; ++UI)
21125 switch (UI->getOpcode()) {
21130 ExpectingFlags = true;
21132 case ISD::CopyToReg:
21133 case ISD::SIGN_EXTEND:
21134 case ISD::ZERO_EXTEND:
21135 case ISD::ANY_EXTEND:
21139 if (!ExpectingFlags) {
21140 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21141 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21143 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21144 X86::CondCode tmp = cc0;
21149 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
21150 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21151 // FIXME: need symbolic constants for these magic numbers.
21152 // See X86ATTInstPrinter.cpp:printSSECC().
21153 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21154 if (Subtarget->hasAVX512()) {
21155 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21156 CMP01, DAG.getConstant(x86cc, MVT::i8));
21157 if (N->getValueType(0) != MVT::i1)
21158 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21162 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21163 CMP00.getValueType(), CMP00, CMP01,
21164 DAG.getConstant(x86cc, MVT::i8));
21166 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21167 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21169 if (is64BitFP && !Subtarget->is64Bit()) {
21170 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21171 // 64-bit integer, since that's not a legal type. Since
21172 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21173 // bits, but can do this little dance to extract the lowest 32 bits
21174 // and work with those going forward.
21175 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21177 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21179 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21180 Vector32, DAG.getIntPtrConstant(0));
21184 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21185 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21186 DAG.getConstant(1, IntVT));
21187 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21188 return OneBitOfTruth;
21196 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21197 /// so it can be folded inside ANDNP.
21198 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21199 EVT VT = N->getValueType(0);
21201 // Match direct AllOnes for 128 and 256-bit vectors
21202 if (ISD::isBuildVectorAllOnes(N))
21205 // Look through a bit convert.
21206 if (N->getOpcode() == ISD::BITCAST)
21207 N = N->getOperand(0).getNode();
21209 // Sometimes the operand may come from a insert_subvector building a 256-bit
21211 if (VT.is256BitVector() &&
21212 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21213 SDValue V1 = N->getOperand(0);
21214 SDValue V2 = N->getOperand(1);
21216 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21217 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21218 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21219 ISD::isBuildVectorAllOnes(V2.getNode()))
21226 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21227 // register. In most cases we actually compare or select YMM-sized registers
21228 // and mixing the two types creates horrible code. This method optimizes
21229 // some of the transition sequences.
21230 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21231 TargetLowering::DAGCombinerInfo &DCI,
21232 const X86Subtarget *Subtarget) {
21233 EVT VT = N->getValueType(0);
21234 if (!VT.is256BitVector())
21237 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21238 N->getOpcode() == ISD::ZERO_EXTEND ||
21239 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21241 SDValue Narrow = N->getOperand(0);
21242 EVT NarrowVT = Narrow->getValueType(0);
21243 if (!NarrowVT.is128BitVector())
21246 if (Narrow->getOpcode() != ISD::XOR &&
21247 Narrow->getOpcode() != ISD::AND &&
21248 Narrow->getOpcode() != ISD::OR)
21251 SDValue N0 = Narrow->getOperand(0);
21252 SDValue N1 = Narrow->getOperand(1);
21255 // The Left side has to be a trunc.
21256 if (N0.getOpcode() != ISD::TRUNCATE)
21259 // The type of the truncated inputs.
21260 EVT WideVT = N0->getOperand(0)->getValueType(0);
21264 // The right side has to be a 'trunc' or a constant vector.
21265 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21266 ConstantSDNode *RHSConstSplat = nullptr;
21267 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21268 RHSConstSplat = RHSBV->getConstantSplatNode();
21269 if (!RHSTrunc && !RHSConstSplat)
21272 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21274 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21277 // Set N0 and N1 to hold the inputs to the new wide operation.
21278 N0 = N0->getOperand(0);
21279 if (RHSConstSplat) {
21280 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21281 SDValue(RHSConstSplat, 0));
21282 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21283 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21284 } else if (RHSTrunc) {
21285 N1 = N1->getOperand(0);
21288 // Generate the wide operation.
21289 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21290 unsigned Opcode = N->getOpcode();
21292 case ISD::ANY_EXTEND:
21294 case ISD::ZERO_EXTEND: {
21295 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21296 APInt Mask = APInt::getAllOnesValue(InBits);
21297 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21298 return DAG.getNode(ISD::AND, DL, VT,
21299 Op, DAG.getConstant(Mask, VT));
21301 case ISD::SIGN_EXTEND:
21302 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21303 Op, DAG.getValueType(NarrowVT));
21305 llvm_unreachable("Unexpected opcode");
21309 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21310 TargetLowering::DAGCombinerInfo &DCI,
21311 const X86Subtarget *Subtarget) {
21312 EVT VT = N->getValueType(0);
21313 if (DCI.isBeforeLegalizeOps())
21316 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21320 // Create BEXTR instructions
21321 // BEXTR is ((X >> imm) & (2**size-1))
21322 if (VT == MVT::i32 || VT == MVT::i64) {
21323 SDValue N0 = N->getOperand(0);
21324 SDValue N1 = N->getOperand(1);
21327 // Check for BEXTR.
21328 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21329 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21330 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21331 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21332 if (MaskNode && ShiftNode) {
21333 uint64_t Mask = MaskNode->getZExtValue();
21334 uint64_t Shift = ShiftNode->getZExtValue();
21335 if (isMask_64(Mask)) {
21336 uint64_t MaskSize = CountPopulation_64(Mask);
21337 if (Shift + MaskSize <= VT.getSizeInBits())
21338 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21339 DAG.getConstant(Shift | (MaskSize << 8), VT));
21347 // Want to form ANDNP nodes:
21348 // 1) In the hopes of then easily combining them with OR and AND nodes
21349 // to form PBLEND/PSIGN.
21350 // 2) To match ANDN packed intrinsics
21351 if (VT != MVT::v2i64 && VT != MVT::v4i64)
21354 SDValue N0 = N->getOperand(0);
21355 SDValue N1 = N->getOperand(1);
21358 // Check LHS for vnot
21359 if (N0.getOpcode() == ISD::XOR &&
21360 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21361 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21362 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21364 // Check RHS for vnot
21365 if (N1.getOpcode() == ISD::XOR &&
21366 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21367 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21368 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21373 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21374 TargetLowering::DAGCombinerInfo &DCI,
21375 const X86Subtarget *Subtarget) {
21376 if (DCI.isBeforeLegalizeOps())
21379 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21383 SDValue N0 = N->getOperand(0);
21384 SDValue N1 = N->getOperand(1);
21385 EVT VT = N->getValueType(0);
21387 // look for psign/blend
21388 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21389 if (!Subtarget->hasSSSE3() ||
21390 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21393 // Canonicalize pandn to RHS
21394 if (N0.getOpcode() == X86ISD::ANDNP)
21396 // or (and (m, y), (pandn m, x))
21397 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21398 SDValue Mask = N1.getOperand(0);
21399 SDValue X = N1.getOperand(1);
21401 if (N0.getOperand(0) == Mask)
21402 Y = N0.getOperand(1);
21403 if (N0.getOperand(1) == Mask)
21404 Y = N0.getOperand(0);
21406 // Check to see if the mask appeared in both the AND and ANDNP and
21410 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21411 // Look through mask bitcast.
21412 if (Mask.getOpcode() == ISD::BITCAST)
21413 Mask = Mask.getOperand(0);
21414 if (X.getOpcode() == ISD::BITCAST)
21415 X = X.getOperand(0);
21416 if (Y.getOpcode() == ISD::BITCAST)
21417 Y = Y.getOperand(0);
21419 EVT MaskVT = Mask.getValueType();
21421 // Validate that the Mask operand is a vector sra node.
21422 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21423 // there is no psrai.b
21424 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21425 unsigned SraAmt = ~0;
21426 if (Mask.getOpcode() == ISD::SRA) {
21427 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21428 if (auto *AmtConst = AmtBV->getConstantSplatNode())
21429 SraAmt = AmtConst->getZExtValue();
21430 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21431 SDValue SraC = Mask.getOperand(1);
21432 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
21434 if ((SraAmt + 1) != EltBits)
21439 // Now we know we at least have a plendvb with the mask val. See if
21440 // we can form a psignb/w/d.
21441 // psign = x.type == y.type == mask.type && y = sub(0, x);
21442 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21443 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21444 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21445 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21446 "Unsupported VT for PSIGN");
21447 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21448 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21450 // PBLENDVB only available on SSE 4.1
21451 if (!Subtarget->hasSSE41())
21454 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21456 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21457 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21458 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21459 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21460 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21464 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21467 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21468 MachineFunction &MF = DAG.getMachineFunction();
21469 bool OptForSize = MF.getFunction()->getAttributes().
21470 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21472 // SHLD/SHRD instructions have lower register pressure, but on some
21473 // platforms they have higher latency than the equivalent
21474 // series of shifts/or that would otherwise be generated.
21475 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21476 // have higher latencies and we are not optimizing for size.
21477 if (!OptForSize && Subtarget->isSHLDSlow())
21480 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21482 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21484 if (!N0.hasOneUse() || !N1.hasOneUse())
21487 SDValue ShAmt0 = N0.getOperand(1);
21488 if (ShAmt0.getValueType() != MVT::i8)
21490 SDValue ShAmt1 = N1.getOperand(1);
21491 if (ShAmt1.getValueType() != MVT::i8)
21493 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21494 ShAmt0 = ShAmt0.getOperand(0);
21495 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21496 ShAmt1 = ShAmt1.getOperand(0);
21499 unsigned Opc = X86ISD::SHLD;
21500 SDValue Op0 = N0.getOperand(0);
21501 SDValue Op1 = N1.getOperand(0);
21502 if (ShAmt0.getOpcode() == ISD::SUB) {
21503 Opc = X86ISD::SHRD;
21504 std::swap(Op0, Op1);
21505 std::swap(ShAmt0, ShAmt1);
21508 unsigned Bits = VT.getSizeInBits();
21509 if (ShAmt1.getOpcode() == ISD::SUB) {
21510 SDValue Sum = ShAmt1.getOperand(0);
21511 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21512 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21513 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21514 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21515 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21516 return DAG.getNode(Opc, DL, VT,
21518 DAG.getNode(ISD::TRUNCATE, DL,
21521 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21522 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21524 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21525 return DAG.getNode(Opc, DL, VT,
21526 N0.getOperand(0), N1.getOperand(0),
21527 DAG.getNode(ISD::TRUNCATE, DL,
21534 // Generate NEG and CMOV for integer abs.
21535 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21536 EVT VT = N->getValueType(0);
21538 // Since X86 does not have CMOV for 8-bit integer, we don't convert
21539 // 8-bit integer abs to NEG and CMOV.
21540 if (VT.isInteger() && VT.getSizeInBits() == 8)
21543 SDValue N0 = N->getOperand(0);
21544 SDValue N1 = N->getOperand(1);
21547 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21548 // and change it to SUB and CMOV.
21549 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21550 N0.getOpcode() == ISD::ADD &&
21551 N0.getOperand(1) == N1 &&
21552 N1.getOpcode() == ISD::SRA &&
21553 N1.getOperand(0) == N0.getOperand(0))
21554 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21555 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21556 // Generate SUB & CMOV.
21557 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21558 DAG.getConstant(0, VT), N0.getOperand(0));
21560 SDValue Ops[] = { N0.getOperand(0), Neg,
21561 DAG.getConstant(X86::COND_GE, MVT::i8),
21562 SDValue(Neg.getNode(), 1) };
21563 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21568 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21569 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21570 TargetLowering::DAGCombinerInfo &DCI,
21571 const X86Subtarget *Subtarget) {
21572 if (DCI.isBeforeLegalizeOps())
21575 if (Subtarget->hasCMov()) {
21576 SDValue RV = performIntegerAbsCombine(N, DAG);
21584 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21585 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21586 TargetLowering::DAGCombinerInfo &DCI,
21587 const X86Subtarget *Subtarget) {
21588 LoadSDNode *Ld = cast<LoadSDNode>(N);
21589 EVT RegVT = Ld->getValueType(0);
21590 EVT MemVT = Ld->getMemoryVT();
21592 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21594 // On Sandybridge unaligned 256bit loads are inefficient.
21595 ISD::LoadExtType Ext = Ld->getExtensionType();
21596 unsigned Alignment = Ld->getAlignment();
21597 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21598 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21599 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21600 unsigned NumElems = RegVT.getVectorNumElements();
21604 SDValue Ptr = Ld->getBasePtr();
21605 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21607 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21609 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21610 Ld->getPointerInfo(), Ld->isVolatile(),
21611 Ld->isNonTemporal(), Ld->isInvariant(),
21613 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21614 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21615 Ld->getPointerInfo(), Ld->isVolatile(),
21616 Ld->isNonTemporal(), Ld->isInvariant(),
21617 std::min(16U, Alignment));
21618 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21620 Load2.getValue(1));
21622 SDValue NewVec = DAG.getUNDEF(RegVT);
21623 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21624 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21625 return DCI.CombineTo(N, NewVec, TF, true);
21631 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21632 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21633 const X86Subtarget *Subtarget) {
21634 StoreSDNode *St = cast<StoreSDNode>(N);
21635 EVT VT = St->getValue().getValueType();
21636 EVT StVT = St->getMemoryVT();
21638 SDValue StoredVal = St->getOperand(1);
21639 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21641 // If we are saving a concatenation of two XMM registers, perform two stores.
21642 // On Sandy Bridge, 256-bit memory operations are executed by two
21643 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21644 // memory operation.
21645 unsigned Alignment = St->getAlignment();
21646 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21647 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21648 StVT == VT && !IsAligned) {
21649 unsigned NumElems = VT.getVectorNumElements();
21653 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21654 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21656 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21657 SDValue Ptr0 = St->getBasePtr();
21658 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21660 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21661 St->getPointerInfo(), St->isVolatile(),
21662 St->isNonTemporal(), Alignment);
21663 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21664 St->getPointerInfo(), St->isVolatile(),
21665 St->isNonTemporal(),
21666 std::min(16U, Alignment));
21667 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21670 // Optimize trunc store (of multiple scalars) to shuffle and store.
21671 // First, pack all of the elements in one place. Next, store to memory
21672 // in fewer chunks.
21673 if (St->isTruncatingStore() && VT.isVector()) {
21674 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21675 unsigned NumElems = VT.getVectorNumElements();
21676 assert(StVT != VT && "Cannot truncate to the same type");
21677 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21678 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21680 // From, To sizes and ElemCount must be pow of two
21681 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21682 // We are going to use the original vector elt for storing.
21683 // Accumulated smaller vector elements must be a multiple of the store size.
21684 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21686 unsigned SizeRatio = FromSz / ToSz;
21688 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21690 // Create a type on which we perform the shuffle
21691 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21692 StVT.getScalarType(), NumElems*SizeRatio);
21694 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21696 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21697 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21698 for (unsigned i = 0; i != NumElems; ++i)
21699 ShuffleVec[i] = i * SizeRatio;
21701 // Can't shuffle using an illegal type.
21702 if (!TLI.isTypeLegal(WideVecVT))
21705 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21706 DAG.getUNDEF(WideVecVT),
21708 // At this point all of the data is stored at the bottom of the
21709 // register. We now need to save it to mem.
21711 // Find the largest store unit
21712 MVT StoreType = MVT::i8;
21713 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21714 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21715 MVT Tp = (MVT::SimpleValueType)tp;
21716 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21720 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21721 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21722 (64 <= NumElems * ToSz))
21723 StoreType = MVT::f64;
21725 // Bitcast the original vector into a vector of store-size units
21726 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21727 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21728 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21729 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21730 SmallVector<SDValue, 8> Chains;
21731 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21732 TLI.getPointerTy());
21733 SDValue Ptr = St->getBasePtr();
21735 // Perform one or more big stores into memory.
21736 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21737 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21738 StoreType, ShuffWide,
21739 DAG.getIntPtrConstant(i));
21740 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21741 St->getPointerInfo(), St->isVolatile(),
21742 St->isNonTemporal(), St->getAlignment());
21743 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21744 Chains.push_back(Ch);
21747 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21750 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
21751 // the FP state in cases where an emms may be missing.
21752 // A preferable solution to the general problem is to figure out the right
21753 // places to insert EMMS. This qualifies as a quick hack.
21755 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21756 if (VT.getSizeInBits() != 64)
21759 const Function *F = DAG.getMachineFunction().getFunction();
21760 bool NoImplicitFloatOps = F->getAttributes().
21761 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21762 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21763 && Subtarget->hasSSE2();
21764 if ((VT.isVector() ||
21765 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21766 isa<LoadSDNode>(St->getValue()) &&
21767 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21768 St->getChain().hasOneUse() && !St->isVolatile()) {
21769 SDNode* LdVal = St->getValue().getNode();
21770 LoadSDNode *Ld = nullptr;
21771 int TokenFactorIndex = -1;
21772 SmallVector<SDValue, 8> Ops;
21773 SDNode* ChainVal = St->getChain().getNode();
21774 // Must be a store of a load. We currently handle two cases: the load
21775 // is a direct child, and it's under an intervening TokenFactor. It is
21776 // possible to dig deeper under nested TokenFactors.
21777 if (ChainVal == LdVal)
21778 Ld = cast<LoadSDNode>(St->getChain());
21779 else if (St->getValue().hasOneUse() &&
21780 ChainVal->getOpcode() == ISD::TokenFactor) {
21781 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21782 if (ChainVal->getOperand(i).getNode() == LdVal) {
21783 TokenFactorIndex = i;
21784 Ld = cast<LoadSDNode>(St->getValue());
21786 Ops.push_back(ChainVal->getOperand(i));
21790 if (!Ld || !ISD::isNormalLoad(Ld))
21793 // If this is not the MMX case, i.e. we are just turning i64 load/store
21794 // into f64 load/store, avoid the transformation if there are multiple
21795 // uses of the loaded value.
21796 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21801 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21802 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21804 if (Subtarget->is64Bit() || F64IsLegal) {
21805 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21806 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21807 Ld->getPointerInfo(), Ld->isVolatile(),
21808 Ld->isNonTemporal(), Ld->isInvariant(),
21809 Ld->getAlignment());
21810 SDValue NewChain = NewLd.getValue(1);
21811 if (TokenFactorIndex != -1) {
21812 Ops.push_back(NewChain);
21813 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21815 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21816 St->getPointerInfo(),
21817 St->isVolatile(), St->isNonTemporal(),
21818 St->getAlignment());
21821 // Otherwise, lower to two pairs of 32-bit loads / stores.
21822 SDValue LoAddr = Ld->getBasePtr();
21823 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21824 DAG.getConstant(4, MVT::i32));
21826 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21827 Ld->getPointerInfo(),
21828 Ld->isVolatile(), Ld->isNonTemporal(),
21829 Ld->isInvariant(), Ld->getAlignment());
21830 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21831 Ld->getPointerInfo().getWithOffset(4),
21832 Ld->isVolatile(), Ld->isNonTemporal(),
21834 MinAlign(Ld->getAlignment(), 4));
21836 SDValue NewChain = LoLd.getValue(1);
21837 if (TokenFactorIndex != -1) {
21838 Ops.push_back(LoLd);
21839 Ops.push_back(HiLd);
21840 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21843 LoAddr = St->getBasePtr();
21844 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21845 DAG.getConstant(4, MVT::i32));
21847 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21848 St->getPointerInfo(),
21849 St->isVolatile(), St->isNonTemporal(),
21850 St->getAlignment());
21851 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21852 St->getPointerInfo().getWithOffset(4),
21854 St->isNonTemporal(),
21855 MinAlign(St->getAlignment(), 4));
21856 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21861 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21862 /// and return the operands for the horizontal operation in LHS and RHS. A
21863 /// horizontal operation performs the binary operation on successive elements
21864 /// of its first operand, then on successive elements of its second operand,
21865 /// returning the resulting values in a vector. For example, if
21866 /// A = < float a0, float a1, float a2, float a3 >
21868 /// B = < float b0, float b1, float b2, float b3 >
21869 /// then the result of doing a horizontal operation on A and B is
21870 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21871 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21872 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21873 /// set to A, RHS to B, and the routine returns 'true'.
21874 /// Note that the binary operation should have the property that if one of the
21875 /// operands is UNDEF then the result is UNDEF.
21876 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21877 // Look for the following pattern: if
21878 // A = < float a0, float a1, float a2, float a3 >
21879 // B = < float b0, float b1, float b2, float b3 >
21881 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21882 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21883 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21884 // which is A horizontal-op B.
21886 // At least one of the operands should be a vector shuffle.
21887 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21888 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21891 MVT VT = LHS.getSimpleValueType();
21893 assert((VT.is128BitVector() || VT.is256BitVector()) &&
21894 "Unsupported vector type for horizontal add/sub");
21896 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21897 // operate independently on 128-bit lanes.
21898 unsigned NumElts = VT.getVectorNumElements();
21899 unsigned NumLanes = VT.getSizeInBits()/128;
21900 unsigned NumLaneElts = NumElts / NumLanes;
21901 assert((NumLaneElts % 2 == 0) &&
21902 "Vector type should have an even number of elements in each lane");
21903 unsigned HalfLaneElts = NumLaneElts/2;
21905 // View LHS in the form
21906 // LHS = VECTOR_SHUFFLE A, B, LMask
21907 // If LHS is not a shuffle then pretend it is the shuffle
21908 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21909 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21912 SmallVector<int, 16> LMask(NumElts);
21913 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21914 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21915 A = LHS.getOperand(0);
21916 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21917 B = LHS.getOperand(1);
21918 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21919 std::copy(Mask.begin(), Mask.end(), LMask.begin());
21921 if (LHS.getOpcode() != ISD::UNDEF)
21923 for (unsigned i = 0; i != NumElts; ++i)
21927 // Likewise, view RHS in the form
21928 // RHS = VECTOR_SHUFFLE C, D, RMask
21930 SmallVector<int, 16> RMask(NumElts);
21931 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21932 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21933 C = RHS.getOperand(0);
21934 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21935 D = RHS.getOperand(1);
21936 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21937 std::copy(Mask.begin(), Mask.end(), RMask.begin());
21939 if (RHS.getOpcode() != ISD::UNDEF)
21941 for (unsigned i = 0; i != NumElts; ++i)
21945 // Check that the shuffles are both shuffling the same vectors.
21946 if (!(A == C && B == D) && !(A == D && B == C))
21949 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21950 if (!A.getNode() && !B.getNode())
21953 // If A and B occur in reverse order in RHS, then "swap" them (which means
21954 // rewriting the mask).
21956 CommuteVectorShuffleMask(RMask, NumElts);
21958 // At this point LHS and RHS are equivalent to
21959 // LHS = VECTOR_SHUFFLE A, B, LMask
21960 // RHS = VECTOR_SHUFFLE A, B, RMask
21961 // Check that the masks correspond to performing a horizontal operation.
21962 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21963 for (unsigned i = 0; i != NumLaneElts; ++i) {
21964 int LIdx = LMask[i+l], RIdx = RMask[i+l];
21966 // Ignore any UNDEF components.
21967 if (LIdx < 0 || RIdx < 0 ||
21968 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21969 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21972 // Check that successive elements are being operated on. If not, this is
21973 // not a horizontal operation.
21974 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21975 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21976 if (!(LIdx == Index && RIdx == Index + 1) &&
21977 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21982 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21983 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21987 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21988 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21989 const X86Subtarget *Subtarget) {
21990 EVT VT = N->getValueType(0);
21991 SDValue LHS = N->getOperand(0);
21992 SDValue RHS = N->getOperand(1);
21994 // Try to synthesize horizontal adds from adds of shuffles.
21995 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21996 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21997 isHorizontalBinOp(LHS, RHS, true))
21998 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22002 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22003 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22004 const X86Subtarget *Subtarget) {
22005 EVT VT = N->getValueType(0);
22006 SDValue LHS = N->getOperand(0);
22007 SDValue RHS = N->getOperand(1);
22009 // Try to synthesize horizontal subs from subs of shuffles.
22010 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22011 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22012 isHorizontalBinOp(LHS, RHS, false))
22013 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22017 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22018 /// X86ISD::FXOR nodes.
22019 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22020 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22021 // F[X]OR(0.0, x) -> x
22022 // F[X]OR(x, 0.0) -> x
22023 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22024 if (C->getValueAPF().isPosZero())
22025 return N->getOperand(1);
22026 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22027 if (C->getValueAPF().isPosZero())
22028 return N->getOperand(0);
22032 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22033 /// X86ISD::FMAX nodes.
22034 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22035 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22037 // Only perform optimizations if UnsafeMath is used.
22038 if (!DAG.getTarget().Options.UnsafeFPMath)
22041 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22042 // into FMINC and FMAXC, which are Commutative operations.
22043 unsigned NewOp = 0;
22044 switch (N->getOpcode()) {
22045 default: llvm_unreachable("unknown opcode");
22046 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22047 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22050 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22051 N->getOperand(0), N->getOperand(1));
22054 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22055 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22056 // FAND(0.0, x) -> 0.0
22057 // FAND(x, 0.0) -> 0.0
22058 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22059 if (C->getValueAPF().isPosZero())
22060 return N->getOperand(0);
22061 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22062 if (C->getValueAPF().isPosZero())
22063 return N->getOperand(1);
22067 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22068 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22069 // FANDN(x, 0.0) -> 0.0
22070 // FANDN(0.0, x) -> x
22071 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22072 if (C->getValueAPF().isPosZero())
22073 return N->getOperand(1);
22074 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22075 if (C->getValueAPF().isPosZero())
22076 return N->getOperand(1);
22080 static SDValue PerformBTCombine(SDNode *N,
22082 TargetLowering::DAGCombinerInfo &DCI) {
22083 // BT ignores high bits in the bit index operand.
22084 SDValue Op1 = N->getOperand(1);
22085 if (Op1.hasOneUse()) {
22086 unsigned BitWidth = Op1.getValueSizeInBits();
22087 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22088 APInt KnownZero, KnownOne;
22089 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22090 !DCI.isBeforeLegalizeOps());
22091 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22092 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22093 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22094 DCI.CommitTargetLoweringOpt(TLO);
22099 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22100 SDValue Op = N->getOperand(0);
22101 if (Op.getOpcode() == ISD::BITCAST)
22102 Op = Op.getOperand(0);
22103 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22104 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22105 VT.getVectorElementType().getSizeInBits() ==
22106 OpVT.getVectorElementType().getSizeInBits()) {
22107 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22112 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22113 const X86Subtarget *Subtarget) {
22114 EVT VT = N->getValueType(0);
22115 if (!VT.isVector())
22118 SDValue N0 = N->getOperand(0);
22119 SDValue N1 = N->getOperand(1);
22120 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22123 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22124 // both SSE and AVX2 since there is no sign-extended shift right
22125 // operation on a vector with 64-bit elements.
22126 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22127 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22128 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22129 N0.getOpcode() == ISD::SIGN_EXTEND)) {
22130 SDValue N00 = N0.getOperand(0);
22132 // EXTLOAD has a better solution on AVX2,
22133 // it may be replaced with X86ISD::VSEXT node.
22134 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22135 if (!ISD::isNormalLoad(N00.getNode()))
22138 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22139 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22141 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22147 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22148 TargetLowering::DAGCombinerInfo &DCI,
22149 const X86Subtarget *Subtarget) {
22150 if (!DCI.isBeforeLegalizeOps())
22153 if (!Subtarget->hasFp256())
22156 EVT VT = N->getValueType(0);
22157 if (VT.isVector() && VT.getSizeInBits() == 256) {
22158 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22166 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22167 const X86Subtarget* Subtarget) {
22169 EVT VT = N->getValueType(0);
22171 // Let legalize expand this if it isn't a legal type yet.
22172 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22175 EVT ScalarVT = VT.getScalarType();
22176 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22177 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22180 SDValue A = N->getOperand(0);
22181 SDValue B = N->getOperand(1);
22182 SDValue C = N->getOperand(2);
22184 bool NegA = (A.getOpcode() == ISD::FNEG);
22185 bool NegB = (B.getOpcode() == ISD::FNEG);
22186 bool NegC = (C.getOpcode() == ISD::FNEG);
22188 // Negative multiplication when NegA xor NegB
22189 bool NegMul = (NegA != NegB);
22191 A = A.getOperand(0);
22193 B = B.getOperand(0);
22195 C = C.getOperand(0);
22199 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22201 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22203 return DAG.getNode(Opcode, dl, VT, A, B, C);
22206 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22207 TargetLowering::DAGCombinerInfo &DCI,
22208 const X86Subtarget *Subtarget) {
22209 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
22210 // (and (i32 x86isd::setcc_carry), 1)
22211 // This eliminates the zext. This transformation is necessary because
22212 // ISD::SETCC is always legalized to i8.
22214 SDValue N0 = N->getOperand(0);
22215 EVT VT = N->getValueType(0);
22217 if (N0.getOpcode() == ISD::AND &&
22219 N0.getOperand(0).hasOneUse()) {
22220 SDValue N00 = N0.getOperand(0);
22221 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22222 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22223 if (!C || C->getZExtValue() != 1)
22225 return DAG.getNode(ISD::AND, dl, VT,
22226 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22227 N00.getOperand(0), N00.getOperand(1)),
22228 DAG.getConstant(1, VT));
22232 if (N0.getOpcode() == ISD::TRUNCATE &&
22234 N0.getOperand(0).hasOneUse()) {
22235 SDValue N00 = N0.getOperand(0);
22236 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22237 return DAG.getNode(ISD::AND, dl, VT,
22238 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22239 N00.getOperand(0), N00.getOperand(1)),
22240 DAG.getConstant(1, VT));
22243 if (VT.is256BitVector()) {
22244 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22252 // Optimize x == -y --> x+y == 0
22253 // x != -y --> x+y != 0
22254 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22255 const X86Subtarget* Subtarget) {
22256 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22257 SDValue LHS = N->getOperand(0);
22258 SDValue RHS = N->getOperand(1);
22259 EVT VT = N->getValueType(0);
22262 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22263 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22264 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22265 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22266 LHS.getValueType(), RHS, LHS.getOperand(1));
22267 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22268 addV, DAG.getConstant(0, addV.getValueType()), CC);
22270 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22271 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22272 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22273 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22274 RHS.getValueType(), LHS, RHS.getOperand(1));
22275 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22276 addV, DAG.getConstant(0, addV.getValueType()), CC);
22279 if (VT.getScalarType() == MVT::i1) {
22280 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22281 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22282 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22283 if (!IsSEXT0 && !IsVZero0)
22285 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22286 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22287 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22289 if (!IsSEXT1 && !IsVZero1)
22292 if (IsSEXT0 && IsVZero1) {
22293 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22294 if (CC == ISD::SETEQ)
22295 return DAG.getNOT(DL, LHS.getOperand(0), VT);
22296 return LHS.getOperand(0);
22298 if (IsSEXT1 && IsVZero0) {
22299 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22300 if (CC == ISD::SETEQ)
22301 return DAG.getNOT(DL, RHS.getOperand(0), VT);
22302 return RHS.getOperand(0);
22309 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22310 const X86Subtarget *Subtarget) {
22312 MVT VT = N->getOperand(1)->getSimpleValueType(0);
22313 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22314 "X86insertps is only defined for v4x32");
22316 SDValue Ld = N->getOperand(1);
22317 if (MayFoldLoad(Ld)) {
22318 // Extract the countS bits from the immediate so we can get the proper
22319 // address when narrowing the vector load to a specific element.
22320 // When the second source op is a memory address, interps doesn't use
22321 // countS and just gets an f32 from that address.
22322 unsigned DestIndex =
22323 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22324 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22328 // Create this as a scalar to vector to match the instruction pattern.
22329 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22330 // countS bits are ignored when loading from memory on insertps, which
22331 // means we don't need to explicitly set them to 0.
22332 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22333 LoadScalarToVector, N->getOperand(2));
22336 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22337 // as "sbb reg,reg", since it can be extended without zext and produces
22338 // an all-ones bit which is more useful than 0/1 in some cases.
22339 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22342 return DAG.getNode(ISD::AND, DL, VT,
22343 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22344 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22345 DAG.getConstant(1, VT));
22346 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22347 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22348 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22349 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22352 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22353 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22354 TargetLowering::DAGCombinerInfo &DCI,
22355 const X86Subtarget *Subtarget) {
22357 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22358 SDValue EFLAGS = N->getOperand(1);
22360 if (CC == X86::COND_A) {
22361 // Try to convert COND_A into COND_B in an attempt to facilitate
22362 // materializing "setb reg".
22364 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22365 // cannot take an immediate as its first operand.
22367 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22368 EFLAGS.getValueType().isInteger() &&
22369 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22370 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22371 EFLAGS.getNode()->getVTList(),
22372 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22373 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22374 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22378 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22379 // a zext and produces an all-ones bit which is more useful than 0/1 in some
22381 if (CC == X86::COND_B)
22382 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22386 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22387 if (Flags.getNode()) {
22388 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22389 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22395 // Optimize branch condition evaluation.
22397 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22398 TargetLowering::DAGCombinerInfo &DCI,
22399 const X86Subtarget *Subtarget) {
22401 SDValue Chain = N->getOperand(0);
22402 SDValue Dest = N->getOperand(1);
22403 SDValue EFLAGS = N->getOperand(3);
22404 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22408 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22409 if (Flags.getNode()) {
22410 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22411 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22418 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22419 SelectionDAG &DAG) {
22420 // Take advantage of vector comparisons producing 0 or -1 in each lane to
22421 // optimize away operation when it's from a constant.
22423 // The general transformation is:
22424 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22425 // AND(VECTOR_CMP(x,y), constant2)
22426 // constant2 = UNARYOP(constant)
22428 // Early exit if this isn't a vector operation, the operand of the
22429 // unary operation isn't a bitwise AND, or if the sizes of the operations
22430 // aren't the same.
22431 EVT VT = N->getValueType(0);
22432 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22433 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22434 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22437 // Now check that the other operand of the AND is a constant. We could
22438 // make the transformation for non-constant splats as well, but it's unclear
22439 // that would be a benefit as it would not eliminate any operations, just
22440 // perform one more step in scalar code before moving to the vector unit.
22441 if (BuildVectorSDNode *BV =
22442 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22443 // Bail out if the vector isn't a constant.
22444 if (!BV->isConstant())
22447 // Everything checks out. Build up the new and improved node.
22449 EVT IntVT = BV->getValueType(0);
22450 // Create a new constant of the appropriate type for the transformed
22452 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22453 // The AND node needs bitcasts to/from an integer vector type around it.
22454 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22455 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22456 N->getOperand(0)->getOperand(0), MaskConst);
22457 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22464 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22465 const X86TargetLowering *XTLI) {
22466 // First try to optimize away the conversion entirely when it's
22467 // conditionally from a constant. Vectors only.
22468 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22469 if (Res != SDValue())
22472 // Now move on to more general possibilities.
22473 SDValue Op0 = N->getOperand(0);
22474 EVT InVT = Op0->getValueType(0);
22476 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22477 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22479 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22480 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22481 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22484 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22485 // a 32-bit target where SSE doesn't support i64->FP operations.
22486 if (Op0.getOpcode() == ISD::LOAD) {
22487 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22488 EVT VT = Ld->getValueType(0);
22489 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22490 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22491 !XTLI->getSubtarget()->is64Bit() &&
22493 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22494 Ld->getChain(), Op0, DAG);
22495 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22502 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22503 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22504 X86TargetLowering::DAGCombinerInfo &DCI) {
22505 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22506 // the result is either zero or one (depending on the input carry bit).
22507 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22508 if (X86::isZeroNode(N->getOperand(0)) &&
22509 X86::isZeroNode(N->getOperand(1)) &&
22510 // We don't have a good way to replace an EFLAGS use, so only do this when
22512 SDValue(N, 1).use_empty()) {
22514 EVT VT = N->getValueType(0);
22515 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22516 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22517 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22518 DAG.getConstant(X86::COND_B,MVT::i8),
22520 DAG.getConstant(1, VT));
22521 return DCI.CombineTo(N, Res1, CarryOut);
22527 // fold (add Y, (sete X, 0)) -> adc 0, Y
22528 // (add Y, (setne X, 0)) -> sbb -1, Y
22529 // (sub (sete X, 0), Y) -> sbb 0, Y
22530 // (sub (setne X, 0), Y) -> adc -1, Y
22531 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22534 // Look through ZExts.
22535 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22536 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22539 SDValue SetCC = Ext.getOperand(0);
22540 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22543 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22544 if (CC != X86::COND_E && CC != X86::COND_NE)
22547 SDValue Cmp = SetCC.getOperand(1);
22548 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22549 !X86::isZeroNode(Cmp.getOperand(1)) ||
22550 !Cmp.getOperand(0).getValueType().isInteger())
22553 SDValue CmpOp0 = Cmp.getOperand(0);
22554 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22555 DAG.getConstant(1, CmpOp0.getValueType()));
22557 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22558 if (CC == X86::COND_NE)
22559 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22560 DL, OtherVal.getValueType(), OtherVal,
22561 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22562 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22563 DL, OtherVal.getValueType(), OtherVal,
22564 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22567 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22568 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22569 const X86Subtarget *Subtarget) {
22570 EVT VT = N->getValueType(0);
22571 SDValue Op0 = N->getOperand(0);
22572 SDValue Op1 = N->getOperand(1);
22574 // Try to synthesize horizontal adds from adds of shuffles.
22575 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22576 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22577 isHorizontalBinOp(Op0, Op1, true))
22578 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22580 return OptimizeConditionalInDecrement(N, DAG);
22583 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22584 const X86Subtarget *Subtarget) {
22585 SDValue Op0 = N->getOperand(0);
22586 SDValue Op1 = N->getOperand(1);
22588 // X86 can't encode an immediate LHS of a sub. See if we can push the
22589 // negation into a preceding instruction.
22590 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22591 // If the RHS of the sub is a XOR with one use and a constant, invert the
22592 // immediate. Then add one to the LHS of the sub so we can turn
22593 // X-Y -> X+~Y+1, saving one register.
22594 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22595 isa<ConstantSDNode>(Op1.getOperand(1))) {
22596 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22597 EVT VT = Op0.getValueType();
22598 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22600 DAG.getConstant(~XorC, VT));
22601 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22602 DAG.getConstant(C->getAPIntValue()+1, VT));
22606 // Try to synthesize horizontal adds from adds of shuffles.
22607 EVT VT = N->getValueType(0);
22608 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22609 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22610 isHorizontalBinOp(Op0, Op1, true))
22611 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22613 return OptimizeConditionalInDecrement(N, DAG);
22616 /// performVZEXTCombine - Performs build vector combines
22617 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22618 TargetLowering::DAGCombinerInfo &DCI,
22619 const X86Subtarget *Subtarget) {
22620 // (vzext (bitcast (vzext (x)) -> (vzext x)
22621 SDValue In = N->getOperand(0);
22622 while (In.getOpcode() == ISD::BITCAST)
22623 In = In.getOperand(0);
22625 if (In.getOpcode() != X86ISD::VZEXT)
22628 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22632 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22633 DAGCombinerInfo &DCI) const {
22634 SelectionDAG &DAG = DCI.DAG;
22635 switch (N->getOpcode()) {
22637 case ISD::EXTRACT_VECTOR_ELT:
22638 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22640 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22641 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22642 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
22643 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
22644 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
22645 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
22648 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
22649 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
22650 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
22651 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
22652 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
22653 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
22654 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
22655 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
22656 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
22658 case X86ISD::FOR: return PerformFORCombine(N, DAG);
22660 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
22661 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
22662 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
22663 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
22664 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
22665 case ISD::ANY_EXTEND:
22666 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
22667 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
22668 case ISD::SIGN_EXTEND_INREG:
22669 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22670 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22671 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
22672 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22673 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22674 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
22675 case X86ISD::SHUFP: // Handle all target specific shuffles
22676 case X86ISD::PALIGNR:
22677 case X86ISD::UNPCKH:
22678 case X86ISD::UNPCKL:
22679 case X86ISD::MOVHLPS:
22680 case X86ISD::MOVLHPS:
22681 case X86ISD::PSHUFB:
22682 case X86ISD::PSHUFD:
22683 case X86ISD::PSHUFHW:
22684 case X86ISD::PSHUFLW:
22685 case X86ISD::MOVSS:
22686 case X86ISD::MOVSD:
22687 case X86ISD::VPERMILP:
22688 case X86ISD::VPERM2X128:
22689 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22690 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
22691 case ISD::INTRINSIC_WO_CHAIN:
22692 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22693 case X86ISD::INSERTPS:
22694 return PerformINSERTPSCombine(N, DAG, Subtarget);
22695 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22701 /// isTypeDesirableForOp - Return true if the target has native support for
22702 /// the specified value type and it is 'desirable' to use the type for the
22703 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22704 /// instruction encodings are longer and some i16 instructions are slow.
22705 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22706 if (!isTypeLegal(VT))
22708 if (VT != MVT::i16)
22715 case ISD::SIGN_EXTEND:
22716 case ISD::ZERO_EXTEND:
22717 case ISD::ANY_EXTEND:
22730 /// IsDesirableToPromoteOp - This method query the target whether it is
22731 /// beneficial for dag combiner to promote the specified node. If true, it
22732 /// should return the desired promotion type by reference.
22733 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22734 EVT VT = Op.getValueType();
22735 if (VT != MVT::i16)
22738 bool Promote = false;
22739 bool Commute = false;
22740 switch (Op.getOpcode()) {
22743 LoadSDNode *LD = cast<LoadSDNode>(Op);
22744 // If the non-extending load has a single use and it's not live out, then it
22745 // might be folded.
22746 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22747 Op.hasOneUse()*/) {
22748 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22749 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22750 // The only case where we'd want to promote LOAD (rather then it being
22751 // promoted as an operand is when it's only use is liveout.
22752 if (UI->getOpcode() != ISD::CopyToReg)
22759 case ISD::SIGN_EXTEND:
22760 case ISD::ZERO_EXTEND:
22761 case ISD::ANY_EXTEND:
22766 SDValue N0 = Op.getOperand(0);
22767 // Look out for (store (shl (load), x)).
22768 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22781 SDValue N0 = Op.getOperand(0);
22782 SDValue N1 = Op.getOperand(1);
22783 if (!Commute && MayFoldLoad(N1))
22785 // Avoid disabling potential load folding opportunities.
22786 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22788 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22798 //===----------------------------------------------------------------------===//
22799 // X86 Inline Assembly Support
22800 //===----------------------------------------------------------------------===//
22803 // Helper to match a string separated by whitespace.
22804 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22805 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22807 for (unsigned i = 0, e = args.size(); i != e; ++i) {
22808 StringRef piece(*args[i]);
22809 if (!s.startswith(piece)) // Check if the piece matches.
22812 s = s.substr(piece.size());
22813 StringRef::size_type pos = s.find_first_not_of(" \t");
22814 if (pos == 0) // We matched a prefix.
22822 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22825 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22827 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22828 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22829 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22830 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22832 if (AsmPieces.size() == 3)
22834 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22841 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22842 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22844 std::string AsmStr = IA->getAsmString();
22846 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22847 if (!Ty || Ty->getBitWidth() % 16 != 0)
22850 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22851 SmallVector<StringRef, 4> AsmPieces;
22852 SplitString(AsmStr, AsmPieces, ";\n");
22854 switch (AsmPieces.size()) {
22855 default: return false;
22857 // FIXME: this should verify that we are targeting a 486 or better. If not,
22858 // we will turn this bswap into something that will be lowered to logical
22859 // ops instead of emitting the bswap asm. For now, we don't support 486 or
22860 // lower so don't worry about this.
22862 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22863 matchAsm(AsmPieces[0], "bswapl", "$0") ||
22864 matchAsm(AsmPieces[0], "bswapq", "$0") ||
22865 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22866 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22867 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22868 // No need to check constraints, nothing other than the equivalent of
22869 // "=r,0" would be valid here.
22870 return IntrinsicLowering::LowerToByteSwap(CI);
22873 // rorw $$8, ${0:w} --> llvm.bswap.i16
22874 if (CI->getType()->isIntegerTy(16) &&
22875 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22876 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22877 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22879 const std::string &ConstraintsStr = IA->getConstraintString();
22880 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22881 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22882 if (clobbersFlagRegisters(AsmPieces))
22883 return IntrinsicLowering::LowerToByteSwap(CI);
22887 if (CI->getType()->isIntegerTy(32) &&
22888 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22889 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22890 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22891 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22893 const std::string &ConstraintsStr = IA->getConstraintString();
22894 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22895 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22896 if (clobbersFlagRegisters(AsmPieces))
22897 return IntrinsicLowering::LowerToByteSwap(CI);
22900 if (CI->getType()->isIntegerTy(64)) {
22901 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22902 if (Constraints.size() >= 2 &&
22903 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22904 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22905 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
22906 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22907 matchAsm(AsmPieces[1], "bswap", "%edx") &&
22908 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22909 return IntrinsicLowering::LowerToByteSwap(CI);
22917 /// getConstraintType - Given a constraint letter, return the type of
22918 /// constraint it is for this target.
22919 X86TargetLowering::ConstraintType
22920 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22921 if (Constraint.size() == 1) {
22922 switch (Constraint[0]) {
22933 return C_RegisterClass;
22957 return TargetLowering::getConstraintType(Constraint);
22960 /// Examine constraint type and operand type and determine a weight value.
22961 /// This object must already have been set up with the operand type
22962 /// and the current alternative constraint selected.
22963 TargetLowering::ConstraintWeight
22964 X86TargetLowering::getSingleConstraintMatchWeight(
22965 AsmOperandInfo &info, const char *constraint) const {
22966 ConstraintWeight weight = CW_Invalid;
22967 Value *CallOperandVal = info.CallOperandVal;
22968 // If we don't have a value, we can't do a match,
22969 // but allow it at the lowest weight.
22970 if (!CallOperandVal)
22972 Type *type = CallOperandVal->getType();
22973 // Look at the constraint type.
22974 switch (*constraint) {
22976 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22987 if (CallOperandVal->getType()->isIntegerTy())
22988 weight = CW_SpecificReg;
22993 if (type->isFloatingPointTy())
22994 weight = CW_SpecificReg;
22997 if (type->isX86_MMXTy() && Subtarget->hasMMX())
22998 weight = CW_SpecificReg;
23002 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23003 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23004 weight = CW_Register;
23007 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23008 if (C->getZExtValue() <= 31)
23009 weight = CW_Constant;
23013 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23014 if (C->getZExtValue() <= 63)
23015 weight = CW_Constant;
23019 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23020 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23021 weight = CW_Constant;
23025 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23026 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23027 weight = CW_Constant;
23031 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23032 if (C->getZExtValue() <= 3)
23033 weight = CW_Constant;
23037 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23038 if (C->getZExtValue() <= 0xff)
23039 weight = CW_Constant;
23044 if (dyn_cast<ConstantFP>(CallOperandVal)) {
23045 weight = CW_Constant;
23049 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23050 if ((C->getSExtValue() >= -0x80000000LL) &&
23051 (C->getSExtValue() <= 0x7fffffffLL))
23052 weight = CW_Constant;
23056 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23057 if (C->getZExtValue() <= 0xffffffff)
23058 weight = CW_Constant;
23065 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23066 /// with another that has more specific requirements based on the type of the
23067 /// corresponding operand.
23068 const char *X86TargetLowering::
23069 LowerXConstraint(EVT ConstraintVT) const {
23070 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23071 // 'f' like normal targets.
23072 if (ConstraintVT.isFloatingPoint()) {
23073 if (Subtarget->hasSSE2())
23075 if (Subtarget->hasSSE1())
23079 return TargetLowering::LowerXConstraint(ConstraintVT);
23082 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23083 /// vector. If it is invalid, don't add anything to Ops.
23084 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23085 std::string &Constraint,
23086 std::vector<SDValue>&Ops,
23087 SelectionDAG &DAG) const {
23090 // Only support length 1 constraints for now.
23091 if (Constraint.length() > 1) return;
23093 char ConstraintLetter = Constraint[0];
23094 switch (ConstraintLetter) {
23097 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23098 if (C->getZExtValue() <= 31) {
23099 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23105 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23106 if (C->getZExtValue() <= 63) {
23107 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23113 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23114 if (isInt<8>(C->getSExtValue())) {
23115 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23121 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23122 if (C->getZExtValue() <= 255) {
23123 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23129 // 32-bit signed value
23130 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23131 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23132 C->getSExtValue())) {
23133 // Widen to 64 bits here to get it sign extended.
23134 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23137 // FIXME gcc accepts some relocatable values here too, but only in certain
23138 // memory models; it's complicated.
23143 // 32-bit unsigned value
23144 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23145 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23146 C->getZExtValue())) {
23147 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23151 // FIXME gcc accepts some relocatable values here too, but only in certain
23152 // memory models; it's complicated.
23156 // Literal immediates are always ok.
23157 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23158 // Widen to 64 bits here to get it sign extended.
23159 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23163 // In any sort of PIC mode addresses need to be computed at runtime by
23164 // adding in a register or some sort of table lookup. These can't
23165 // be used as immediates.
23166 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23169 // If we are in non-pic codegen mode, we allow the address of a global (with
23170 // an optional displacement) to be used with 'i'.
23171 GlobalAddressSDNode *GA = nullptr;
23172 int64_t Offset = 0;
23174 // Match either (GA), (GA+C), (GA+C1+C2), etc.
23176 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23177 Offset += GA->getOffset();
23179 } else if (Op.getOpcode() == ISD::ADD) {
23180 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23181 Offset += C->getZExtValue();
23182 Op = Op.getOperand(0);
23185 } else if (Op.getOpcode() == ISD::SUB) {
23186 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23187 Offset += -C->getZExtValue();
23188 Op = Op.getOperand(0);
23193 // Otherwise, this isn't something we can handle, reject it.
23197 const GlobalValue *GV = GA->getGlobal();
23198 // If we require an extra load to get this address, as in PIC mode, we
23199 // can't accept it.
23200 if (isGlobalStubReference(
23201 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23204 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23205 GA->getValueType(0), Offset);
23210 if (Result.getNode()) {
23211 Ops.push_back(Result);
23214 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23217 std::pair<unsigned, const TargetRegisterClass*>
23218 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23220 // First, see if this is a constraint that directly corresponds to an LLVM
23222 if (Constraint.size() == 1) {
23223 // GCC Constraint Letters
23224 switch (Constraint[0]) {
23226 // TODO: Slight differences here in allocation order and leaving
23227 // RIP in the class. Do they matter any more here than they do
23228 // in the normal allocation?
23229 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23230 if (Subtarget->is64Bit()) {
23231 if (VT == MVT::i32 || VT == MVT::f32)
23232 return std::make_pair(0U, &X86::GR32RegClass);
23233 if (VT == MVT::i16)
23234 return std::make_pair(0U, &X86::GR16RegClass);
23235 if (VT == MVT::i8 || VT == MVT::i1)
23236 return std::make_pair(0U, &X86::GR8RegClass);
23237 if (VT == MVT::i64 || VT == MVT::f64)
23238 return std::make_pair(0U, &X86::GR64RegClass);
23241 // 32-bit fallthrough
23242 case 'Q': // Q_REGS
23243 if (VT == MVT::i32 || VT == MVT::f32)
23244 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23245 if (VT == MVT::i16)
23246 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23247 if (VT == MVT::i8 || VT == MVT::i1)
23248 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23249 if (VT == MVT::i64)
23250 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23252 case 'r': // GENERAL_REGS
23253 case 'l': // INDEX_REGS
23254 if (VT == MVT::i8 || VT == MVT::i1)
23255 return std::make_pair(0U, &X86::GR8RegClass);
23256 if (VT == MVT::i16)
23257 return std::make_pair(0U, &X86::GR16RegClass);
23258 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23259 return std::make_pair(0U, &X86::GR32RegClass);
23260 return std::make_pair(0U, &X86::GR64RegClass);
23261 case 'R': // LEGACY_REGS
23262 if (VT == MVT::i8 || VT == MVT::i1)
23263 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23264 if (VT == MVT::i16)
23265 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23266 if (VT == MVT::i32 || !Subtarget->is64Bit())
23267 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23268 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23269 case 'f': // FP Stack registers.
23270 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23271 // value to the correct fpstack register class.
23272 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23273 return std::make_pair(0U, &X86::RFP32RegClass);
23274 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23275 return std::make_pair(0U, &X86::RFP64RegClass);
23276 return std::make_pair(0U, &X86::RFP80RegClass);
23277 case 'y': // MMX_REGS if MMX allowed.
23278 if (!Subtarget->hasMMX()) break;
23279 return std::make_pair(0U, &X86::VR64RegClass);
23280 case 'Y': // SSE_REGS if SSE2 allowed
23281 if (!Subtarget->hasSSE2()) break;
23283 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23284 if (!Subtarget->hasSSE1()) break;
23286 switch (VT.SimpleTy) {
23288 // Scalar SSE types.
23291 return std::make_pair(0U, &X86::FR32RegClass);
23294 return std::make_pair(0U, &X86::FR64RegClass);
23302 return std::make_pair(0U, &X86::VR128RegClass);
23310 return std::make_pair(0U, &X86::VR256RegClass);
23315 return std::make_pair(0U, &X86::VR512RegClass);
23321 // Use the default implementation in TargetLowering to convert the register
23322 // constraint into a member of a register class.
23323 std::pair<unsigned, const TargetRegisterClass*> Res;
23324 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23326 // Not found as a standard register?
23328 // Map st(0) -> st(7) -> ST0
23329 if (Constraint.size() == 7 && Constraint[0] == '{' &&
23330 tolower(Constraint[1]) == 's' &&
23331 tolower(Constraint[2]) == 't' &&
23332 Constraint[3] == '(' &&
23333 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23334 Constraint[5] == ')' &&
23335 Constraint[6] == '}') {
23337 Res.first = X86::FP0+Constraint[4]-'0';
23338 Res.second = &X86::RFP80RegClass;
23342 // GCC allows "st(0)" to be called just plain "st".
23343 if (StringRef("{st}").equals_lower(Constraint)) {
23344 Res.first = X86::FP0;
23345 Res.second = &X86::RFP80RegClass;
23350 if (StringRef("{flags}").equals_lower(Constraint)) {
23351 Res.first = X86::EFLAGS;
23352 Res.second = &X86::CCRRegClass;
23356 // 'A' means EAX + EDX.
23357 if (Constraint == "A") {
23358 Res.first = X86::EAX;
23359 Res.second = &X86::GR32_ADRegClass;
23365 // Otherwise, check to see if this is a register class of the wrong value
23366 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23367 // turn into {ax},{dx}.
23368 if (Res.second->hasType(VT))
23369 return Res; // Correct type already, nothing to do.
23371 // All of the single-register GCC register classes map their values onto
23372 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
23373 // really want an 8-bit or 32-bit register, map to the appropriate register
23374 // class and return the appropriate register.
23375 if (Res.second == &X86::GR16RegClass) {
23376 if (VT == MVT::i8 || VT == MVT::i1) {
23377 unsigned DestReg = 0;
23378 switch (Res.first) {
23380 case X86::AX: DestReg = X86::AL; break;
23381 case X86::DX: DestReg = X86::DL; break;
23382 case X86::CX: DestReg = X86::CL; break;
23383 case X86::BX: DestReg = X86::BL; break;
23386 Res.first = DestReg;
23387 Res.second = &X86::GR8RegClass;
23389 } else if (VT == MVT::i32 || VT == MVT::f32) {
23390 unsigned DestReg = 0;
23391 switch (Res.first) {
23393 case X86::AX: DestReg = X86::EAX; break;
23394 case X86::DX: DestReg = X86::EDX; break;
23395 case X86::CX: DestReg = X86::ECX; break;
23396 case X86::BX: DestReg = X86::EBX; break;
23397 case X86::SI: DestReg = X86::ESI; break;
23398 case X86::DI: DestReg = X86::EDI; break;
23399 case X86::BP: DestReg = X86::EBP; break;
23400 case X86::SP: DestReg = X86::ESP; break;
23403 Res.first = DestReg;
23404 Res.second = &X86::GR32RegClass;
23406 } else if (VT == MVT::i64 || VT == MVT::f64) {
23407 unsigned DestReg = 0;
23408 switch (Res.first) {
23410 case X86::AX: DestReg = X86::RAX; break;
23411 case X86::DX: DestReg = X86::RDX; break;
23412 case X86::CX: DestReg = X86::RCX; break;
23413 case X86::BX: DestReg = X86::RBX; break;
23414 case X86::SI: DestReg = X86::RSI; break;
23415 case X86::DI: DestReg = X86::RDI; break;
23416 case X86::BP: DestReg = X86::RBP; break;
23417 case X86::SP: DestReg = X86::RSP; break;
23420 Res.first = DestReg;
23421 Res.second = &X86::GR64RegClass;
23424 } else if (Res.second == &X86::FR32RegClass ||
23425 Res.second == &X86::FR64RegClass ||
23426 Res.second == &X86::VR128RegClass ||
23427 Res.second == &X86::VR256RegClass ||
23428 Res.second == &X86::FR32XRegClass ||
23429 Res.second == &X86::FR64XRegClass ||
23430 Res.second == &X86::VR128XRegClass ||
23431 Res.second == &X86::VR256XRegClass ||
23432 Res.second == &X86::VR512RegClass) {
23433 // Handle references to XMM physical registers that got mapped into the
23434 // wrong class. This can happen with constraints like {xmm0} where the
23435 // target independent register mapper will just pick the first match it can
23436 // find, ignoring the required type.
23438 if (VT == MVT::f32 || VT == MVT::i32)
23439 Res.second = &X86::FR32RegClass;
23440 else if (VT == MVT::f64 || VT == MVT::i64)
23441 Res.second = &X86::FR64RegClass;
23442 else if (X86::VR128RegClass.hasType(VT))
23443 Res.second = &X86::VR128RegClass;
23444 else if (X86::VR256RegClass.hasType(VT))
23445 Res.second = &X86::VR256RegClass;
23446 else if (X86::VR512RegClass.hasType(VT))
23447 Res.second = &X86::VR512RegClass;
23453 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23455 // Scaling factors are not free at all.
23456 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23457 // will take 2 allocations in the out of order engine instead of 1
23458 // for plain addressing mode, i.e. inst (reg1).
23460 // vaddps (%rsi,%drx), %ymm0, %ymm1
23461 // Requires two allocations (one for the load, one for the computation)
23463 // vaddps (%rsi), %ymm0, %ymm1
23464 // Requires just 1 allocation, i.e., freeing allocations for other operations
23465 // and having less micro operations to execute.
23467 // For some X86 architectures, this is even worse because for instance for
23468 // stores, the complex addressing mode forces the instruction to use the
23469 // "load" ports instead of the dedicated "store" port.
23470 // E.g., on Haswell:
23471 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23472 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
23473 if (isLegalAddressingMode(AM, Ty))
23474 // Scale represents reg2 * scale, thus account for 1
23475 // as soon as we use a second register.
23476 return AM.Scale != 0;
23480 bool X86TargetLowering::isTargetFTOL() const {
23481 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();