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 static_cast<const X86RegisterInfo*>(TM.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 if (Subtarget->hasPOPCNT()) {
519 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
521 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
522 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
523 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
524 if (Subtarget->is64Bit())
525 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
528 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
530 if (!Subtarget->hasMOVBE())
531 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
533 // These should be promoted to a larger select which is supported.
534 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
535 // X86 wants to expand cmov itself.
536 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
537 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
538 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
539 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
540 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
541 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
542 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
543 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
544 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
545 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
546 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
547 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
548 if (Subtarget->is64Bit()) {
549 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
550 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
552 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
553 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
554 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
555 // support continuation, user-level threading, and etc.. As a result, no
556 // other SjLj exception interfaces are implemented and please don't build
557 // your own exception handling based on them.
558 // LLVM/Clang supports zero-cost DWARF exception handling.
559 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
560 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
563 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
564 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
565 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
566 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
567 if (Subtarget->is64Bit())
568 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
569 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
570 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
571 if (Subtarget->is64Bit()) {
572 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
573 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
574 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
575 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
576 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
578 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
579 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
580 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
581 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
582 if (Subtarget->is64Bit()) {
583 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
584 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
585 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
588 if (Subtarget->hasSSE1())
589 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
591 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
593 // Expand certain atomics
594 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
596 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
597 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
598 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
601 if (Subtarget->hasCmpxchg16b()) {
602 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
605 // FIXME - use subtarget debug flags
606 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
607 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
608 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
611 if (Subtarget->is64Bit()) {
612 setExceptionPointerRegister(X86::RAX);
613 setExceptionSelectorRegister(X86::RDX);
615 setExceptionPointerRegister(X86::EAX);
616 setExceptionSelectorRegister(X86::EDX);
618 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
619 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
621 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
622 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
624 setOperationAction(ISD::TRAP, MVT::Other, Legal);
625 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
627 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
628 setOperationAction(ISD::VASTART , MVT::Other, Custom);
629 setOperationAction(ISD::VAEND , MVT::Other, Expand);
630 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
631 // TargetInfo::X86_64ABIBuiltinVaList
632 setOperationAction(ISD::VAARG , MVT::Other, Custom);
633 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
635 // TargetInfo::CharPtrBuiltinVaList
636 setOperationAction(ISD::VAARG , MVT::Other, Expand);
637 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
640 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
641 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
643 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
644 MVT::i64 : MVT::i32, Custom);
646 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
647 // f32 and f64 use SSE.
648 // Set up the FP register classes.
649 addRegisterClass(MVT::f32, &X86::FR32RegClass);
650 addRegisterClass(MVT::f64, &X86::FR64RegClass);
652 // Use ANDPD to simulate FABS.
653 setOperationAction(ISD::FABS , MVT::f64, Custom);
654 setOperationAction(ISD::FABS , MVT::f32, Custom);
656 // Use XORP to simulate FNEG.
657 setOperationAction(ISD::FNEG , MVT::f64, Custom);
658 setOperationAction(ISD::FNEG , MVT::f32, Custom);
660 // Use ANDPD and ORPD to simulate FCOPYSIGN.
661 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
662 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
664 // Lower this to FGETSIGNx86 plus an AND.
665 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
666 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
668 // We don't support sin/cos/fmod
669 setOperationAction(ISD::FSIN , MVT::f64, Expand);
670 setOperationAction(ISD::FCOS , MVT::f64, Expand);
671 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
672 setOperationAction(ISD::FSIN , MVT::f32, Expand);
673 setOperationAction(ISD::FCOS , MVT::f32, Expand);
674 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
676 // Expand FP immediates into loads from the stack, except for the special
678 addLegalFPImmediate(APFloat(+0.0)); // xorpd
679 addLegalFPImmediate(APFloat(+0.0f)); // xorps
680 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
681 // Use SSE for f32, x87 for f64.
682 // Set up the FP register classes.
683 addRegisterClass(MVT::f32, &X86::FR32RegClass);
684 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
686 // Use ANDPS to simulate FABS.
687 setOperationAction(ISD::FABS , MVT::f32, Custom);
689 // Use XORP to simulate FNEG.
690 setOperationAction(ISD::FNEG , MVT::f32, Custom);
692 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
694 // Use ANDPS and ORPS to simulate FCOPYSIGN.
695 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
696 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
698 // We don't support sin/cos/fmod
699 setOperationAction(ISD::FSIN , MVT::f32, Expand);
700 setOperationAction(ISD::FCOS , MVT::f32, Expand);
701 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
703 // Special cases we handle for FP constants.
704 addLegalFPImmediate(APFloat(+0.0f)); // xorps
705 addLegalFPImmediate(APFloat(+0.0)); // FLD0
706 addLegalFPImmediate(APFloat(+1.0)); // FLD1
707 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
708 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
710 if (!TM.Options.UnsafeFPMath) {
711 setOperationAction(ISD::FSIN , MVT::f64, Expand);
712 setOperationAction(ISD::FCOS , MVT::f64, Expand);
713 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
715 } else if (!TM.Options.UseSoftFloat) {
716 // f32 and f64 in x87.
717 // Set up the FP register classes.
718 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
719 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
721 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
722 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
723 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
724 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
726 if (!TM.Options.UnsafeFPMath) {
727 setOperationAction(ISD::FSIN , MVT::f64, Expand);
728 setOperationAction(ISD::FSIN , MVT::f32, Expand);
729 setOperationAction(ISD::FCOS , MVT::f64, Expand);
730 setOperationAction(ISD::FCOS , MVT::f32, Expand);
731 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
732 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
734 addLegalFPImmediate(APFloat(+0.0)); // FLD0
735 addLegalFPImmediate(APFloat(+1.0)); // FLD1
736 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
737 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
738 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
739 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
740 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
741 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
744 // We don't support FMA.
745 setOperationAction(ISD::FMA, MVT::f64, Expand);
746 setOperationAction(ISD::FMA, MVT::f32, Expand);
748 // Long double always uses X87.
749 if (!TM.Options.UseSoftFloat) {
750 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
751 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
752 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
754 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
755 addLegalFPImmediate(TmpFlt); // FLD0
757 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
760 APFloat TmpFlt2(+1.0);
761 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
763 addLegalFPImmediate(TmpFlt2); // FLD1
764 TmpFlt2.changeSign();
765 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
768 if (!TM.Options.UnsafeFPMath) {
769 setOperationAction(ISD::FSIN , MVT::f80, Expand);
770 setOperationAction(ISD::FCOS , MVT::f80, Expand);
771 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
774 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
775 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
776 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
777 setOperationAction(ISD::FRINT, MVT::f80, Expand);
778 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
779 setOperationAction(ISD::FMA, MVT::f80, Expand);
782 // Always use a library call for pow.
783 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
784 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
785 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
787 setOperationAction(ISD::FLOG, MVT::f80, Expand);
788 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
789 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
790 setOperationAction(ISD::FEXP, MVT::f80, Expand);
791 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
793 // First set operation action for all vector types to either promote
794 // (for widening) or expand (for scalarization). Then we will selectively
795 // turn on ones that can be effectively codegen'd.
796 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
797 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
798 MVT VT = (MVT::SimpleValueType)i;
799 setOperationAction(ISD::ADD , VT, Expand);
800 setOperationAction(ISD::SUB , VT, Expand);
801 setOperationAction(ISD::FADD, VT, Expand);
802 setOperationAction(ISD::FNEG, VT, Expand);
803 setOperationAction(ISD::FSUB, VT, Expand);
804 setOperationAction(ISD::MUL , VT, Expand);
805 setOperationAction(ISD::FMUL, VT, Expand);
806 setOperationAction(ISD::SDIV, VT, Expand);
807 setOperationAction(ISD::UDIV, VT, Expand);
808 setOperationAction(ISD::FDIV, VT, Expand);
809 setOperationAction(ISD::SREM, VT, Expand);
810 setOperationAction(ISD::UREM, VT, Expand);
811 setOperationAction(ISD::LOAD, VT, Expand);
812 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
813 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
814 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
815 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
816 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
817 setOperationAction(ISD::FABS, VT, Expand);
818 setOperationAction(ISD::FSIN, VT, Expand);
819 setOperationAction(ISD::FSINCOS, VT, Expand);
820 setOperationAction(ISD::FCOS, VT, Expand);
821 setOperationAction(ISD::FSINCOS, VT, Expand);
822 setOperationAction(ISD::FREM, VT, Expand);
823 setOperationAction(ISD::FMA, VT, Expand);
824 setOperationAction(ISD::FPOWI, VT, Expand);
825 setOperationAction(ISD::FSQRT, VT, Expand);
826 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
827 setOperationAction(ISD::FFLOOR, VT, Expand);
828 setOperationAction(ISD::FCEIL, VT, Expand);
829 setOperationAction(ISD::FTRUNC, VT, Expand);
830 setOperationAction(ISD::FRINT, VT, Expand);
831 setOperationAction(ISD::FNEARBYINT, VT, Expand);
832 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
833 setOperationAction(ISD::MULHS, VT, Expand);
834 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
835 setOperationAction(ISD::MULHU, VT, Expand);
836 setOperationAction(ISD::SDIVREM, VT, Expand);
837 setOperationAction(ISD::UDIVREM, VT, Expand);
838 setOperationAction(ISD::FPOW, VT, Expand);
839 setOperationAction(ISD::CTPOP, VT, Expand);
840 setOperationAction(ISD::CTTZ, VT, Expand);
841 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
842 setOperationAction(ISD::CTLZ, VT, Expand);
843 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
844 setOperationAction(ISD::SHL, VT, Expand);
845 setOperationAction(ISD::SRA, VT, Expand);
846 setOperationAction(ISD::SRL, VT, Expand);
847 setOperationAction(ISD::ROTL, VT, Expand);
848 setOperationAction(ISD::ROTR, VT, Expand);
849 setOperationAction(ISD::BSWAP, VT, Expand);
850 setOperationAction(ISD::SETCC, VT, Expand);
851 setOperationAction(ISD::FLOG, VT, Expand);
852 setOperationAction(ISD::FLOG2, VT, Expand);
853 setOperationAction(ISD::FLOG10, VT, Expand);
854 setOperationAction(ISD::FEXP, VT, Expand);
855 setOperationAction(ISD::FEXP2, VT, Expand);
856 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
857 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
858 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
859 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
860 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
861 setOperationAction(ISD::TRUNCATE, VT, Expand);
862 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
863 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
864 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
865 setOperationAction(ISD::VSELECT, VT, Expand);
866 setOperationAction(ISD::SELECT_CC, VT, Expand);
867 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
868 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
869 setTruncStoreAction(VT,
870 (MVT::SimpleValueType)InnerVT, Expand);
871 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
872 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
873 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
876 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
877 // with -msoft-float, disable use of MMX as well.
878 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
879 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
880 // No operations on x86mmx supported, everything uses intrinsics.
883 // MMX-sized vectors (other than x86mmx) are expected to be expanded
884 // into smaller operations.
885 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
886 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
887 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
888 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
889 setOperationAction(ISD::AND, MVT::v8i8, Expand);
890 setOperationAction(ISD::AND, MVT::v4i16, Expand);
891 setOperationAction(ISD::AND, MVT::v2i32, Expand);
892 setOperationAction(ISD::AND, MVT::v1i64, Expand);
893 setOperationAction(ISD::OR, MVT::v8i8, Expand);
894 setOperationAction(ISD::OR, MVT::v4i16, Expand);
895 setOperationAction(ISD::OR, MVT::v2i32, Expand);
896 setOperationAction(ISD::OR, MVT::v1i64, Expand);
897 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
898 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
899 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
900 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
901 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
902 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
903 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
904 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
905 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
906 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
907 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
908 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
909 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
910 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
911 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
912 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
913 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
915 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
916 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
918 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
919 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
920 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
921 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
922 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
923 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
924 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
925 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
926 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
927 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
928 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
929 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
932 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
933 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
935 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
936 // registers cannot be used even for integer operations.
937 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
938 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
939 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
940 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
942 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
943 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
944 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
945 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
946 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
947 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
948 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
949 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
950 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
951 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
952 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
953 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
954 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
955 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
956 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
957 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
958 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
959 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
960 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
961 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
962 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
963 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
965 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
966 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
967 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
968 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
970 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
971 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
972 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
973 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
974 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
976 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
977 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
978 MVT VT = (MVT::SimpleValueType)i;
979 // Do not attempt to custom lower non-power-of-2 vectors
980 if (!isPowerOf2_32(VT.getVectorNumElements()))
982 // Do not attempt to custom lower non-128-bit vectors
983 if (!VT.is128BitVector())
985 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
986 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
987 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
990 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
991 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
992 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
993 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
994 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
995 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
997 if (Subtarget->is64Bit()) {
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
999 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1002 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1003 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1004 MVT VT = (MVT::SimpleValueType)i;
1006 // Do not attempt to promote non-128-bit vectors
1007 if (!VT.is128BitVector())
1010 setOperationAction(ISD::AND, VT, Promote);
1011 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1012 setOperationAction(ISD::OR, VT, Promote);
1013 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1014 setOperationAction(ISD::XOR, VT, Promote);
1015 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1016 setOperationAction(ISD::LOAD, VT, Promote);
1017 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1018 setOperationAction(ISD::SELECT, VT, Promote);
1019 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1022 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1024 // Custom lower v2i64 and v2f64 selects.
1025 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1026 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1027 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1028 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1030 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1031 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1033 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1034 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1035 // As there is no 64-bit GPR available, we need build a special custom
1036 // sequence to convert from v2i32 to v2f32.
1037 if (!Subtarget->is64Bit())
1038 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1040 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1041 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1043 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1045 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1046 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1047 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1050 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1051 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1052 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1053 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1054 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1055 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1056 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1057 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1058 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1059 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1060 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1062 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1063 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1064 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1065 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1066 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1067 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1068 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1069 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1070 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1071 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1073 // FIXME: Do we need to handle scalar-to-vector here?
1074 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1076 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1077 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1078 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1079 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1080 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1081 // There is no BLENDI for byte vectors. We don't need to custom lower
1082 // some vselects for now.
1083 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1085 // i8 and i16 vectors are custom , because the source register and source
1086 // source memory operand types are not the same width. f32 vectors are
1087 // custom since the immediate controlling the insert encodes additional
1089 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1090 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1091 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1092 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1094 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1095 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1096 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1097 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1099 // FIXME: these should be Legal but thats only for the case where
1100 // the index is constant. For now custom expand to deal with that.
1101 if (Subtarget->is64Bit()) {
1102 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1103 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1107 if (Subtarget->hasSSE2()) {
1108 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1109 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1111 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1112 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1114 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1115 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1117 // In the customized shift lowering, the legal cases in AVX2 will be
1119 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1120 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1122 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1123 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1125 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1128 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1129 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1130 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1131 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1132 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1133 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1134 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1136 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1137 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1138 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1140 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1142 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1143 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1145 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1146 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1147 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1148 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1149 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1150 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1151 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1153 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1154 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1156 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1158 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1159 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1160 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1161 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1162 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1163 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1164 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1166 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1167 // even though v8i16 is a legal type.
1168 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1169 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1170 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1172 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1173 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1174 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1176 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1177 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1179 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1181 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1182 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1184 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1185 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1187 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1188 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1190 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1191 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1192 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1193 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1195 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1196 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1197 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1199 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1200 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1201 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1202 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1204 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1205 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1206 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1207 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1208 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1209 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1210 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1211 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1212 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1213 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1214 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1215 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1217 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1218 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1219 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1220 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1221 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1222 setOperationAction(ISD::FMA, MVT::f32, Legal);
1223 setOperationAction(ISD::FMA, MVT::f64, Legal);
1226 if (Subtarget->hasInt256()) {
1227 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1228 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1229 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1230 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1232 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1233 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1234 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1235 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1237 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1238 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1239 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1240 // Don't lower v32i8 because there is no 128-bit byte mul
1242 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1243 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1244 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1245 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1247 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1248 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1250 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1251 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1252 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1253 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1255 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1256 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1257 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1258 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1260 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1261 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1262 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1263 // Don't lower v32i8 because there is no 128-bit byte mul
1266 // In the customized shift lowering, the legal cases in AVX2 will be
1268 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1269 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1271 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1272 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1274 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1276 // Custom lower several nodes for 256-bit types.
1277 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1278 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1279 MVT VT = (MVT::SimpleValueType)i;
1281 // Extract subvector is special because the value type
1282 // (result) is 128-bit but the source is 256-bit wide.
1283 if (VT.is128BitVector())
1284 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1286 // Do not attempt to custom lower other non-256-bit vectors
1287 if (!VT.is256BitVector())
1290 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1291 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1292 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1293 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1294 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1295 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1296 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1299 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1300 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1301 MVT VT = (MVT::SimpleValueType)i;
1303 // Do not attempt to promote non-256-bit vectors
1304 if (!VT.is256BitVector())
1307 setOperationAction(ISD::AND, VT, Promote);
1308 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1309 setOperationAction(ISD::OR, VT, Promote);
1310 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1311 setOperationAction(ISD::XOR, VT, Promote);
1312 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1313 setOperationAction(ISD::LOAD, VT, Promote);
1314 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1315 setOperationAction(ISD::SELECT, VT, Promote);
1316 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1320 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1321 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1322 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1323 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1324 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1326 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1327 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1328 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1330 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1331 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1332 setOperationAction(ISD::XOR, MVT::i1, Legal);
1333 setOperationAction(ISD::OR, MVT::i1, Legal);
1334 setOperationAction(ISD::AND, MVT::i1, Legal);
1335 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1336 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1337 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1338 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1339 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1340 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1342 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1343 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1344 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1345 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1347 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1349 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1350 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1351 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1352 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1353 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1354 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1355 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1356 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1358 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1359 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1360 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1361 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1362 if (Subtarget->is64Bit()) {
1363 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1364 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1365 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1366 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1368 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1369 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1370 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1371 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1372 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1373 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1374 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1375 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1376 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1377 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1379 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1380 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1381 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1382 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1383 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1384 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1385 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1386 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1387 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1388 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1389 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1390 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1391 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1393 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1394 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1395 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1396 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1397 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1398 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1400 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1401 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1403 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1405 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1406 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1407 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1408 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1409 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1410 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1411 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1412 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1413 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1415 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1416 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1418 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1419 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1421 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1423 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1424 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1426 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1427 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1429 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1430 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1432 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1433 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1434 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1435 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1436 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1437 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1439 if (Subtarget->hasCDI()) {
1440 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1441 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1444 // Custom lower several nodes.
1445 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1446 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1447 MVT VT = (MVT::SimpleValueType)i;
1449 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1450 // Extract subvector is special because the value type
1451 // (result) is 256/128-bit but the source is 512-bit wide.
1452 if (VT.is128BitVector() || VT.is256BitVector())
1453 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1455 if (VT.getVectorElementType() == MVT::i1)
1456 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1458 // Do not attempt to custom lower other non-512-bit vectors
1459 if (!VT.is512BitVector())
1462 if ( EltSize >= 32) {
1463 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1464 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1465 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1466 setOperationAction(ISD::VSELECT, VT, Legal);
1467 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1468 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1469 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1472 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1473 MVT VT = (MVT::SimpleValueType)i;
1475 // Do not attempt to promote non-256-bit vectors
1476 if (!VT.is512BitVector())
1479 setOperationAction(ISD::SELECT, VT, Promote);
1480 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1484 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1485 // of this type with custom code.
1486 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1487 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1488 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1492 // We want to custom lower some of our intrinsics.
1493 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1494 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1495 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1496 if (!Subtarget->is64Bit())
1497 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1499 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1500 // handle type legalization for these operations here.
1502 // FIXME: We really should do custom legalization for addition and
1503 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1504 // than generic legalization for 64-bit multiplication-with-overflow, though.
1505 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1506 // Add/Sub/Mul with overflow operations are custom lowered.
1508 setOperationAction(ISD::SADDO, VT, Custom);
1509 setOperationAction(ISD::UADDO, VT, Custom);
1510 setOperationAction(ISD::SSUBO, VT, Custom);
1511 setOperationAction(ISD::USUBO, VT, Custom);
1512 setOperationAction(ISD::SMULO, VT, Custom);
1513 setOperationAction(ISD::UMULO, VT, Custom);
1516 // There are no 8-bit 3-address imul/mul instructions
1517 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1518 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1520 if (!Subtarget->is64Bit()) {
1521 // These libcalls are not available in 32-bit.
1522 setLibcallName(RTLIB::SHL_I128, nullptr);
1523 setLibcallName(RTLIB::SRL_I128, nullptr);
1524 setLibcallName(RTLIB::SRA_I128, nullptr);
1527 // Combine sin / cos into one node or libcall if possible.
1528 if (Subtarget->hasSinCos()) {
1529 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1530 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1531 if (Subtarget->isTargetDarwin()) {
1532 // For MacOSX, we don't want to the normal expansion of a libcall to
1533 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1535 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1536 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1540 if (Subtarget->isTargetWin64()) {
1541 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1542 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1543 setOperationAction(ISD::SREM, MVT::i128, Custom);
1544 setOperationAction(ISD::UREM, MVT::i128, Custom);
1545 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1546 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1549 // We have target-specific dag combine patterns for the following nodes:
1550 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1551 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1552 setTargetDAGCombine(ISD::VSELECT);
1553 setTargetDAGCombine(ISD::SELECT);
1554 setTargetDAGCombine(ISD::SHL);
1555 setTargetDAGCombine(ISD::SRA);
1556 setTargetDAGCombine(ISD::SRL);
1557 setTargetDAGCombine(ISD::OR);
1558 setTargetDAGCombine(ISD::AND);
1559 setTargetDAGCombine(ISD::ADD);
1560 setTargetDAGCombine(ISD::FADD);
1561 setTargetDAGCombine(ISD::FSUB);
1562 setTargetDAGCombine(ISD::FMA);
1563 setTargetDAGCombine(ISD::SUB);
1564 setTargetDAGCombine(ISD::LOAD);
1565 setTargetDAGCombine(ISD::STORE);
1566 setTargetDAGCombine(ISD::ZERO_EXTEND);
1567 setTargetDAGCombine(ISD::ANY_EXTEND);
1568 setTargetDAGCombine(ISD::SIGN_EXTEND);
1569 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1570 setTargetDAGCombine(ISD::TRUNCATE);
1571 setTargetDAGCombine(ISD::SINT_TO_FP);
1572 setTargetDAGCombine(ISD::SETCC);
1573 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1574 setTargetDAGCombine(ISD::BUILD_VECTOR);
1575 if (Subtarget->is64Bit())
1576 setTargetDAGCombine(ISD::MUL);
1577 setTargetDAGCombine(ISD::XOR);
1579 computeRegisterProperties();
1581 // On Darwin, -Os means optimize for size without hurting performance,
1582 // do not reduce the limit.
1583 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1584 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1585 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1586 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1587 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1588 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1589 setPrefLoopAlignment(4); // 2^4 bytes.
1591 // Predictable cmov don't hurt on atom because it's in-order.
1592 PredictableSelectIsExpensive = !Subtarget->isAtom();
1594 setPrefFunctionAlignment(4); // 2^4 bytes.
1597 TargetLoweringBase::LegalizeTypeAction
1598 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1599 if (ExperimentalVectorWideningLegalization &&
1600 VT.getVectorNumElements() != 1 &&
1601 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1602 return TypeWidenVector;
1604 return TargetLoweringBase::getPreferredVectorAction(VT);
1607 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1609 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1611 if (Subtarget->hasAVX512())
1612 switch(VT.getVectorNumElements()) {
1613 case 8: return MVT::v8i1;
1614 case 16: return MVT::v16i1;
1617 return VT.changeVectorElementTypeToInteger();
1620 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1621 /// the desired ByVal argument alignment.
1622 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1625 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1626 if (VTy->getBitWidth() == 128)
1628 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1629 unsigned EltAlign = 0;
1630 getMaxByValAlign(ATy->getElementType(), EltAlign);
1631 if (EltAlign > MaxAlign)
1632 MaxAlign = EltAlign;
1633 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1634 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1635 unsigned EltAlign = 0;
1636 getMaxByValAlign(STy->getElementType(i), EltAlign);
1637 if (EltAlign > MaxAlign)
1638 MaxAlign = EltAlign;
1645 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1646 /// function arguments in the caller parameter area. For X86, aggregates
1647 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1648 /// are at 4-byte boundaries.
1649 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1650 if (Subtarget->is64Bit()) {
1651 // Max of 8 and alignment of type.
1652 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1659 if (Subtarget->hasSSE1())
1660 getMaxByValAlign(Ty, Align);
1664 /// getOptimalMemOpType - Returns the target specific optimal type for load
1665 /// and store operations as a result of memset, memcpy, and memmove
1666 /// lowering. If DstAlign is zero that means it's safe to destination
1667 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1668 /// means there isn't a need to check it against alignment requirement,
1669 /// probably because the source does not need to be loaded. If 'IsMemset' is
1670 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1671 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1672 /// source is constant so it does not need to be loaded.
1673 /// It returns EVT::Other if the type should be determined using generic
1674 /// target-independent logic.
1676 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1677 unsigned DstAlign, unsigned SrcAlign,
1678 bool IsMemset, bool ZeroMemset,
1680 MachineFunction &MF) const {
1681 const Function *F = MF.getFunction();
1682 if ((!IsMemset || ZeroMemset) &&
1683 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1684 Attribute::NoImplicitFloat)) {
1686 (Subtarget->isUnalignedMemAccessFast() ||
1687 ((DstAlign == 0 || DstAlign >= 16) &&
1688 (SrcAlign == 0 || SrcAlign >= 16)))) {
1690 if (Subtarget->hasInt256())
1692 if (Subtarget->hasFp256())
1695 if (Subtarget->hasSSE2())
1697 if (Subtarget->hasSSE1())
1699 } else if (!MemcpyStrSrc && Size >= 8 &&
1700 !Subtarget->is64Bit() &&
1701 Subtarget->hasSSE2()) {
1702 // Do not use f64 to lower memcpy if source is string constant. It's
1703 // better to use i32 to avoid the loads.
1707 if (Subtarget->is64Bit() && Size >= 8)
1712 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1714 return X86ScalarSSEf32;
1715 else if (VT == MVT::f64)
1716 return X86ScalarSSEf64;
1721 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1725 *Fast = Subtarget->isUnalignedMemAccessFast();
1729 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1730 /// current function. The returned value is a member of the
1731 /// MachineJumpTableInfo::JTEntryKind enum.
1732 unsigned X86TargetLowering::getJumpTableEncoding() const {
1733 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1735 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1736 Subtarget->isPICStyleGOT())
1737 return MachineJumpTableInfo::EK_Custom32;
1739 // Otherwise, use the normal jump table encoding heuristics.
1740 return TargetLowering::getJumpTableEncoding();
1744 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1745 const MachineBasicBlock *MBB,
1746 unsigned uid,MCContext &Ctx) const{
1747 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1748 Subtarget->isPICStyleGOT());
1749 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1751 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1752 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1755 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1757 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1758 SelectionDAG &DAG) const {
1759 if (!Subtarget->is64Bit())
1760 // This doesn't have SDLoc associated with it, but is not really the
1761 // same as a Register.
1762 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1766 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1767 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1769 const MCExpr *X86TargetLowering::
1770 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1771 MCContext &Ctx) const {
1772 // X86-64 uses RIP relative addressing based on the jump table label.
1773 if (Subtarget->isPICStyleRIPRel())
1774 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1776 // Otherwise, the reference is relative to the PIC base.
1777 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1780 // FIXME: Why this routine is here? Move to RegInfo!
1781 std::pair<const TargetRegisterClass*, uint8_t>
1782 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1783 const TargetRegisterClass *RRC = nullptr;
1785 switch (VT.SimpleTy) {
1787 return TargetLowering::findRepresentativeClass(VT);
1788 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1789 RRC = Subtarget->is64Bit() ?
1790 (const TargetRegisterClass*)&X86::GR64RegClass :
1791 (const TargetRegisterClass*)&X86::GR32RegClass;
1794 RRC = &X86::VR64RegClass;
1796 case MVT::f32: case MVT::f64:
1797 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1798 case MVT::v4f32: case MVT::v2f64:
1799 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1801 RRC = &X86::VR128RegClass;
1804 return std::make_pair(RRC, Cost);
1807 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1808 unsigned &Offset) const {
1809 if (!Subtarget->isTargetLinux())
1812 if (Subtarget->is64Bit()) {
1813 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1815 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1827 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1828 unsigned DestAS) const {
1829 assert(SrcAS != DestAS && "Expected different address spaces!");
1831 return SrcAS < 256 && DestAS < 256;
1834 //===----------------------------------------------------------------------===//
1835 // Return Value Calling Convention Implementation
1836 //===----------------------------------------------------------------------===//
1838 #include "X86GenCallingConv.inc"
1841 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1842 MachineFunction &MF, bool isVarArg,
1843 const SmallVectorImpl<ISD::OutputArg> &Outs,
1844 LLVMContext &Context) const {
1845 SmallVector<CCValAssign, 16> RVLocs;
1846 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1848 return CCInfo.CheckReturn(Outs, RetCC_X86);
1851 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1852 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1857 X86TargetLowering::LowerReturn(SDValue Chain,
1858 CallingConv::ID CallConv, bool isVarArg,
1859 const SmallVectorImpl<ISD::OutputArg> &Outs,
1860 const SmallVectorImpl<SDValue> &OutVals,
1861 SDLoc dl, SelectionDAG &DAG) const {
1862 MachineFunction &MF = DAG.getMachineFunction();
1863 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865 SmallVector<CCValAssign, 16> RVLocs;
1866 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1867 RVLocs, *DAG.getContext());
1868 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1871 SmallVector<SDValue, 6> RetOps;
1872 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1873 // Operand #1 = Bytes To Pop
1874 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1877 // Copy the result values into the output registers.
1878 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1879 CCValAssign &VA = RVLocs[i];
1880 assert(VA.isRegLoc() && "Can only return in registers!");
1881 SDValue ValToCopy = OutVals[i];
1882 EVT ValVT = ValToCopy.getValueType();
1884 // Promote values to the appropriate types
1885 if (VA.getLocInfo() == CCValAssign::SExt)
1886 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1887 else if (VA.getLocInfo() == CCValAssign::ZExt)
1888 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1889 else if (VA.getLocInfo() == CCValAssign::AExt)
1890 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1891 else if (VA.getLocInfo() == CCValAssign::BCvt)
1892 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1894 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1895 "Unexpected FP-extend for return value.");
1897 // If this is x86-64, and we disabled SSE, we can't return FP values,
1898 // or SSE or MMX vectors.
1899 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1900 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1901 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1902 report_fatal_error("SSE register return with SSE disabled");
1904 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1905 // llvm-gcc has never done it right and no one has noticed, so this
1906 // should be OK for now.
1907 if (ValVT == MVT::f64 &&
1908 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1909 report_fatal_error("SSE2 register return with SSE2 disabled");
1911 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1912 // the RET instruction and handled by the FP Stackifier.
1913 if (VA.getLocReg() == X86::ST0 ||
1914 VA.getLocReg() == X86::ST1) {
1915 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1916 // change the value to the FP stack register class.
1917 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1918 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1919 RetOps.push_back(ValToCopy);
1920 // Don't emit a copytoreg.
1924 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1925 // which is returned in RAX / RDX.
1926 if (Subtarget->is64Bit()) {
1927 if (ValVT == MVT::x86mmx) {
1928 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1929 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1930 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1932 // If we don't have SSE2 available, convert to v4f32 so the generated
1933 // register is legal.
1934 if (!Subtarget->hasSSE2())
1935 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1940 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1941 Flag = Chain.getValue(1);
1942 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1945 // The x86-64 ABIs require that for returning structs by value we copy
1946 // the sret argument into %rax/%eax (depending on ABI) for the return.
1947 // Win32 requires us to put the sret argument to %eax as well.
1948 // We saved the argument into a virtual register in the entry block,
1949 // so now we copy the value out and into %rax/%eax.
1950 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1951 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1952 MachineFunction &MF = DAG.getMachineFunction();
1953 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1954 unsigned Reg = FuncInfo->getSRetReturnReg();
1956 "SRetReturnReg should have been set in LowerFormalArguments().");
1957 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1960 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1961 X86::RAX : X86::EAX;
1962 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1963 Flag = Chain.getValue(1);
1965 // RAX/EAX now acts like a return value.
1966 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1969 RetOps[0] = Chain; // Update chain.
1971 // Add the flag if we have it.
1973 RetOps.push_back(Flag);
1975 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1978 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1979 if (N->getNumValues() != 1)
1981 if (!N->hasNUsesOfValue(1, 0))
1984 SDValue TCChain = Chain;
1985 SDNode *Copy = *N->use_begin();
1986 if (Copy->getOpcode() == ISD::CopyToReg) {
1987 // If the copy has a glue operand, we conservatively assume it isn't safe to
1988 // perform a tail call.
1989 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1991 TCChain = Copy->getOperand(0);
1992 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1995 bool HasRet = false;
1996 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1998 if (UI->getOpcode() != X86ISD::RET_FLAG)
2011 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2012 ISD::NodeType ExtendKind) const {
2014 // TODO: Is this also valid on 32-bit?
2015 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2016 ReturnMVT = MVT::i8;
2018 ReturnMVT = MVT::i32;
2020 MVT MinVT = getRegisterType(ReturnMVT);
2021 return VT.bitsLT(MinVT) ? MinVT : VT;
2024 /// LowerCallResult - Lower the result values of a call into the
2025 /// appropriate copies out of appropriate physical registers.
2028 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2029 CallingConv::ID CallConv, bool isVarArg,
2030 const SmallVectorImpl<ISD::InputArg> &Ins,
2031 SDLoc dl, SelectionDAG &DAG,
2032 SmallVectorImpl<SDValue> &InVals) const {
2034 // Assign locations to each value returned by this call.
2035 SmallVector<CCValAssign, 16> RVLocs;
2036 bool Is64Bit = Subtarget->is64Bit();
2037 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2038 DAG.getTarget(), RVLocs, *DAG.getContext());
2039 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2041 // Copy all of the result registers out of their specified physreg.
2042 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2043 CCValAssign &VA = RVLocs[i];
2044 EVT CopyVT = VA.getValVT();
2046 // If this is x86-64, and we disabled SSE, we can't return FP values
2047 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2048 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2049 report_fatal_error("SSE register return with SSE disabled");
2054 // If this is a call to a function that returns an fp value on the floating
2055 // point stack, we must guarantee the value is popped from the stack, so
2056 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2057 // if the return value is not used. We use the FpPOP_RETVAL instruction
2059 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2060 // If we prefer to use the value in xmm registers, copy it out as f80 and
2061 // use a truncate to move it from fp stack reg to xmm reg.
2062 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2063 SDValue Ops[] = { Chain, InFlag };
2064 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2065 MVT::Other, MVT::Glue, Ops), 1);
2066 Val = Chain.getValue(0);
2068 // Round the f80 to the right size, which also moves it to the appropriate
2070 if (CopyVT != VA.getValVT())
2071 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2072 // This truncation won't change the value.
2073 DAG.getIntPtrConstant(1));
2075 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2076 CopyVT, InFlag).getValue(1);
2077 Val = Chain.getValue(0);
2079 InFlag = Chain.getValue(2);
2080 InVals.push_back(Val);
2086 //===----------------------------------------------------------------------===//
2087 // C & StdCall & Fast Calling Convention implementation
2088 //===----------------------------------------------------------------------===//
2089 // StdCall calling convention seems to be standard for many Windows' API
2090 // routines and around. It differs from C calling convention just a little:
2091 // callee should clean up the stack, not caller. Symbols should be also
2092 // decorated in some fancy way :) It doesn't support any vector arguments.
2093 // For info on fast calling convention see Fast Calling Convention (tail call)
2094 // implementation LowerX86_32FastCCCallTo.
2096 /// CallIsStructReturn - Determines whether a call uses struct return
2098 enum StructReturnType {
2103 static StructReturnType
2104 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2106 return NotStructReturn;
2108 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2109 if (!Flags.isSRet())
2110 return NotStructReturn;
2111 if (Flags.isInReg())
2112 return RegStructReturn;
2113 return StackStructReturn;
2116 /// ArgsAreStructReturn - Determines whether a function uses struct
2117 /// return semantics.
2118 static StructReturnType
2119 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2121 return NotStructReturn;
2123 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2124 if (!Flags.isSRet())
2125 return NotStructReturn;
2126 if (Flags.isInReg())
2127 return RegStructReturn;
2128 return StackStructReturn;
2131 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2132 /// by "Src" to address "Dst" with size and alignment information specified by
2133 /// the specific parameter attribute. The copy will be passed as a byval
2134 /// function parameter.
2136 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2137 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2139 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2141 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2142 /*isVolatile*/false, /*AlwaysInline=*/true,
2143 MachinePointerInfo(), MachinePointerInfo());
2146 /// IsTailCallConvention - Return true if the calling convention is one that
2147 /// supports tail call optimization.
2148 static bool IsTailCallConvention(CallingConv::ID CC) {
2149 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2150 CC == CallingConv::HiPE);
2153 /// \brief Return true if the calling convention is a C calling convention.
2154 static bool IsCCallConvention(CallingConv::ID CC) {
2155 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2156 CC == CallingConv::X86_64_SysV);
2159 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2160 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2164 CallingConv::ID CalleeCC = CS.getCallingConv();
2165 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2171 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2172 /// a tailcall target by changing its ABI.
2173 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2174 bool GuaranteedTailCallOpt) {
2175 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2179 X86TargetLowering::LowerMemArgument(SDValue Chain,
2180 CallingConv::ID CallConv,
2181 const SmallVectorImpl<ISD::InputArg> &Ins,
2182 SDLoc dl, SelectionDAG &DAG,
2183 const CCValAssign &VA,
2184 MachineFrameInfo *MFI,
2186 // Create the nodes corresponding to a load from this parameter slot.
2187 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2188 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2189 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2190 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2193 // If value is passed by pointer we have address passed instead of the value
2195 if (VA.getLocInfo() == CCValAssign::Indirect)
2196 ValVT = VA.getLocVT();
2198 ValVT = VA.getValVT();
2200 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2201 // changed with more analysis.
2202 // In case of tail call optimization mark all arguments mutable. Since they
2203 // could be overwritten by lowering of arguments in case of a tail call.
2204 if (Flags.isByVal()) {
2205 unsigned Bytes = Flags.getByValSize();
2206 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2207 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2208 return DAG.getFrameIndex(FI, getPointerTy());
2210 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2211 VA.getLocMemOffset(), isImmutable);
2212 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2213 return DAG.getLoad(ValVT, dl, Chain, FIN,
2214 MachinePointerInfo::getFixedStack(FI),
2215 false, false, false, 0);
2220 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2221 CallingConv::ID CallConv,
2223 const SmallVectorImpl<ISD::InputArg> &Ins,
2226 SmallVectorImpl<SDValue> &InVals)
2228 MachineFunction &MF = DAG.getMachineFunction();
2229 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2231 const Function* Fn = MF.getFunction();
2232 if (Fn->hasExternalLinkage() &&
2233 Subtarget->isTargetCygMing() &&
2234 Fn->getName() == "main")
2235 FuncInfo->setForceFramePointer(true);
2237 MachineFrameInfo *MFI = MF.getFrameInfo();
2238 bool Is64Bit = Subtarget->is64Bit();
2239 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2241 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2242 "Var args not supported with calling convention fastcc, ghc or hipe");
2244 // Assign locations to all of the incoming arguments.
2245 SmallVector<CCValAssign, 16> ArgLocs;
2246 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2247 ArgLocs, *DAG.getContext());
2249 // Allocate shadow area for Win64
2251 CCInfo.AllocateStack(32, 8);
2253 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2255 unsigned LastVal = ~0U;
2257 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2258 CCValAssign &VA = ArgLocs[i];
2259 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2261 assert(VA.getValNo() != LastVal &&
2262 "Don't support value assigned to multiple locs yet");
2264 LastVal = VA.getValNo();
2266 if (VA.isRegLoc()) {
2267 EVT RegVT = VA.getLocVT();
2268 const TargetRegisterClass *RC;
2269 if (RegVT == MVT::i32)
2270 RC = &X86::GR32RegClass;
2271 else if (Is64Bit && RegVT == MVT::i64)
2272 RC = &X86::GR64RegClass;
2273 else if (RegVT == MVT::f32)
2274 RC = &X86::FR32RegClass;
2275 else if (RegVT == MVT::f64)
2276 RC = &X86::FR64RegClass;
2277 else if (RegVT.is512BitVector())
2278 RC = &X86::VR512RegClass;
2279 else if (RegVT.is256BitVector())
2280 RC = &X86::VR256RegClass;
2281 else if (RegVT.is128BitVector())
2282 RC = &X86::VR128RegClass;
2283 else if (RegVT == MVT::x86mmx)
2284 RC = &X86::VR64RegClass;
2285 else if (RegVT == MVT::i1)
2286 RC = &X86::VK1RegClass;
2287 else if (RegVT == MVT::v8i1)
2288 RC = &X86::VK8RegClass;
2289 else if (RegVT == MVT::v16i1)
2290 RC = &X86::VK16RegClass;
2292 llvm_unreachable("Unknown argument type!");
2294 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2295 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2297 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2298 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2300 if (VA.getLocInfo() == CCValAssign::SExt)
2301 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2302 DAG.getValueType(VA.getValVT()));
2303 else if (VA.getLocInfo() == CCValAssign::ZExt)
2304 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2305 DAG.getValueType(VA.getValVT()));
2306 else if (VA.getLocInfo() == CCValAssign::BCvt)
2307 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2309 if (VA.isExtInLoc()) {
2310 // Handle MMX values passed in XMM regs.
2311 if (RegVT.isVector())
2312 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2314 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2317 assert(VA.isMemLoc());
2318 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2321 // If value is passed via pointer - do a load.
2322 if (VA.getLocInfo() == CCValAssign::Indirect)
2323 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2324 MachinePointerInfo(), false, false, false, 0);
2326 InVals.push_back(ArgValue);
2329 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2330 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2331 // The x86-64 ABIs require that for returning structs by value we copy
2332 // the sret argument into %rax/%eax (depending on ABI) for the return.
2333 // Win32 requires us to put the sret argument to %eax as well.
2334 // Save the argument into a virtual register so that we can access it
2335 // from the return points.
2336 if (Ins[i].Flags.isSRet()) {
2337 unsigned Reg = FuncInfo->getSRetReturnReg();
2339 MVT PtrTy = getPointerTy();
2340 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2341 FuncInfo->setSRetReturnReg(Reg);
2343 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2344 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2350 unsigned StackSize = CCInfo.getNextStackOffset();
2351 // Align stack specially for tail calls.
2352 if (FuncIsMadeTailCallSafe(CallConv,
2353 MF.getTarget().Options.GuaranteedTailCallOpt))
2354 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2356 // If the function takes variable number of arguments, make a frame index for
2357 // the start of the first vararg value... for expansion of llvm.va_start.
2359 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2360 CallConv != CallingConv::X86_ThisCall)) {
2361 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2364 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2366 // FIXME: We should really autogenerate these arrays
2367 static const MCPhysReg GPR64ArgRegsWin64[] = {
2368 X86::RCX, X86::RDX, X86::R8, X86::R9
2370 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2371 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2373 static const MCPhysReg XMMArgRegs64Bit[] = {
2374 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2375 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2377 const MCPhysReg *GPR64ArgRegs;
2378 unsigned NumXMMRegs = 0;
2381 // The XMM registers which might contain var arg parameters are shadowed
2382 // in their paired GPR. So we only need to save the GPR to their home
2384 TotalNumIntRegs = 4;
2385 GPR64ArgRegs = GPR64ArgRegsWin64;
2387 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2388 GPR64ArgRegs = GPR64ArgRegs64Bit;
2390 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2393 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2396 bool NoImplicitFloatOps = Fn->getAttributes().
2397 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2398 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2399 "SSE register cannot be used when SSE is disabled!");
2400 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2401 NoImplicitFloatOps) &&
2402 "SSE register cannot be used when SSE is disabled!");
2403 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2404 !Subtarget->hasSSE1())
2405 // Kernel mode asks for SSE to be disabled, so don't push them
2407 TotalNumXMMRegs = 0;
2410 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2411 // Get to the caller-allocated home save location. Add 8 to account
2412 // for the return address.
2413 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2414 FuncInfo->setRegSaveFrameIndex(
2415 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2416 // Fixup to set vararg frame on shadow area (4 x i64).
2418 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2420 // For X86-64, if there are vararg parameters that are passed via
2421 // registers, then we must store them to their spots on the stack so
2422 // they may be loaded by deferencing the result of va_next.
2423 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2424 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2425 FuncInfo->setRegSaveFrameIndex(
2426 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2430 // Store the integer parameter registers.
2431 SmallVector<SDValue, 8> MemOps;
2432 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2434 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2435 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2436 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2437 DAG.getIntPtrConstant(Offset));
2438 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2439 &X86::GR64RegClass);
2440 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2442 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2443 MachinePointerInfo::getFixedStack(
2444 FuncInfo->getRegSaveFrameIndex(), Offset),
2446 MemOps.push_back(Store);
2450 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2451 // Now store the XMM (fp + vector) parameter registers.
2452 SmallVector<SDValue, 11> SaveXMMOps;
2453 SaveXMMOps.push_back(Chain);
2455 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2456 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2457 SaveXMMOps.push_back(ALVal);
2459 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2460 FuncInfo->getRegSaveFrameIndex()));
2461 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2462 FuncInfo->getVarArgsFPOffset()));
2464 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2465 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2466 &X86::VR128RegClass);
2467 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2468 SaveXMMOps.push_back(Val);
2470 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2471 MVT::Other, SaveXMMOps));
2474 if (!MemOps.empty())
2475 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2479 // Some CCs need callee pop.
2480 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2481 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2482 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2484 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2485 // If this is an sret function, the return should pop the hidden pointer.
2486 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2487 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2488 argsAreStructReturn(Ins) == StackStructReturn)
2489 FuncInfo->setBytesToPopOnReturn(4);
2493 // RegSaveFrameIndex is X86-64 only.
2494 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2495 if (CallConv == CallingConv::X86_FastCall ||
2496 CallConv == CallingConv::X86_ThisCall)
2497 // fastcc functions can't have varargs.
2498 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2501 FuncInfo->setArgumentStackSize(StackSize);
2507 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2508 SDValue StackPtr, SDValue Arg,
2509 SDLoc dl, SelectionDAG &DAG,
2510 const CCValAssign &VA,
2511 ISD::ArgFlagsTy Flags) const {
2512 unsigned LocMemOffset = VA.getLocMemOffset();
2513 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2514 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2515 if (Flags.isByVal())
2516 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2518 return DAG.getStore(Chain, dl, Arg, PtrOff,
2519 MachinePointerInfo::getStack(LocMemOffset),
2523 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2524 /// optimization is performed and it is required.
2526 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2527 SDValue &OutRetAddr, SDValue Chain,
2528 bool IsTailCall, bool Is64Bit,
2529 int FPDiff, SDLoc dl) const {
2530 // Adjust the Return address stack slot.
2531 EVT VT = getPointerTy();
2532 OutRetAddr = getReturnAddressFrameIndex(DAG);
2534 // Load the "old" Return address.
2535 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2536 false, false, false, 0);
2537 return SDValue(OutRetAddr.getNode(), 1);
2540 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2541 /// optimization is performed and it is required (FPDiff!=0).
2542 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2543 SDValue Chain, SDValue RetAddrFrIdx,
2544 EVT PtrVT, unsigned SlotSize,
2545 int FPDiff, SDLoc dl) {
2546 // Store the return address to the appropriate stack slot.
2547 if (!FPDiff) return Chain;
2548 // Calculate the new stack slot for the return address.
2549 int NewReturnAddrFI =
2550 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2552 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2553 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2554 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2560 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2561 SmallVectorImpl<SDValue> &InVals) const {
2562 SelectionDAG &DAG = CLI.DAG;
2564 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2565 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2566 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2567 SDValue Chain = CLI.Chain;
2568 SDValue Callee = CLI.Callee;
2569 CallingConv::ID CallConv = CLI.CallConv;
2570 bool &isTailCall = CLI.IsTailCall;
2571 bool isVarArg = CLI.IsVarArg;
2573 MachineFunction &MF = DAG.getMachineFunction();
2574 bool Is64Bit = Subtarget->is64Bit();
2575 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2576 StructReturnType SR = callIsStructReturn(Outs);
2577 bool IsSibcall = false;
2579 if (MF.getTarget().Options.DisableTailCalls)
2582 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2584 // Force this to be a tail call. The verifier rules are enough to ensure
2585 // that we can lower this successfully without moving the return address
2588 } else if (isTailCall) {
2589 // Check if it's really possible to do a tail call.
2590 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2591 isVarArg, SR != NotStructReturn,
2592 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2593 Outs, OutVals, Ins, DAG);
2595 // Sibcalls are automatically detected tailcalls which do not require
2597 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2604 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2605 "Var args not supported with calling convention fastcc, ghc or hipe");
2607 // Analyze operands of the call, assigning locations to each operand.
2608 SmallVector<CCValAssign, 16> ArgLocs;
2609 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2610 ArgLocs, *DAG.getContext());
2612 // Allocate shadow area for Win64
2614 CCInfo.AllocateStack(32, 8);
2616 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2618 // Get a count of how many bytes are to be pushed on the stack.
2619 unsigned NumBytes = CCInfo.getNextStackOffset();
2621 // This is a sibcall. The memory operands are available in caller's
2622 // own caller's stack.
2624 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2625 IsTailCallConvention(CallConv))
2626 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2629 if (isTailCall && !IsSibcall && !IsMustTail) {
2630 // Lower arguments at fp - stackoffset + fpdiff.
2631 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2632 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2634 FPDiff = NumBytesCallerPushed - NumBytes;
2636 // Set the delta of movement of the returnaddr stackslot.
2637 // But only set if delta is greater than previous delta.
2638 if (FPDiff < X86Info->getTCReturnAddrDelta())
2639 X86Info->setTCReturnAddrDelta(FPDiff);
2642 unsigned NumBytesToPush = NumBytes;
2643 unsigned NumBytesToPop = NumBytes;
2645 // If we have an inalloca argument, all stack space has already been allocated
2646 // for us and be right at the top of the stack. We don't support multiple
2647 // arguments passed in memory when using inalloca.
2648 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2650 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2651 "an inalloca argument must be the only memory argument");
2655 Chain = DAG.getCALLSEQ_START(
2656 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2658 SDValue RetAddrFrIdx;
2659 // Load return address for tail calls.
2660 if (isTailCall && FPDiff)
2661 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2662 Is64Bit, FPDiff, dl);
2664 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2665 SmallVector<SDValue, 8> MemOpChains;
2668 // Walk the register/memloc assignments, inserting copies/loads. In the case
2669 // of tail call optimization arguments are handle later.
2670 const X86RegisterInfo *RegInfo =
2671 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2672 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2673 // Skip inalloca arguments, they have already been written.
2674 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2675 if (Flags.isInAlloca())
2678 CCValAssign &VA = ArgLocs[i];
2679 EVT RegVT = VA.getLocVT();
2680 SDValue Arg = OutVals[i];
2681 bool isByVal = Flags.isByVal();
2683 // Promote the value if needed.
2684 switch (VA.getLocInfo()) {
2685 default: llvm_unreachable("Unknown loc info!");
2686 case CCValAssign::Full: break;
2687 case CCValAssign::SExt:
2688 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2690 case CCValAssign::ZExt:
2691 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2693 case CCValAssign::AExt:
2694 if (RegVT.is128BitVector()) {
2695 // Special case: passing MMX values in XMM registers.
2696 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2697 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2698 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2700 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2702 case CCValAssign::BCvt:
2703 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2705 case CCValAssign::Indirect: {
2706 // Store the argument.
2707 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2708 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2709 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2710 MachinePointerInfo::getFixedStack(FI),
2717 if (VA.isRegLoc()) {
2718 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2719 if (isVarArg && IsWin64) {
2720 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2721 // shadow reg if callee is a varargs function.
2722 unsigned ShadowReg = 0;
2723 switch (VA.getLocReg()) {
2724 case X86::XMM0: ShadowReg = X86::RCX; break;
2725 case X86::XMM1: ShadowReg = X86::RDX; break;
2726 case X86::XMM2: ShadowReg = X86::R8; break;
2727 case X86::XMM3: ShadowReg = X86::R9; break;
2730 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2732 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2733 assert(VA.isMemLoc());
2734 if (!StackPtr.getNode())
2735 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2737 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2738 dl, DAG, VA, Flags));
2742 if (!MemOpChains.empty())
2743 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2745 if (Subtarget->isPICStyleGOT()) {
2746 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2749 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2750 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2752 // If we are tail calling and generating PIC/GOT style code load the
2753 // address of the callee into ECX. The value in ecx is used as target of
2754 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2755 // for tail calls on PIC/GOT architectures. Normally we would just put the
2756 // address of GOT into ebx and then call target@PLT. But for tail calls
2757 // ebx would be restored (since ebx is callee saved) before jumping to the
2760 // Note: The actual moving to ECX is done further down.
2761 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2762 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2763 !G->getGlobal()->hasProtectedVisibility())
2764 Callee = LowerGlobalAddress(Callee, DAG);
2765 else if (isa<ExternalSymbolSDNode>(Callee))
2766 Callee = LowerExternalSymbol(Callee, DAG);
2770 if (Is64Bit && isVarArg && !IsWin64) {
2771 // From AMD64 ABI document:
2772 // For calls that may call functions that use varargs or stdargs
2773 // (prototype-less calls or calls to functions containing ellipsis (...) in
2774 // the declaration) %al is used as hidden argument to specify the number
2775 // of SSE registers used. The contents of %al do not need to match exactly
2776 // the number of registers, but must be an ubound on the number of SSE
2777 // registers used and is in the range 0 - 8 inclusive.
2779 // Count the number of XMM registers allocated.
2780 static const MCPhysReg XMMArgRegs[] = {
2781 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2782 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2784 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2785 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2786 && "SSE registers cannot be used when SSE is disabled");
2788 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2789 DAG.getConstant(NumXMMRegs, MVT::i8)));
2792 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2793 // don't need this because the eligibility check rejects calls that require
2794 // shuffling arguments passed in memory.
2795 if (!IsSibcall && isTailCall) {
2796 // Force all the incoming stack arguments to be loaded from the stack
2797 // before any new outgoing arguments are stored to the stack, because the
2798 // outgoing stack slots may alias the incoming argument stack slots, and
2799 // the alias isn't otherwise explicit. This is slightly more conservative
2800 // than necessary, because it means that each store effectively depends
2801 // on every argument instead of just those arguments it would clobber.
2802 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2804 SmallVector<SDValue, 8> MemOpChains2;
2807 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2808 CCValAssign &VA = ArgLocs[i];
2811 assert(VA.isMemLoc());
2812 SDValue Arg = OutVals[i];
2813 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2814 // Skip inalloca arguments. They don't require any work.
2815 if (Flags.isInAlloca())
2817 // Create frame index.
2818 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2819 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2820 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2821 FIN = DAG.getFrameIndex(FI, getPointerTy());
2823 if (Flags.isByVal()) {
2824 // Copy relative to framepointer.
2825 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2826 if (!StackPtr.getNode())
2827 StackPtr = DAG.getCopyFromReg(Chain, dl,
2828 RegInfo->getStackRegister(),
2830 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2832 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2836 // Store relative to framepointer.
2837 MemOpChains2.push_back(
2838 DAG.getStore(ArgChain, dl, Arg, FIN,
2839 MachinePointerInfo::getFixedStack(FI),
2844 if (!MemOpChains2.empty())
2845 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2847 // Store the return address to the appropriate stack slot.
2848 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2849 getPointerTy(), RegInfo->getSlotSize(),
2853 // Build a sequence of copy-to-reg nodes chained together with token chain
2854 // and flag operands which copy the outgoing args into registers.
2856 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2857 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2858 RegsToPass[i].second, InFlag);
2859 InFlag = Chain.getValue(1);
2862 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2863 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2864 // In the 64-bit large code model, we have to make all calls
2865 // through a register, since the call instruction's 32-bit
2866 // pc-relative offset may not be large enough to hold the whole
2868 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2869 // If the callee is a GlobalAddress node (quite common, every direct call
2870 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2873 // We should use extra load for direct calls to dllimported functions in
2875 const GlobalValue *GV = G->getGlobal();
2876 if (!GV->hasDLLImportStorageClass()) {
2877 unsigned char OpFlags = 0;
2878 bool ExtraLoad = false;
2879 unsigned WrapperKind = ISD::DELETED_NODE;
2881 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2882 // external symbols most go through the PLT in PIC mode. If the symbol
2883 // has hidden or protected visibility, or if it is static or local, then
2884 // we don't need to use the PLT - we can directly call it.
2885 if (Subtarget->isTargetELF() &&
2886 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2887 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2888 OpFlags = X86II::MO_PLT;
2889 } else if (Subtarget->isPICStyleStubAny() &&
2890 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2891 (!Subtarget->getTargetTriple().isMacOSX() ||
2892 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2893 // PC-relative references to external symbols should go through $stub,
2894 // unless we're building with the leopard linker or later, which
2895 // automatically synthesizes these stubs.
2896 OpFlags = X86II::MO_DARWIN_STUB;
2897 } else if (Subtarget->isPICStyleRIPRel() &&
2898 isa<Function>(GV) &&
2899 cast<Function>(GV)->getAttributes().
2900 hasAttribute(AttributeSet::FunctionIndex,
2901 Attribute::NonLazyBind)) {
2902 // If the function is marked as non-lazy, generate an indirect call
2903 // which loads from the GOT directly. This avoids runtime overhead
2904 // at the cost of eager binding (and one extra byte of encoding).
2905 OpFlags = X86II::MO_GOTPCREL;
2906 WrapperKind = X86ISD::WrapperRIP;
2910 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2911 G->getOffset(), OpFlags);
2913 // Add a wrapper if needed.
2914 if (WrapperKind != ISD::DELETED_NODE)
2915 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2916 // Add extra indirection if needed.
2918 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2919 MachinePointerInfo::getGOT(),
2920 false, false, false, 0);
2922 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2923 unsigned char OpFlags = 0;
2925 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2926 // external symbols should go through the PLT.
2927 if (Subtarget->isTargetELF() &&
2928 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2929 OpFlags = X86II::MO_PLT;
2930 } else if (Subtarget->isPICStyleStubAny() &&
2931 (!Subtarget->getTargetTriple().isMacOSX() ||
2932 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2933 // PC-relative references to external symbols should go through $stub,
2934 // unless we're building with the leopard linker or later, which
2935 // automatically synthesizes these stubs.
2936 OpFlags = X86II::MO_DARWIN_STUB;
2939 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2943 // Returns a chain & a flag for retval copy to use.
2944 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2945 SmallVector<SDValue, 8> Ops;
2947 if (!IsSibcall && isTailCall) {
2948 Chain = DAG.getCALLSEQ_END(Chain,
2949 DAG.getIntPtrConstant(NumBytesToPop, true),
2950 DAG.getIntPtrConstant(0, true), InFlag, dl);
2951 InFlag = Chain.getValue(1);
2954 Ops.push_back(Chain);
2955 Ops.push_back(Callee);
2958 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2960 // Add argument registers to the end of the list so that they are known live
2962 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2963 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2964 RegsToPass[i].second.getValueType()));
2966 // Add a register mask operand representing the call-preserved registers.
2967 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2968 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2969 assert(Mask && "Missing call preserved mask for calling convention");
2970 Ops.push_back(DAG.getRegisterMask(Mask));
2972 if (InFlag.getNode())
2973 Ops.push_back(InFlag);
2977 //// If this is the first return lowered for this function, add the regs
2978 //// to the liveout set for the function.
2979 // This isn't right, although it's probably harmless on x86; liveouts
2980 // should be computed from returns not tail calls. Consider a void
2981 // function making a tail call to a function returning int.
2982 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2985 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2986 InFlag = Chain.getValue(1);
2988 // Create the CALLSEQ_END node.
2989 unsigned NumBytesForCalleeToPop;
2990 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2991 DAG.getTarget().Options.GuaranteedTailCallOpt))
2992 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2993 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2994 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2995 SR == StackStructReturn)
2996 // If this is a call to a struct-return function, the callee
2997 // pops the hidden struct pointer, so we have to push it back.
2998 // This is common for Darwin/X86, Linux & Mingw32 targets.
2999 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3000 NumBytesForCalleeToPop = 4;
3002 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3004 // Returns a flag for retval copy to use.
3006 Chain = DAG.getCALLSEQ_END(Chain,
3007 DAG.getIntPtrConstant(NumBytesToPop, true),
3008 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3011 InFlag = Chain.getValue(1);
3014 // Handle result values, copying them out of physregs into vregs that we
3016 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3017 Ins, dl, DAG, InVals);
3020 //===----------------------------------------------------------------------===//
3021 // Fast Calling Convention (tail call) implementation
3022 //===----------------------------------------------------------------------===//
3024 // Like std call, callee cleans arguments, convention except that ECX is
3025 // reserved for storing the tail called function address. Only 2 registers are
3026 // free for argument passing (inreg). Tail call optimization is performed
3028 // * tailcallopt is enabled
3029 // * caller/callee are fastcc
3030 // On X86_64 architecture with GOT-style position independent code only local
3031 // (within module) calls are supported at the moment.
3032 // To keep the stack aligned according to platform abi the function
3033 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3034 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3035 // If a tail called function callee has more arguments than the caller the
3036 // caller needs to make sure that there is room to move the RETADDR to. This is
3037 // achieved by reserving an area the size of the argument delta right after the
3038 // original REtADDR, but before the saved framepointer or the spilled registers
3039 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3051 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3052 /// for a 16 byte align requirement.
3054 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3055 SelectionDAG& DAG) const {
3056 MachineFunction &MF = DAG.getMachineFunction();
3057 const TargetMachine &TM = MF.getTarget();
3058 const X86RegisterInfo *RegInfo =
3059 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3060 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3061 unsigned StackAlignment = TFI.getStackAlignment();
3062 uint64_t AlignMask = StackAlignment - 1;
3063 int64_t Offset = StackSize;
3064 unsigned SlotSize = RegInfo->getSlotSize();
3065 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3066 // Number smaller than 12 so just add the difference.
3067 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3069 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3070 Offset = ((~AlignMask) & Offset) + StackAlignment +
3071 (StackAlignment-SlotSize);
3076 /// MatchingStackOffset - Return true if the given stack call argument is
3077 /// already available in the same position (relatively) of the caller's
3078 /// incoming argument stack.
3080 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3081 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3082 const X86InstrInfo *TII) {
3083 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3085 if (Arg.getOpcode() == ISD::CopyFromReg) {
3086 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3087 if (!TargetRegisterInfo::isVirtualRegister(VR))
3089 MachineInstr *Def = MRI->getVRegDef(VR);
3092 if (!Flags.isByVal()) {
3093 if (!TII->isLoadFromStackSlot(Def, FI))
3096 unsigned Opcode = Def->getOpcode();
3097 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3098 Def->getOperand(1).isFI()) {
3099 FI = Def->getOperand(1).getIndex();
3100 Bytes = Flags.getByValSize();
3104 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3105 if (Flags.isByVal())
3106 // ByVal argument is passed in as a pointer but it's now being
3107 // dereferenced. e.g.
3108 // define @foo(%struct.X* %A) {
3109 // tail call @bar(%struct.X* byval %A)
3112 SDValue Ptr = Ld->getBasePtr();
3113 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3116 FI = FINode->getIndex();
3117 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3118 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3119 FI = FINode->getIndex();
3120 Bytes = Flags.getByValSize();
3124 assert(FI != INT_MAX);
3125 if (!MFI->isFixedObjectIndex(FI))
3127 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3130 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3131 /// for tail call optimization. Targets which want to do tail call
3132 /// optimization should implement this function.
3134 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3135 CallingConv::ID CalleeCC,
3137 bool isCalleeStructRet,
3138 bool isCallerStructRet,
3140 const SmallVectorImpl<ISD::OutputArg> &Outs,
3141 const SmallVectorImpl<SDValue> &OutVals,
3142 const SmallVectorImpl<ISD::InputArg> &Ins,
3143 SelectionDAG &DAG) const {
3144 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3147 // If -tailcallopt is specified, make fastcc functions tail-callable.
3148 const MachineFunction &MF = DAG.getMachineFunction();
3149 const Function *CallerF = MF.getFunction();
3151 // If the function return type is x86_fp80 and the callee return type is not,
3152 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3153 // perform a tailcall optimization here.
3154 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3157 CallingConv::ID CallerCC = CallerF->getCallingConv();
3158 bool CCMatch = CallerCC == CalleeCC;
3159 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3160 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3162 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3163 if (IsTailCallConvention(CalleeCC) && CCMatch)
3168 // Look for obvious safe cases to perform tail call optimization that do not
3169 // require ABI changes. This is what gcc calls sibcall.
3171 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3172 // emit a special epilogue.
3173 const X86RegisterInfo *RegInfo =
3174 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3175 if (RegInfo->needsStackRealignment(MF))
3178 // Also avoid sibcall optimization if either caller or callee uses struct
3179 // return semantics.
3180 if (isCalleeStructRet || isCallerStructRet)
3183 // An stdcall/thiscall caller is expected to clean up its arguments; the
3184 // callee isn't going to do that.
3185 // FIXME: this is more restrictive than needed. We could produce a tailcall
3186 // when the stack adjustment matches. For example, with a thiscall that takes
3187 // only one argument.
3188 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3189 CallerCC == CallingConv::X86_ThisCall))
3192 // Do not sibcall optimize vararg calls unless all arguments are passed via
3194 if (isVarArg && !Outs.empty()) {
3196 // Optimizing for varargs on Win64 is unlikely to be safe without
3197 // additional testing.
3198 if (IsCalleeWin64 || IsCallerWin64)
3201 SmallVector<CCValAssign, 16> ArgLocs;
3202 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3203 DAG.getTarget(), ArgLocs, *DAG.getContext());
3205 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3206 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3207 if (!ArgLocs[i].isRegLoc())
3211 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3212 // stack. Therefore, if it's not used by the call it is not safe to optimize
3213 // this into a sibcall.
3214 bool Unused = false;
3215 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3222 SmallVector<CCValAssign, 16> RVLocs;
3223 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3224 DAG.getTarget(), RVLocs, *DAG.getContext());
3225 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3226 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3227 CCValAssign &VA = RVLocs[i];
3228 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3233 // If the calling conventions do not match, then we'd better make sure the
3234 // results are returned in the same way as what the caller expects.
3236 SmallVector<CCValAssign, 16> RVLocs1;
3237 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3238 DAG.getTarget(), RVLocs1, *DAG.getContext());
3239 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3241 SmallVector<CCValAssign, 16> RVLocs2;
3242 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3243 DAG.getTarget(), RVLocs2, *DAG.getContext());
3244 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3246 if (RVLocs1.size() != RVLocs2.size())
3248 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3249 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3251 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3253 if (RVLocs1[i].isRegLoc()) {
3254 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3257 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3263 // If the callee takes no arguments then go on to check the results of the
3265 if (!Outs.empty()) {
3266 // Check if stack adjustment is needed. For now, do not do this if any
3267 // argument is passed on the stack.
3268 SmallVector<CCValAssign, 16> ArgLocs;
3269 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3270 DAG.getTarget(), ArgLocs, *DAG.getContext());
3272 // Allocate shadow area for Win64
3274 CCInfo.AllocateStack(32, 8);
3276 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3277 if (CCInfo.getNextStackOffset()) {
3278 MachineFunction &MF = DAG.getMachineFunction();
3279 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3282 // Check if the arguments are already laid out in the right way as
3283 // the caller's fixed stack objects.
3284 MachineFrameInfo *MFI = MF.getFrameInfo();
3285 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3286 const X86InstrInfo *TII =
3287 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3288 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3289 CCValAssign &VA = ArgLocs[i];
3290 SDValue Arg = OutVals[i];
3291 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3292 if (VA.getLocInfo() == CCValAssign::Indirect)
3294 if (!VA.isRegLoc()) {
3295 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3302 // If the tailcall address may be in a register, then make sure it's
3303 // possible to register allocate for it. In 32-bit, the call address can
3304 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3305 // callee-saved registers are restored. These happen to be the same
3306 // registers used to pass 'inreg' arguments so watch out for those.
3307 if (!Subtarget->is64Bit() &&
3308 ((!isa<GlobalAddressSDNode>(Callee) &&
3309 !isa<ExternalSymbolSDNode>(Callee)) ||
3310 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3311 unsigned NumInRegs = 0;
3312 // In PIC we need an extra register to formulate the address computation
3314 unsigned MaxInRegs =
3315 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3317 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3318 CCValAssign &VA = ArgLocs[i];
3321 unsigned Reg = VA.getLocReg();
3324 case X86::EAX: case X86::EDX: case X86::ECX:
3325 if (++NumInRegs == MaxInRegs)
3337 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3338 const TargetLibraryInfo *libInfo) const {
3339 return X86::createFastISel(funcInfo, libInfo);
3342 //===----------------------------------------------------------------------===//
3343 // Other Lowering Hooks
3344 //===----------------------------------------------------------------------===//
3346 static bool MayFoldLoad(SDValue Op) {
3347 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3350 static bool MayFoldIntoStore(SDValue Op) {
3351 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3354 static bool isTargetShuffle(unsigned Opcode) {
3356 default: return false;
3357 case X86ISD::PSHUFD:
3358 case X86ISD::PSHUFHW:
3359 case X86ISD::PSHUFLW:
3361 case X86ISD::PALIGNR:
3362 case X86ISD::MOVLHPS:
3363 case X86ISD::MOVLHPD:
3364 case X86ISD::MOVHLPS:
3365 case X86ISD::MOVLPS:
3366 case X86ISD::MOVLPD:
3367 case X86ISD::MOVSHDUP:
3368 case X86ISD::MOVSLDUP:
3369 case X86ISD::MOVDDUP:
3372 case X86ISD::UNPCKL:
3373 case X86ISD::UNPCKH:
3374 case X86ISD::VPERMILP:
3375 case X86ISD::VPERM2X128:
3376 case X86ISD::VPERMI:
3381 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3382 SDValue V1, SelectionDAG &DAG) {
3384 default: llvm_unreachable("Unknown x86 shuffle node");
3385 case X86ISD::MOVSHDUP:
3386 case X86ISD::MOVSLDUP:
3387 case X86ISD::MOVDDUP:
3388 return DAG.getNode(Opc, dl, VT, V1);
3392 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3393 SDValue V1, unsigned TargetMask,
3394 SelectionDAG &DAG) {
3396 default: llvm_unreachable("Unknown x86 shuffle node");
3397 case X86ISD::PSHUFD:
3398 case X86ISD::PSHUFHW:
3399 case X86ISD::PSHUFLW:
3400 case X86ISD::VPERMILP:
3401 case X86ISD::VPERMI:
3402 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3406 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3407 SDValue V1, SDValue V2, unsigned TargetMask,
3408 SelectionDAG &DAG) {
3410 default: llvm_unreachable("Unknown x86 shuffle node");
3411 case X86ISD::PALIGNR:
3413 case X86ISD::VPERM2X128:
3414 return DAG.getNode(Opc, dl, VT, V1, V2,
3415 DAG.getConstant(TargetMask, MVT::i8));
3419 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3420 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3422 default: llvm_unreachable("Unknown x86 shuffle node");
3423 case X86ISD::MOVLHPS:
3424 case X86ISD::MOVLHPD:
3425 case X86ISD::MOVHLPS:
3426 case X86ISD::MOVLPS:
3427 case X86ISD::MOVLPD:
3430 case X86ISD::UNPCKL:
3431 case X86ISD::UNPCKH:
3432 return DAG.getNode(Opc, dl, VT, V1, V2);
3436 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3437 MachineFunction &MF = DAG.getMachineFunction();
3438 const X86RegisterInfo *RegInfo =
3439 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3440 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3441 int ReturnAddrIndex = FuncInfo->getRAIndex();
3443 if (ReturnAddrIndex == 0) {
3444 // Set up a frame object for the return address.
3445 unsigned SlotSize = RegInfo->getSlotSize();
3446 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3449 FuncInfo->setRAIndex(ReturnAddrIndex);
3452 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3455 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3456 bool hasSymbolicDisplacement) {
3457 // Offset should fit into 32 bit immediate field.
3458 if (!isInt<32>(Offset))
3461 // If we don't have a symbolic displacement - we don't have any extra
3463 if (!hasSymbolicDisplacement)
3466 // FIXME: Some tweaks might be needed for medium code model.
3467 if (M != CodeModel::Small && M != CodeModel::Kernel)
3470 // For small code model we assume that latest object is 16MB before end of 31
3471 // bits boundary. We may also accept pretty large negative constants knowing
3472 // that all objects are in the positive half of address space.
3473 if (M == CodeModel::Small && Offset < 16*1024*1024)
3476 // For kernel code model we know that all object resist in the negative half
3477 // of 32bits address space. We may not accept negative offsets, since they may
3478 // be just off and we may accept pretty large positive ones.
3479 if (M == CodeModel::Kernel && Offset > 0)
3485 /// isCalleePop - Determines whether the callee is required to pop its
3486 /// own arguments. Callee pop is necessary to support tail calls.
3487 bool X86::isCalleePop(CallingConv::ID CallingConv,
3488 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3492 switch (CallingConv) {
3495 case CallingConv::X86_StdCall:
3497 case CallingConv::X86_FastCall:
3499 case CallingConv::X86_ThisCall:
3501 case CallingConv::Fast:
3503 case CallingConv::GHC:
3505 case CallingConv::HiPE:
3510 /// \brief Return true if the condition is an unsigned comparison operation.
3511 static bool isX86CCUnsigned(unsigned X86CC) {
3513 default: llvm_unreachable("Invalid integer condition!");
3514 case X86::COND_E: return true;
3515 case X86::COND_G: return false;
3516 case X86::COND_GE: return false;
3517 case X86::COND_L: return false;
3518 case X86::COND_LE: return false;
3519 case X86::COND_NE: return true;
3520 case X86::COND_B: return true;
3521 case X86::COND_A: return true;
3522 case X86::COND_BE: return true;
3523 case X86::COND_AE: return true;
3525 llvm_unreachable("covered switch fell through?!");
3528 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3529 /// specific condition code, returning the condition code and the LHS/RHS of the
3530 /// comparison to make.
3531 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3532 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3534 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3535 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3536 // X > -1 -> X == 0, jump !sign.
3537 RHS = DAG.getConstant(0, RHS.getValueType());
3538 return X86::COND_NS;
3540 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3541 // X < 0 -> X == 0, jump on sign.
3544 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3546 RHS = DAG.getConstant(0, RHS.getValueType());
3547 return X86::COND_LE;
3551 switch (SetCCOpcode) {
3552 default: llvm_unreachable("Invalid integer condition!");
3553 case ISD::SETEQ: return X86::COND_E;
3554 case ISD::SETGT: return X86::COND_G;
3555 case ISD::SETGE: return X86::COND_GE;
3556 case ISD::SETLT: return X86::COND_L;
3557 case ISD::SETLE: return X86::COND_LE;
3558 case ISD::SETNE: return X86::COND_NE;
3559 case ISD::SETULT: return X86::COND_B;
3560 case ISD::SETUGT: return X86::COND_A;
3561 case ISD::SETULE: return X86::COND_BE;
3562 case ISD::SETUGE: return X86::COND_AE;
3566 // First determine if it is required or is profitable to flip the operands.
3568 // If LHS is a foldable load, but RHS is not, flip the condition.
3569 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3570 !ISD::isNON_EXTLoad(RHS.getNode())) {
3571 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3572 std::swap(LHS, RHS);
3575 switch (SetCCOpcode) {
3581 std::swap(LHS, RHS);
3585 // On a floating point condition, the flags are set as follows:
3587 // 0 | 0 | 0 | X > Y
3588 // 0 | 0 | 1 | X < Y
3589 // 1 | 0 | 0 | X == Y
3590 // 1 | 1 | 1 | unordered
3591 switch (SetCCOpcode) {
3592 default: llvm_unreachable("Condcode should be pre-legalized away");
3594 case ISD::SETEQ: return X86::COND_E;
3595 case ISD::SETOLT: // flipped
3597 case ISD::SETGT: return X86::COND_A;
3598 case ISD::SETOLE: // flipped
3600 case ISD::SETGE: return X86::COND_AE;
3601 case ISD::SETUGT: // flipped
3603 case ISD::SETLT: return X86::COND_B;
3604 case ISD::SETUGE: // flipped
3606 case ISD::SETLE: return X86::COND_BE;
3608 case ISD::SETNE: return X86::COND_NE;
3609 case ISD::SETUO: return X86::COND_P;
3610 case ISD::SETO: return X86::COND_NP;
3612 case ISD::SETUNE: return X86::COND_INVALID;
3616 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3617 /// code. Current x86 isa includes the following FP cmov instructions:
3618 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3619 static bool hasFPCMov(unsigned X86CC) {
3635 /// isFPImmLegal - Returns true if the target can instruction select the
3636 /// specified FP immediate natively. If false, the legalizer will
3637 /// materialize the FP immediate as a load from a constant pool.
3638 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3639 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3640 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3646 /// \brief Returns true if it is beneficial to convert a load of a constant
3647 /// to just the constant itself.
3648 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3650 assert(Ty->isIntegerTy());
3652 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3653 if (BitSize == 0 || BitSize > 64)
3658 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3659 /// the specified range (L, H].
3660 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3661 return (Val < 0) || (Val >= Low && Val < Hi);
3664 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3665 /// specified value.
3666 static bool isUndefOrEqual(int Val, int CmpVal) {
3667 return (Val < 0 || Val == CmpVal);
3670 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3671 /// from position Pos and ending in Pos+Size, falls within the specified
3672 /// sequential range (L, L+Pos]. or is undef.
3673 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3674 unsigned Pos, unsigned Size, int Low) {
3675 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3676 if (!isUndefOrEqual(Mask[i], Low))
3681 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3682 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3683 /// the second operand.
3684 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3685 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3686 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3687 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3688 return (Mask[0] < 2 && Mask[1] < 2);
3692 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3693 /// is suitable for input to PSHUFHW.
3694 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3695 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3698 // Lower quadword copied in order or undef.
3699 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3702 // Upper quadword shuffled.
3703 for (unsigned i = 4; i != 8; ++i)
3704 if (!isUndefOrInRange(Mask[i], 4, 8))
3707 if (VT == MVT::v16i16) {
3708 // Lower quadword copied in order or undef.
3709 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3712 // Upper quadword shuffled.
3713 for (unsigned i = 12; i != 16; ++i)
3714 if (!isUndefOrInRange(Mask[i], 12, 16))
3721 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3722 /// is suitable for input to PSHUFLW.
3723 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3724 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3727 // Upper quadword copied in order.
3728 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3731 // Lower quadword shuffled.
3732 for (unsigned i = 0; i != 4; ++i)
3733 if (!isUndefOrInRange(Mask[i], 0, 4))
3736 if (VT == MVT::v16i16) {
3737 // Upper quadword copied in order.
3738 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3741 // Lower quadword shuffled.
3742 for (unsigned i = 8; i != 12; ++i)
3743 if (!isUndefOrInRange(Mask[i], 8, 12))
3750 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3751 /// is suitable for input to PALIGNR.
3752 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3753 const X86Subtarget *Subtarget) {
3754 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3755 (VT.is256BitVector() && !Subtarget->hasInt256()))
3758 unsigned NumElts = VT.getVectorNumElements();
3759 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3760 unsigned NumLaneElts = NumElts/NumLanes;
3762 // Do not handle 64-bit element shuffles with palignr.
3763 if (NumLaneElts == 2)
3766 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3768 for (i = 0; i != NumLaneElts; ++i) {
3773 // Lane is all undef, go to next lane
3774 if (i == NumLaneElts)
3777 int Start = Mask[i+l];
3779 // Make sure its in this lane in one of the sources
3780 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3781 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3784 // If not lane 0, then we must match lane 0
3785 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3788 // Correct second source to be contiguous with first source
3789 if (Start >= (int)NumElts)
3790 Start -= NumElts - NumLaneElts;
3792 // Make sure we're shifting in the right direction.
3793 if (Start <= (int)(i+l))
3798 // Check the rest of the elements to see if they are consecutive.
3799 for (++i; i != NumLaneElts; ++i) {
3800 int Idx = Mask[i+l];
3802 // Make sure its in this lane
3803 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3804 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3807 // If not lane 0, then we must match lane 0
3808 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3811 if (Idx >= (int)NumElts)
3812 Idx -= NumElts - NumLaneElts;
3814 if (!isUndefOrEqual(Idx, Start+i))
3823 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3824 /// the two vector operands have swapped position.
3825 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3826 unsigned NumElems) {
3827 for (unsigned i = 0; i != NumElems; ++i) {
3831 else if (idx < (int)NumElems)
3832 Mask[i] = idx + NumElems;
3834 Mask[i] = idx - NumElems;
3838 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3839 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3840 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3841 /// reverse of what x86 shuffles want.
3842 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3844 unsigned NumElems = VT.getVectorNumElements();
3845 unsigned NumLanes = VT.getSizeInBits()/128;
3846 unsigned NumLaneElems = NumElems/NumLanes;
3848 if (NumLaneElems != 2 && NumLaneElems != 4)
3851 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3852 bool symetricMaskRequired =
3853 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3855 // VSHUFPSY divides the resulting vector into 4 chunks.
3856 // The sources are also splitted into 4 chunks, and each destination
3857 // chunk must come from a different source chunk.
3859 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3860 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3862 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3863 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3865 // VSHUFPDY divides the resulting vector into 4 chunks.
3866 // The sources are also splitted into 4 chunks, and each destination
3867 // chunk must come from a different source chunk.
3869 // SRC1 => X3 X2 X1 X0
3870 // SRC2 => Y3 Y2 Y1 Y0
3872 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3874 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3875 unsigned HalfLaneElems = NumLaneElems/2;
3876 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3877 for (unsigned i = 0; i != NumLaneElems; ++i) {
3878 int Idx = Mask[i+l];
3879 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3880 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3882 // For VSHUFPSY, the mask of the second half must be the same as the
3883 // first but with the appropriate offsets. This works in the same way as
3884 // VPERMILPS works with masks.
3885 if (!symetricMaskRequired || Idx < 0)
3887 if (MaskVal[i] < 0) {
3888 MaskVal[i] = Idx - l;
3891 if ((signed)(Idx - l) != MaskVal[i])
3899 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3900 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3901 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3902 if (!VT.is128BitVector())
3905 unsigned NumElems = VT.getVectorNumElements();
3910 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3911 return isUndefOrEqual(Mask[0], 6) &&
3912 isUndefOrEqual(Mask[1], 7) &&
3913 isUndefOrEqual(Mask[2], 2) &&
3914 isUndefOrEqual(Mask[3], 3);
3917 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3918 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3920 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3921 if (!VT.is128BitVector())
3924 unsigned NumElems = VT.getVectorNumElements();
3929 return isUndefOrEqual(Mask[0], 2) &&
3930 isUndefOrEqual(Mask[1], 3) &&
3931 isUndefOrEqual(Mask[2], 2) &&
3932 isUndefOrEqual(Mask[3], 3);
3935 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3937 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3938 if (!VT.is128BitVector())
3941 unsigned NumElems = VT.getVectorNumElements();
3943 if (NumElems != 2 && NumElems != 4)
3946 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3947 if (!isUndefOrEqual(Mask[i], i + NumElems))
3950 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3951 if (!isUndefOrEqual(Mask[i], i))
3957 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3958 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3959 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3960 if (!VT.is128BitVector())
3963 unsigned NumElems = VT.getVectorNumElements();
3965 if (NumElems != 2 && NumElems != 4)
3968 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3969 if (!isUndefOrEqual(Mask[i], i))
3972 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3973 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3979 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3980 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3981 /// i. e: If all but one element come from the same vector.
3982 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3983 // TODO: Deal with AVX's VINSERTPS
3984 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3987 unsigned CorrectPosV1 = 0;
3988 unsigned CorrectPosV2 = 0;
3989 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3990 if (Mask[i] == -1) {
3998 else if (Mask[i] == i + 4)
4002 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4003 // We have 3 elements (undefs count as elements from any vector) from one
4004 // vector, and one from another.
4011 // Some special combinations that can be optimized.
4014 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4015 SelectionDAG &DAG) {
4016 MVT VT = SVOp->getSimpleValueType(0);
4019 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4022 ArrayRef<int> Mask = SVOp->getMask();
4024 // These are the special masks that may be optimized.
4025 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4026 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4027 bool MatchEvenMask = true;
4028 bool MatchOddMask = true;
4029 for (int i=0; i<8; ++i) {
4030 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4031 MatchEvenMask = false;
4032 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4033 MatchOddMask = false;
4036 if (!MatchEvenMask && !MatchOddMask)
4039 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4041 SDValue Op0 = SVOp->getOperand(0);
4042 SDValue Op1 = SVOp->getOperand(1);
4044 if (MatchEvenMask) {
4045 // Shift the second operand right to 32 bits.
4046 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4047 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4049 // Shift the first operand left to 32 bits.
4050 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4051 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4053 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4054 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4057 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4058 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4059 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4060 bool HasInt256, bool V2IsSplat = false) {
4062 assert(VT.getSizeInBits() >= 128 &&
4063 "Unsupported vector type for unpckl");
4065 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4067 unsigned NumOf256BitLanes;
4068 unsigned NumElts = VT.getVectorNumElements();
4069 if (VT.is256BitVector()) {
4070 if (NumElts != 4 && NumElts != 8 &&
4071 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4074 NumOf256BitLanes = 1;
4075 } else if (VT.is512BitVector()) {
4076 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4077 "Unsupported vector type for unpckh");
4079 NumOf256BitLanes = 2;
4082 NumOf256BitLanes = 1;
4085 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4086 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4088 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4089 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4090 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4091 int BitI = Mask[l256*NumEltsInStride+l+i];
4092 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4093 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4095 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4097 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4105 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4106 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4107 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4108 bool HasInt256, bool V2IsSplat = false) {
4109 assert(VT.getSizeInBits() >= 128 &&
4110 "Unsupported vector type for unpckh");
4112 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4114 unsigned NumOf256BitLanes;
4115 unsigned NumElts = VT.getVectorNumElements();
4116 if (VT.is256BitVector()) {
4117 if (NumElts != 4 && NumElts != 8 &&
4118 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4121 NumOf256BitLanes = 1;
4122 } else if (VT.is512BitVector()) {
4123 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4124 "Unsupported vector type for unpckh");
4126 NumOf256BitLanes = 2;
4129 NumOf256BitLanes = 1;
4132 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4133 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4135 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4136 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4137 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4138 int BitI = Mask[l256*NumEltsInStride+l+i];
4139 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4140 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4142 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4144 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4152 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4153 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4155 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4156 unsigned NumElts = VT.getVectorNumElements();
4157 bool Is256BitVec = VT.is256BitVector();
4159 if (VT.is512BitVector())
4161 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4162 "Unsupported vector type for unpckh");
4164 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4165 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4168 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4169 // FIXME: Need a better way to get rid of this, there's no latency difference
4170 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4171 // the former later. We should also remove the "_undef" special mask.
4172 if (NumElts == 4 && Is256BitVec)
4175 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4176 // independently on 128-bit lanes.
4177 unsigned NumLanes = VT.getSizeInBits()/128;
4178 unsigned NumLaneElts = NumElts/NumLanes;
4180 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4181 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4182 int BitI = Mask[l+i];
4183 int BitI1 = Mask[l+i+1];
4185 if (!isUndefOrEqual(BitI, j))
4187 if (!isUndefOrEqual(BitI1, j))
4195 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4196 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4198 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4199 unsigned NumElts = VT.getVectorNumElements();
4201 if (VT.is512BitVector())
4204 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4205 "Unsupported vector type for unpckh");
4207 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4208 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4211 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4212 // independently on 128-bit lanes.
4213 unsigned NumLanes = VT.getSizeInBits()/128;
4214 unsigned NumLaneElts = NumElts/NumLanes;
4216 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4217 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4218 int BitI = Mask[l+i];
4219 int BitI1 = Mask[l+i+1];
4220 if (!isUndefOrEqual(BitI, j))
4222 if (!isUndefOrEqual(BitI1, j))
4229 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4230 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4231 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4232 if (!VT.is512BitVector())
4235 unsigned NumElts = VT.getVectorNumElements();
4236 unsigned HalfSize = NumElts/2;
4237 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4238 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4243 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4244 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4252 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4253 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4254 /// MOVSD, and MOVD, i.e. setting the lowest element.
4255 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4256 if (VT.getVectorElementType().getSizeInBits() < 32)
4258 if (!VT.is128BitVector())
4261 unsigned NumElts = VT.getVectorNumElements();
4263 if (!isUndefOrEqual(Mask[0], NumElts))
4266 for (unsigned i = 1; i != NumElts; ++i)
4267 if (!isUndefOrEqual(Mask[i], i))
4273 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4274 /// as permutations between 128-bit chunks or halves. As an example: this
4276 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4277 /// The first half comes from the second half of V1 and the second half from the
4278 /// the second half of V2.
4279 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4280 if (!HasFp256 || !VT.is256BitVector())
4283 // The shuffle result is divided into half A and half B. In total the two
4284 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4285 // B must come from C, D, E or F.
4286 unsigned HalfSize = VT.getVectorNumElements()/2;
4287 bool MatchA = false, MatchB = false;
4289 // Check if A comes from one of C, D, E, F.
4290 for (unsigned Half = 0; Half != 4; ++Half) {
4291 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4297 // Check if B comes from one of C, D, E, F.
4298 for (unsigned Half = 0; Half != 4; ++Half) {
4299 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4305 return MatchA && MatchB;
4308 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4309 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4310 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4311 MVT VT = SVOp->getSimpleValueType(0);
4313 unsigned HalfSize = VT.getVectorNumElements()/2;
4315 unsigned FstHalf = 0, SndHalf = 0;
4316 for (unsigned i = 0; i < HalfSize; ++i) {
4317 if (SVOp->getMaskElt(i) > 0) {
4318 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4322 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4323 if (SVOp->getMaskElt(i) > 0) {
4324 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4329 return (FstHalf | (SndHalf << 4));
4332 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4333 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4334 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4338 unsigned NumElts = VT.getVectorNumElements();
4340 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4341 for (unsigned i = 0; i != NumElts; ++i) {
4344 Imm8 |= Mask[i] << (i*2);
4349 unsigned LaneSize = 4;
4350 SmallVector<int, 4> MaskVal(LaneSize, -1);
4352 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4353 for (unsigned i = 0; i != LaneSize; ++i) {
4354 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4358 if (MaskVal[i] < 0) {
4359 MaskVal[i] = Mask[i+l] - l;
4360 Imm8 |= MaskVal[i] << (i*2);
4363 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4370 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4371 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4372 /// Note that VPERMIL mask matching is different depending whether theunderlying
4373 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4374 /// to the same elements of the low, but to the higher half of the source.
4375 /// In VPERMILPD the two lanes could be shuffled independently of each other
4376 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4377 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4378 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4379 if (VT.getSizeInBits() < 256 || EltSize < 32)
4381 bool symetricMaskRequired = (EltSize == 32);
4382 unsigned NumElts = VT.getVectorNumElements();
4384 unsigned NumLanes = VT.getSizeInBits()/128;
4385 unsigned LaneSize = NumElts/NumLanes;
4386 // 2 or 4 elements in one lane
4388 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4389 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4390 for (unsigned i = 0; i != LaneSize; ++i) {
4391 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4393 if (symetricMaskRequired) {
4394 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4395 ExpectedMaskVal[i] = Mask[i+l] - l;
4398 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4406 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4407 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4408 /// element of vector 2 and the other elements to come from vector 1 in order.
4409 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4410 bool V2IsSplat = false, bool V2IsUndef = false) {
4411 if (!VT.is128BitVector())
4414 unsigned NumOps = VT.getVectorNumElements();
4415 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4418 if (!isUndefOrEqual(Mask[0], 0))
4421 for (unsigned i = 1; i != NumOps; ++i)
4422 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4423 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4424 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4430 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4431 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4432 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4433 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4434 const X86Subtarget *Subtarget) {
4435 if (!Subtarget->hasSSE3())
4438 unsigned NumElems = VT.getVectorNumElements();
4440 if ((VT.is128BitVector() && NumElems != 4) ||
4441 (VT.is256BitVector() && NumElems != 8) ||
4442 (VT.is512BitVector() && NumElems != 16))
4445 // "i+1" is the value the indexed mask element must have
4446 for (unsigned i = 0; i != NumElems; i += 2)
4447 if (!isUndefOrEqual(Mask[i], i+1) ||
4448 !isUndefOrEqual(Mask[i+1], i+1))
4454 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4455 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4456 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4457 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4458 const X86Subtarget *Subtarget) {
4459 if (!Subtarget->hasSSE3())
4462 unsigned NumElems = VT.getVectorNumElements();
4464 if ((VT.is128BitVector() && NumElems != 4) ||
4465 (VT.is256BitVector() && NumElems != 8) ||
4466 (VT.is512BitVector() && NumElems != 16))
4469 // "i" is the value the indexed mask element must have
4470 for (unsigned i = 0; i != NumElems; i += 2)
4471 if (!isUndefOrEqual(Mask[i], i) ||
4472 !isUndefOrEqual(Mask[i+1], i))
4478 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4479 /// specifies a shuffle of elements that is suitable for input to 256-bit
4480 /// version of MOVDDUP.
4481 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4482 if (!HasFp256 || !VT.is256BitVector())
4485 unsigned NumElts = VT.getVectorNumElements();
4489 for (unsigned i = 0; i != NumElts/2; ++i)
4490 if (!isUndefOrEqual(Mask[i], 0))
4492 for (unsigned i = NumElts/2; i != NumElts; ++i)
4493 if (!isUndefOrEqual(Mask[i], NumElts/2))
4498 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4499 /// specifies a shuffle of elements that is suitable for input to 128-bit
4500 /// version of MOVDDUP.
4501 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4502 if (!VT.is128BitVector())
4505 unsigned e = VT.getVectorNumElements() / 2;
4506 for (unsigned i = 0; i != e; ++i)
4507 if (!isUndefOrEqual(Mask[i], i))
4509 for (unsigned i = 0; i != e; ++i)
4510 if (!isUndefOrEqual(Mask[e+i], i))
4515 /// isVEXTRACTIndex - Return true if the specified
4516 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4517 /// suitable for instruction that extract 128 or 256 bit vectors
4518 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4519 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4520 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4523 // The index should be aligned on a vecWidth-bit boundary.
4525 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4527 MVT VT = N->getSimpleValueType(0);
4528 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4529 bool Result = (Index * ElSize) % vecWidth == 0;
4534 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4535 /// operand specifies a subvector insert that is suitable for input to
4536 /// insertion of 128 or 256-bit subvectors
4537 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4538 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4539 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4541 // The index should be aligned on a vecWidth-bit boundary.
4543 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4545 MVT VT = N->getSimpleValueType(0);
4546 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4547 bool Result = (Index * ElSize) % vecWidth == 0;
4552 bool X86::isVINSERT128Index(SDNode *N) {
4553 return isVINSERTIndex(N, 128);
4556 bool X86::isVINSERT256Index(SDNode *N) {
4557 return isVINSERTIndex(N, 256);
4560 bool X86::isVEXTRACT128Index(SDNode *N) {
4561 return isVEXTRACTIndex(N, 128);
4564 bool X86::isVEXTRACT256Index(SDNode *N) {
4565 return isVEXTRACTIndex(N, 256);
4568 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4569 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4570 /// Handles 128-bit and 256-bit.
4571 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4572 MVT VT = N->getSimpleValueType(0);
4574 assert((VT.getSizeInBits() >= 128) &&
4575 "Unsupported vector type for PSHUF/SHUFP");
4577 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4578 // independently on 128-bit lanes.
4579 unsigned NumElts = VT.getVectorNumElements();
4580 unsigned NumLanes = VT.getSizeInBits()/128;
4581 unsigned NumLaneElts = NumElts/NumLanes;
4583 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4584 "Only supports 2, 4 or 8 elements per lane");
4586 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4588 for (unsigned i = 0; i != NumElts; ++i) {
4589 int Elt = N->getMaskElt(i);
4590 if (Elt < 0) continue;
4591 Elt &= NumLaneElts - 1;
4592 unsigned ShAmt = (i << Shift) % 8;
4593 Mask |= Elt << ShAmt;
4599 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4600 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4601 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4602 MVT VT = N->getSimpleValueType(0);
4604 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4605 "Unsupported vector type for PSHUFHW");
4607 unsigned NumElts = VT.getVectorNumElements();
4610 for (unsigned l = 0; l != NumElts; l += 8) {
4611 // 8 nodes per lane, but we only care about the last 4.
4612 for (unsigned i = 0; i < 4; ++i) {
4613 int Elt = N->getMaskElt(l+i+4);
4614 if (Elt < 0) continue;
4615 Elt &= 0x3; // only 2-bits.
4616 Mask |= Elt << (i * 2);
4623 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4624 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4625 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4626 MVT VT = N->getSimpleValueType(0);
4628 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4629 "Unsupported vector type for PSHUFHW");
4631 unsigned NumElts = VT.getVectorNumElements();
4634 for (unsigned l = 0; l != NumElts; l += 8) {
4635 // 8 nodes per lane, but we only care about the first 4.
4636 for (unsigned i = 0; i < 4; ++i) {
4637 int Elt = N->getMaskElt(l+i);
4638 if (Elt < 0) continue;
4639 Elt &= 0x3; // only 2-bits
4640 Mask |= Elt << (i * 2);
4647 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4648 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4649 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4650 MVT VT = SVOp->getSimpleValueType(0);
4651 unsigned EltSize = VT.is512BitVector() ? 1 :
4652 VT.getVectorElementType().getSizeInBits() >> 3;
4654 unsigned NumElts = VT.getVectorNumElements();
4655 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4656 unsigned NumLaneElts = NumElts/NumLanes;
4660 for (i = 0; i != NumElts; ++i) {
4661 Val = SVOp->getMaskElt(i);
4665 if (Val >= (int)NumElts)
4666 Val -= NumElts - NumLaneElts;
4668 assert(Val - i > 0 && "PALIGNR imm should be positive");
4669 return (Val - i) * EltSize;
4672 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4673 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4674 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4675 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4678 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4680 MVT VecVT = N->getOperand(0).getSimpleValueType();
4681 MVT ElVT = VecVT.getVectorElementType();
4683 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4684 return Index / NumElemsPerChunk;
4687 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4688 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4689 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4690 llvm_unreachable("Illegal insert subvector for VINSERT");
4693 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4695 MVT VecVT = N->getSimpleValueType(0);
4696 MVT ElVT = VecVT.getVectorElementType();
4698 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4699 return Index / NumElemsPerChunk;
4702 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4703 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4704 /// and VINSERTI128 instructions.
4705 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4706 return getExtractVEXTRACTImmediate(N, 128);
4709 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4710 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4711 /// and VINSERTI64x4 instructions.
4712 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4713 return getExtractVEXTRACTImmediate(N, 256);
4716 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4717 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4718 /// and VINSERTI128 instructions.
4719 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4720 return getInsertVINSERTImmediate(N, 128);
4723 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4724 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4725 /// and VINSERTI64x4 instructions.
4726 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4727 return getInsertVINSERTImmediate(N, 256);
4730 /// isZero - Returns true if Elt is a constant integer zero
4731 static bool isZero(SDValue V) {
4732 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4733 return C && C->isNullValue();
4736 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4738 bool X86::isZeroNode(SDValue Elt) {
4741 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4742 return CFP->getValueAPF().isPosZero();
4746 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4747 /// their permute mask.
4748 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4749 SelectionDAG &DAG) {
4750 MVT VT = SVOp->getSimpleValueType(0);
4751 unsigned NumElems = VT.getVectorNumElements();
4752 SmallVector<int, 8> MaskVec;
4754 for (unsigned i = 0; i != NumElems; ++i) {
4755 int Idx = SVOp->getMaskElt(i);
4757 if (Idx < (int)NumElems)
4762 MaskVec.push_back(Idx);
4764 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4765 SVOp->getOperand(0), &MaskVec[0]);
4768 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4769 /// match movhlps. The lower half elements should come from upper half of
4770 /// V1 (and in order), and the upper half elements should come from the upper
4771 /// half of V2 (and in order).
4772 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4773 if (!VT.is128BitVector())
4775 if (VT.getVectorNumElements() != 4)
4777 for (unsigned i = 0, e = 2; i != e; ++i)
4778 if (!isUndefOrEqual(Mask[i], i+2))
4780 for (unsigned i = 2; i != 4; ++i)
4781 if (!isUndefOrEqual(Mask[i], i+4))
4786 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4787 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4789 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4790 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4792 N = N->getOperand(0).getNode();
4793 if (!ISD::isNON_EXTLoad(N))
4796 *LD = cast<LoadSDNode>(N);
4800 // Test whether the given value is a vector value which will be legalized
4802 static bool WillBeConstantPoolLoad(SDNode *N) {
4803 if (N->getOpcode() != ISD::BUILD_VECTOR)
4806 // Check for any non-constant elements.
4807 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4808 switch (N->getOperand(i).getNode()->getOpcode()) {
4810 case ISD::ConstantFP:
4817 // Vectors of all-zeros and all-ones are materialized with special
4818 // instructions rather than being loaded.
4819 return !ISD::isBuildVectorAllZeros(N) &&
4820 !ISD::isBuildVectorAllOnes(N);
4823 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4824 /// match movlp{s|d}. The lower half elements should come from lower half of
4825 /// V1 (and in order), and the upper half elements should come from the upper
4826 /// half of V2 (and in order). And since V1 will become the source of the
4827 /// MOVLP, it must be either a vector load or a scalar load to vector.
4828 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4829 ArrayRef<int> Mask, MVT VT) {
4830 if (!VT.is128BitVector())
4833 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4835 // Is V2 is a vector load, don't do this transformation. We will try to use
4836 // load folding shufps op.
4837 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4840 unsigned NumElems = VT.getVectorNumElements();
4842 if (NumElems != 2 && NumElems != 4)
4844 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4845 if (!isUndefOrEqual(Mask[i], i))
4847 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4848 if (!isUndefOrEqual(Mask[i], i+NumElems))
4853 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4855 static bool isSplatVector(SDNode *N) {
4856 if (N->getOpcode() != ISD::BUILD_VECTOR)
4859 SDValue SplatValue = N->getOperand(0);
4860 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4861 if (N->getOperand(i) != SplatValue)
4866 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4867 /// to an zero vector.
4868 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4869 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4870 SDValue V1 = N->getOperand(0);
4871 SDValue V2 = N->getOperand(1);
4872 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4873 for (unsigned i = 0; i != NumElems; ++i) {
4874 int Idx = N->getMaskElt(i);
4875 if (Idx >= (int)NumElems) {
4876 unsigned Opc = V2.getOpcode();
4877 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4879 if (Opc != ISD::BUILD_VECTOR ||
4880 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4882 } else if (Idx >= 0) {
4883 unsigned Opc = V1.getOpcode();
4884 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4886 if (Opc != ISD::BUILD_VECTOR ||
4887 !X86::isZeroNode(V1.getOperand(Idx)))
4894 /// getZeroVector - Returns a vector of specified type with all zero elements.
4896 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4897 SelectionDAG &DAG, SDLoc dl) {
4898 assert(VT.isVector() && "Expected a vector type");
4900 // Always build SSE zero vectors as <4 x i32> bitcasted
4901 // to their dest type. This ensures they get CSE'd.
4903 if (VT.is128BitVector()) { // SSE
4904 if (Subtarget->hasSSE2()) { // SSE2
4905 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4906 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4908 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4909 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4911 } else if (VT.is256BitVector()) { // AVX
4912 if (Subtarget->hasInt256()) { // AVX2
4913 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4914 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4915 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4917 // 256-bit logic and arithmetic instructions in AVX are all
4918 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4919 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4920 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4921 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4923 } else if (VT.is512BitVector()) { // AVX-512
4924 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4925 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4926 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4927 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4928 } else if (VT.getScalarType() == MVT::i1) {
4929 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4930 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4931 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4932 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4934 llvm_unreachable("Unexpected vector type");
4936 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4939 /// getOnesVector - Returns a vector of specified type with all bits set.
4940 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4941 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4942 /// Then bitcast to their original type, ensuring they get CSE'd.
4943 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4945 assert(VT.isVector() && "Expected a vector type");
4947 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4949 if (VT.is256BitVector()) {
4950 if (HasInt256) { // AVX2
4951 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4952 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4954 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4955 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4957 } else if (VT.is128BitVector()) {
4958 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4960 llvm_unreachable("Unexpected vector type");
4962 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4965 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4966 /// that point to V2 points to its first element.
4967 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4968 for (unsigned i = 0; i != NumElems; ++i) {
4969 if (Mask[i] > (int)NumElems) {
4975 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4976 /// operation of specified width.
4977 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4979 unsigned NumElems = VT.getVectorNumElements();
4980 SmallVector<int, 8> Mask;
4981 Mask.push_back(NumElems);
4982 for (unsigned i = 1; i != NumElems; ++i)
4984 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4987 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4988 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4990 unsigned NumElems = VT.getVectorNumElements();
4991 SmallVector<int, 8> Mask;
4992 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4994 Mask.push_back(i + NumElems);
4996 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4999 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5000 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5002 unsigned NumElems = VT.getVectorNumElements();
5003 SmallVector<int, 8> Mask;
5004 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5005 Mask.push_back(i + Half);
5006 Mask.push_back(i + NumElems + Half);
5008 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5011 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5012 // a generic shuffle instruction because the target has no such instructions.
5013 // Generate shuffles which repeat i16 and i8 several times until they can be
5014 // represented by v4f32 and then be manipulated by target suported shuffles.
5015 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5016 MVT VT = V.getSimpleValueType();
5017 int NumElems = VT.getVectorNumElements();
5020 while (NumElems > 4) {
5021 if (EltNo < NumElems/2) {
5022 V = getUnpackl(DAG, dl, VT, V, V);
5024 V = getUnpackh(DAG, dl, VT, V, V);
5025 EltNo -= NumElems/2;
5032 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5033 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5034 MVT VT = V.getSimpleValueType();
5037 if (VT.is128BitVector()) {
5038 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5039 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5040 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5042 } else if (VT.is256BitVector()) {
5043 // To use VPERMILPS to splat scalars, the second half of indicies must
5044 // refer to the higher part, which is a duplication of the lower one,
5045 // because VPERMILPS can only handle in-lane permutations.
5046 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5047 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5049 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5050 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5053 llvm_unreachable("Vector size not supported");
5055 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5058 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5059 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5060 MVT SrcVT = SV->getSimpleValueType(0);
5061 SDValue V1 = SV->getOperand(0);
5064 int EltNo = SV->getSplatIndex();
5065 int NumElems = SrcVT.getVectorNumElements();
5066 bool Is256BitVec = SrcVT.is256BitVector();
5068 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5069 "Unknown how to promote splat for type");
5071 // Extract the 128-bit part containing the splat element and update
5072 // the splat element index when it refers to the higher register.
5074 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5075 if (EltNo >= NumElems/2)
5076 EltNo -= NumElems/2;
5079 // All i16 and i8 vector types can't be used directly by a generic shuffle
5080 // instruction because the target has no such instruction. Generate shuffles
5081 // which repeat i16 and i8 several times until they fit in i32, and then can
5082 // be manipulated by target suported shuffles.
5083 MVT EltVT = SrcVT.getVectorElementType();
5084 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5085 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5087 // Recreate the 256-bit vector and place the same 128-bit vector
5088 // into the low and high part. This is necessary because we want
5089 // to use VPERM* to shuffle the vectors
5091 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5094 return getLegalSplat(DAG, V1, EltNo);
5097 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5098 /// vector of zero or undef vector. This produces a shuffle where the low
5099 /// element of V2 is swizzled into the zero/undef vector, landing at element
5100 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5101 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5103 const X86Subtarget *Subtarget,
5104 SelectionDAG &DAG) {
5105 MVT VT = V2.getSimpleValueType();
5107 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5108 unsigned NumElems = VT.getVectorNumElements();
5109 SmallVector<int, 16> MaskVec;
5110 for (unsigned i = 0; i != NumElems; ++i)
5111 // If this is the insertion idx, put the low elt of V2 here.
5112 MaskVec.push_back(i == Idx ? NumElems : i);
5113 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5116 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5117 /// target specific opcode. Returns true if the Mask could be calculated.
5118 /// Sets IsUnary to true if only uses one source.
5119 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5120 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5121 unsigned NumElems = VT.getVectorNumElements();
5125 switch(N->getOpcode()) {
5127 ImmN = N->getOperand(N->getNumOperands()-1);
5128 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5130 case X86ISD::UNPCKH:
5131 DecodeUNPCKHMask(VT, Mask);
5133 case X86ISD::UNPCKL:
5134 DecodeUNPCKLMask(VT, Mask);
5136 case X86ISD::MOVHLPS:
5137 DecodeMOVHLPSMask(NumElems, Mask);
5139 case X86ISD::MOVLHPS:
5140 DecodeMOVLHPSMask(NumElems, Mask);
5142 case X86ISD::PALIGNR:
5143 ImmN = N->getOperand(N->getNumOperands()-1);
5144 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5146 case X86ISD::PSHUFD:
5147 case X86ISD::VPERMILP:
5148 ImmN = N->getOperand(N->getNumOperands()-1);
5149 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5152 case X86ISD::PSHUFHW:
5153 ImmN = N->getOperand(N->getNumOperands()-1);
5154 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5157 case X86ISD::PSHUFLW:
5158 ImmN = N->getOperand(N->getNumOperands()-1);
5159 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5162 case X86ISD::VPERMI:
5163 ImmN = N->getOperand(N->getNumOperands()-1);
5164 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5168 case X86ISD::MOVSD: {
5169 // The index 0 always comes from the first element of the second source,
5170 // this is why MOVSS and MOVSD are used in the first place. The other
5171 // elements come from the other positions of the first source vector
5172 Mask.push_back(NumElems);
5173 for (unsigned i = 1; i != NumElems; ++i) {
5178 case X86ISD::VPERM2X128:
5179 ImmN = N->getOperand(N->getNumOperands()-1);
5180 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5181 if (Mask.empty()) return false;
5183 case X86ISD::MOVDDUP:
5184 case X86ISD::MOVLHPD:
5185 case X86ISD::MOVLPD:
5186 case X86ISD::MOVLPS:
5187 case X86ISD::MOVSHDUP:
5188 case X86ISD::MOVSLDUP:
5189 // Not yet implemented
5191 default: llvm_unreachable("unknown target shuffle node");
5197 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5198 /// element of the result of the vector shuffle.
5199 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5202 return SDValue(); // Limit search depth.
5204 SDValue V = SDValue(N, 0);
5205 EVT VT = V.getValueType();
5206 unsigned Opcode = V.getOpcode();
5208 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5209 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5210 int Elt = SV->getMaskElt(Index);
5213 return DAG.getUNDEF(VT.getVectorElementType());
5215 unsigned NumElems = VT.getVectorNumElements();
5216 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5217 : SV->getOperand(1);
5218 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5221 // Recurse into target specific vector shuffles to find scalars.
5222 if (isTargetShuffle(Opcode)) {
5223 MVT ShufVT = V.getSimpleValueType();
5224 unsigned NumElems = ShufVT.getVectorNumElements();
5225 SmallVector<int, 16> ShuffleMask;
5228 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5231 int Elt = ShuffleMask[Index];
5233 return DAG.getUNDEF(ShufVT.getVectorElementType());
5235 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5237 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5241 // Actual nodes that may contain scalar elements
5242 if (Opcode == ISD::BITCAST) {
5243 V = V.getOperand(0);
5244 EVT SrcVT = V.getValueType();
5245 unsigned NumElems = VT.getVectorNumElements();
5247 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5251 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5252 return (Index == 0) ? V.getOperand(0)
5253 : DAG.getUNDEF(VT.getVectorElementType());
5255 if (V.getOpcode() == ISD::BUILD_VECTOR)
5256 return V.getOperand(Index);
5261 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5262 /// shuffle operation which come from a consecutively from a zero. The
5263 /// search can start in two different directions, from left or right.
5264 /// We count undefs as zeros until PreferredNum is reached.
5265 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5266 unsigned NumElems, bool ZerosFromLeft,
5268 unsigned PreferredNum = -1U) {
5269 unsigned NumZeros = 0;
5270 for (unsigned i = 0; i != NumElems; ++i) {
5271 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5272 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5276 if (X86::isZeroNode(Elt))
5278 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5279 NumZeros = std::min(NumZeros + 1, PreferredNum);
5287 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5288 /// correspond consecutively to elements from one of the vector operands,
5289 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5291 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5292 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5293 unsigned NumElems, unsigned &OpNum) {
5294 bool SeenV1 = false;
5295 bool SeenV2 = false;
5297 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5298 int Idx = SVOp->getMaskElt(i);
5299 // Ignore undef indicies
5303 if (Idx < (int)NumElems)
5308 // Only accept consecutive elements from the same vector
5309 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5313 OpNum = SeenV1 ? 0 : 1;
5317 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5318 /// logical left shift of a vector.
5319 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5320 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5322 SVOp->getSimpleValueType(0).getVectorNumElements();
5323 unsigned NumZeros = getNumOfConsecutiveZeros(
5324 SVOp, NumElems, false /* check zeros from right */, DAG,
5325 SVOp->getMaskElt(0));
5331 // Considering the elements in the mask that are not consecutive zeros,
5332 // check if they consecutively come from only one of the source vectors.
5334 // V1 = {X, A, B, C} 0
5336 // vector_shuffle V1, V2 <1, 2, 3, X>
5338 if (!isShuffleMaskConsecutive(SVOp,
5339 0, // Mask Start Index
5340 NumElems-NumZeros, // Mask End Index(exclusive)
5341 NumZeros, // Where to start looking in the src vector
5342 NumElems, // Number of elements in vector
5343 OpSrc)) // Which source operand ?
5348 ShVal = SVOp->getOperand(OpSrc);
5352 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5353 /// logical left shift of a vector.
5354 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5355 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5357 SVOp->getSimpleValueType(0).getVectorNumElements();
5358 unsigned NumZeros = getNumOfConsecutiveZeros(
5359 SVOp, NumElems, true /* check zeros from left */, DAG,
5360 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5366 // Considering the elements in the mask that are not consecutive zeros,
5367 // check if they consecutively come from only one of the source vectors.
5369 // 0 { A, B, X, X } = V2
5371 // vector_shuffle V1, V2 <X, X, 4, 5>
5373 if (!isShuffleMaskConsecutive(SVOp,
5374 NumZeros, // Mask Start Index
5375 NumElems, // Mask End Index(exclusive)
5376 0, // Where to start looking in the src vector
5377 NumElems, // Number of elements in vector
5378 OpSrc)) // Which source operand ?
5383 ShVal = SVOp->getOperand(OpSrc);
5387 /// isVectorShift - Returns true if the shuffle can be implemented as a
5388 /// logical left or right shift of a vector.
5389 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5390 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5391 // Although the logic below support any bitwidth size, there are no
5392 // shift instructions which handle more than 128-bit vectors.
5393 if (!SVOp->getSimpleValueType(0).is128BitVector())
5396 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5397 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5403 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5405 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5406 unsigned NumNonZero, unsigned NumZero,
5408 const X86Subtarget* Subtarget,
5409 const TargetLowering &TLI) {
5416 for (unsigned i = 0; i < 16; ++i) {
5417 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5418 if (ThisIsNonZero && First) {
5420 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5422 V = DAG.getUNDEF(MVT::v8i16);
5427 SDValue ThisElt, LastElt;
5428 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5429 if (LastIsNonZero) {
5430 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5431 MVT::i16, Op.getOperand(i-1));
5433 if (ThisIsNonZero) {
5434 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5435 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5436 ThisElt, DAG.getConstant(8, MVT::i8));
5438 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5442 if (ThisElt.getNode())
5443 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5444 DAG.getIntPtrConstant(i/2));
5448 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5451 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5453 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5454 unsigned NumNonZero, unsigned NumZero,
5456 const X86Subtarget* Subtarget,
5457 const TargetLowering &TLI) {
5464 for (unsigned i = 0; i < 8; ++i) {
5465 bool isNonZero = (NonZeros & (1 << i)) != 0;
5469 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5471 V = DAG.getUNDEF(MVT::v8i16);
5474 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5475 MVT::v8i16, V, Op.getOperand(i),
5476 DAG.getIntPtrConstant(i));
5483 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5484 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5485 unsigned NonZeros, unsigned NumNonZero,
5486 unsigned NumZero, SelectionDAG &DAG,
5487 const X86Subtarget *Subtarget,
5488 const TargetLowering &TLI) {
5489 // We know there's at least one non-zero element
5490 unsigned FirstNonZeroIdx = 0;
5491 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5492 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5493 X86::isZeroNode(FirstNonZero)) {
5495 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5498 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5499 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5502 SDValue V = FirstNonZero.getOperand(0);
5503 MVT VVT = V.getSimpleValueType();
5504 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5507 unsigned FirstNonZeroDst =
5508 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5509 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5510 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5511 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5513 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5514 SDValue Elem = Op.getOperand(Idx);
5515 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5518 // TODO: What else can be here? Deal with it.
5519 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5522 // TODO: Some optimizations are still possible here
5523 // ex: Getting one element from a vector, and the rest from another.
5524 if (Elem.getOperand(0) != V)
5527 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5530 else if (IncorrectIdx == -1U) {
5534 // There was already one element with an incorrect index.
5535 // We can't optimize this case to an insertps.
5539 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5541 EVT VT = Op.getSimpleValueType();
5542 unsigned ElementMoveMask = 0;
5543 if (IncorrectIdx == -1U)
5544 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5546 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5548 SDValue InsertpsMask =
5549 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5550 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5556 /// getVShift - Return a vector logical shift node.
5558 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5559 unsigned NumBits, SelectionDAG &DAG,
5560 const TargetLowering &TLI, SDLoc dl) {
5561 assert(VT.is128BitVector() && "Unknown type for VShift");
5562 EVT ShVT = MVT::v2i64;
5563 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5564 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5565 return DAG.getNode(ISD::BITCAST, dl, VT,
5566 DAG.getNode(Opc, dl, ShVT, SrcOp,
5567 DAG.getConstant(NumBits,
5568 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5572 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5574 // Check if the scalar load can be widened into a vector load. And if
5575 // the address is "base + cst" see if the cst can be "absorbed" into
5576 // the shuffle mask.
5577 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5578 SDValue Ptr = LD->getBasePtr();
5579 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5581 EVT PVT = LD->getValueType(0);
5582 if (PVT != MVT::i32 && PVT != MVT::f32)
5587 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5588 FI = FINode->getIndex();
5590 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5591 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5592 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5593 Offset = Ptr.getConstantOperandVal(1);
5594 Ptr = Ptr.getOperand(0);
5599 // FIXME: 256-bit vector instructions don't require a strict alignment,
5600 // improve this code to support it better.
5601 unsigned RequiredAlign = VT.getSizeInBits()/8;
5602 SDValue Chain = LD->getChain();
5603 // Make sure the stack object alignment is at least 16 or 32.
5604 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5605 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5606 if (MFI->isFixedObjectIndex(FI)) {
5607 // Can't change the alignment. FIXME: It's possible to compute
5608 // the exact stack offset and reference FI + adjust offset instead.
5609 // If someone *really* cares about this. That's the way to implement it.
5612 MFI->setObjectAlignment(FI, RequiredAlign);
5616 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5617 // Ptr + (Offset & ~15).
5620 if ((Offset % RequiredAlign) & 3)
5622 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5624 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5625 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5627 int EltNo = (Offset - StartOffset) >> 2;
5628 unsigned NumElems = VT.getVectorNumElements();
5630 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5631 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5632 LD->getPointerInfo().getWithOffset(StartOffset),
5633 false, false, false, 0);
5635 SmallVector<int, 8> Mask;
5636 for (unsigned i = 0; i != NumElems; ++i)
5637 Mask.push_back(EltNo);
5639 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5645 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5646 /// vector of type 'VT', see if the elements can be replaced by a single large
5647 /// load which has the same value as a build_vector whose operands are 'elts'.
5649 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5651 /// FIXME: we'd also like to handle the case where the last elements are zero
5652 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5653 /// There's even a handy isZeroNode for that purpose.
5654 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5655 SDLoc &DL, SelectionDAG &DAG,
5656 bool isAfterLegalize) {
5657 EVT EltVT = VT.getVectorElementType();
5658 unsigned NumElems = Elts.size();
5660 LoadSDNode *LDBase = nullptr;
5661 unsigned LastLoadedElt = -1U;
5663 // For each element in the initializer, see if we've found a load or an undef.
5664 // If we don't find an initial load element, or later load elements are
5665 // non-consecutive, bail out.
5666 for (unsigned i = 0; i < NumElems; ++i) {
5667 SDValue Elt = Elts[i];
5669 if (!Elt.getNode() ||
5670 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5673 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5675 LDBase = cast<LoadSDNode>(Elt.getNode());
5679 if (Elt.getOpcode() == ISD::UNDEF)
5682 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5683 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5688 // If we have found an entire vector of loads and undefs, then return a large
5689 // load of the entire vector width starting at the base pointer. If we found
5690 // consecutive loads for the low half, generate a vzext_load node.
5691 if (LastLoadedElt == NumElems - 1) {
5693 if (isAfterLegalize &&
5694 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5697 SDValue NewLd = SDValue();
5699 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5700 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5701 LDBase->getPointerInfo(),
5702 LDBase->isVolatile(), LDBase->isNonTemporal(),
5703 LDBase->isInvariant(), 0);
5704 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5705 LDBase->getPointerInfo(),
5706 LDBase->isVolatile(), LDBase->isNonTemporal(),
5707 LDBase->isInvariant(), LDBase->getAlignment());
5709 if (LDBase->hasAnyUseOfValue(1)) {
5710 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5712 SDValue(NewLd.getNode(), 1));
5713 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5714 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5715 SDValue(NewLd.getNode(), 1));
5720 if (NumElems == 4 && LastLoadedElt == 1 &&
5721 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5722 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5723 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5725 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5726 LDBase->getPointerInfo(),
5727 LDBase->getAlignment(),
5728 false/*isVolatile*/, true/*ReadMem*/,
5731 // Make sure the newly-created LOAD is in the same position as LDBase in
5732 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5733 // update uses of LDBase's output chain to use the TokenFactor.
5734 if (LDBase->hasAnyUseOfValue(1)) {
5735 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5736 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5737 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5738 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5739 SDValue(ResNode.getNode(), 1));
5742 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5747 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5748 /// to generate a splat value for the following cases:
5749 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5750 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5751 /// a scalar load, or a constant.
5752 /// The VBROADCAST node is returned when a pattern is found,
5753 /// or SDValue() otherwise.
5754 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5755 SelectionDAG &DAG) {
5756 if (!Subtarget->hasFp256())
5759 MVT VT = Op.getSimpleValueType();
5762 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5763 "Unsupported vector type for broadcast.");
5768 switch (Op.getOpcode()) {
5770 // Unknown pattern found.
5773 case ISD::BUILD_VECTOR: {
5774 // The BUILD_VECTOR node must be a splat.
5775 if (!isSplatVector(Op.getNode()))
5778 Ld = Op.getOperand(0);
5779 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5780 Ld.getOpcode() == ISD::ConstantFP);
5782 // The suspected load node has several users. Make sure that all
5783 // of its users are from the BUILD_VECTOR node.
5784 // Constants may have multiple users.
5785 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5790 case ISD::VECTOR_SHUFFLE: {
5791 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5793 // Shuffles must have a splat mask where the first element is
5795 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5798 SDValue Sc = Op.getOperand(0);
5799 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5800 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5802 if (!Subtarget->hasInt256())
5805 // Use the register form of the broadcast instruction available on AVX2.
5806 if (VT.getSizeInBits() >= 256)
5807 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5808 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5811 Ld = Sc.getOperand(0);
5812 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5813 Ld.getOpcode() == ISD::ConstantFP);
5815 // The scalar_to_vector node and the suspected
5816 // load node must have exactly one user.
5817 // Constants may have multiple users.
5819 // AVX-512 has register version of the broadcast
5820 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5821 Ld.getValueType().getSizeInBits() >= 32;
5822 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5829 bool IsGE256 = (VT.getSizeInBits() >= 256);
5831 // Handle the broadcasting a single constant scalar from the constant pool
5832 // into a vector. On Sandybridge it is still better to load a constant vector
5833 // from the constant pool and not to broadcast it from a scalar.
5834 if (ConstSplatVal && Subtarget->hasInt256()) {
5835 EVT CVT = Ld.getValueType();
5836 assert(!CVT.isVector() && "Must not broadcast a vector type");
5837 unsigned ScalarSize = CVT.getSizeInBits();
5839 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5840 const Constant *C = nullptr;
5841 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5842 C = CI->getConstantIntValue();
5843 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5844 C = CF->getConstantFPValue();
5846 assert(C && "Invalid constant type");
5848 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5849 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5850 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5851 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5852 MachinePointerInfo::getConstantPool(),
5853 false, false, false, Alignment);
5855 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5859 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5860 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5862 // Handle AVX2 in-register broadcasts.
5863 if (!IsLoad && Subtarget->hasInt256() &&
5864 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5865 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5867 // The scalar source must be a normal load.
5871 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5872 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5874 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5875 // double since there is no vbroadcastsd xmm
5876 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5877 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5878 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5881 // Unsupported broadcast.
5885 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5886 /// underlying vector and index.
5888 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5890 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5892 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5893 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5896 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5898 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5900 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5901 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5904 // In this case the vector is the extract_subvector expression and the index
5905 // is 2, as specified by the shuffle.
5906 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5907 SDValue ShuffleVec = SVOp->getOperand(0);
5908 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5909 assert(ShuffleVecVT.getVectorElementType() ==
5910 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5912 int ShuffleIdx = SVOp->getMaskElt(Idx);
5913 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5914 ExtractedFromVec = ShuffleVec;
5920 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5921 MVT VT = Op.getSimpleValueType();
5923 // Skip if insert_vec_elt is not supported.
5924 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5925 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5929 unsigned NumElems = Op.getNumOperands();
5933 SmallVector<unsigned, 4> InsertIndices;
5934 SmallVector<int, 8> Mask(NumElems, -1);
5936 for (unsigned i = 0; i != NumElems; ++i) {
5937 unsigned Opc = Op.getOperand(i).getOpcode();
5939 if (Opc == ISD::UNDEF)
5942 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5943 // Quit if more than 1 elements need inserting.
5944 if (InsertIndices.size() > 1)
5947 InsertIndices.push_back(i);
5951 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5952 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5953 // Quit if non-constant index.
5954 if (!isa<ConstantSDNode>(ExtIdx))
5956 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5958 // Quit if extracted from vector of different type.
5959 if (ExtractedFromVec.getValueType() != VT)
5962 if (!VecIn1.getNode())
5963 VecIn1 = ExtractedFromVec;
5964 else if (VecIn1 != ExtractedFromVec) {
5965 if (!VecIn2.getNode())
5966 VecIn2 = ExtractedFromVec;
5967 else if (VecIn2 != ExtractedFromVec)
5968 // Quit if more than 2 vectors to shuffle
5972 if (ExtractedFromVec == VecIn1)
5974 else if (ExtractedFromVec == VecIn2)
5975 Mask[i] = Idx + NumElems;
5978 if (!VecIn1.getNode())
5981 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5982 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5983 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5984 unsigned Idx = InsertIndices[i];
5985 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5986 DAG.getIntPtrConstant(Idx));
5992 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5994 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5996 MVT VT = Op.getSimpleValueType();
5997 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5998 "Unexpected type in LowerBUILD_VECTORvXi1!");
6001 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6002 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6003 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6004 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6007 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6008 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6009 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6010 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6013 bool AllContants = true;
6014 uint64_t Immediate = 0;
6015 int NonConstIdx = -1;
6016 bool IsSplat = true;
6017 unsigned NumNonConsts = 0;
6018 unsigned NumConsts = 0;
6019 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6020 SDValue In = Op.getOperand(idx);
6021 if (In.getOpcode() == ISD::UNDEF)
6023 if (!isa<ConstantSDNode>(In)) {
6024 AllContants = false;
6030 if (cast<ConstantSDNode>(In)->getZExtValue())
6031 Immediate |= (1ULL << idx);
6033 if (In != Op.getOperand(0))
6038 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6039 DAG.getConstant(Immediate, MVT::i16));
6040 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6041 DAG.getIntPtrConstant(0));
6044 if (NumNonConsts == 1 && NonConstIdx != 0) {
6047 SDValue VecAsImm = DAG.getConstant(Immediate,
6048 MVT::getIntegerVT(VT.getSizeInBits()));
6049 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6052 DstVec = DAG.getUNDEF(VT);
6053 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6054 Op.getOperand(NonConstIdx),
6055 DAG.getIntPtrConstant(NonConstIdx));
6057 if (!IsSplat && (NonConstIdx != 0))
6058 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6059 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6062 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6063 DAG.getConstant(-1, SelectVT),
6064 DAG.getConstant(0, SelectVT));
6066 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6067 DAG.getConstant((Immediate | 1), SelectVT),
6068 DAG.getConstant(Immediate, SelectVT));
6069 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6072 /// \brief Return true if \p N implements a horizontal binop and return the
6073 /// operands for the horizontal binop into V0 and V1.
6075 /// This is a helper function of PerformBUILD_VECTORCombine.
6076 /// This function checks that the build_vector \p N in input implements a
6077 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6078 /// operation to match.
6079 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6080 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6081 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6084 /// This function only analyzes elements of \p N whose indices are
6085 /// in range [BaseIdx, LastIdx).
6086 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6088 unsigned BaseIdx, unsigned LastIdx,
6089 SDValue &V0, SDValue &V1) {
6090 EVT VT = N->getValueType(0);
6092 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6093 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6094 "Invalid Vector in input!");
6096 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6097 bool CanFold = true;
6098 unsigned ExpectedVExtractIdx = BaseIdx;
6099 unsigned NumElts = LastIdx - BaseIdx;
6100 V0 = DAG.getUNDEF(VT);
6101 V1 = DAG.getUNDEF(VT);
6103 // Check if N implements a horizontal binop.
6104 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6105 SDValue Op = N->getOperand(i + BaseIdx);
6108 if (Op->getOpcode() == ISD::UNDEF) {
6109 // Update the expected vector extract index.
6110 if (i * 2 == NumElts)
6111 ExpectedVExtractIdx = BaseIdx;
6112 ExpectedVExtractIdx += 2;
6116 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6121 SDValue Op0 = Op.getOperand(0);
6122 SDValue Op1 = Op.getOperand(1);
6124 // Try to match the following pattern:
6125 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6126 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6127 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6128 Op0.getOperand(0) == Op1.getOperand(0) &&
6129 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6130 isa<ConstantSDNode>(Op1.getOperand(1)));
6134 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6135 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6137 if (i * 2 < NumElts) {
6138 if (V0.getOpcode() == ISD::UNDEF)
6139 V0 = Op0.getOperand(0);
6141 if (V1.getOpcode() == ISD::UNDEF)
6142 V1 = Op0.getOperand(0);
6143 if (i * 2 == NumElts)
6144 ExpectedVExtractIdx = BaseIdx;
6147 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6148 if (I0 == ExpectedVExtractIdx)
6149 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6150 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6151 // Try to match the following dag sequence:
6152 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6153 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6157 ExpectedVExtractIdx += 2;
6163 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6164 /// a concat_vector.
6166 /// This is a helper function of PerformBUILD_VECTORCombine.
6167 /// This function expects two 256-bit vectors called V0 and V1.
6168 /// At first, each vector is split into two separate 128-bit vectors.
6169 /// Then, the resulting 128-bit vectors are used to implement two
6170 /// horizontal binary operations.
6172 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6174 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6175 /// the two new horizontal binop.
6176 /// When Mode is set, the first horizontal binop dag node would take as input
6177 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6178 /// horizontal binop dag node would take as input the lower 128-bit of V1
6179 /// and the upper 128-bit of V1.
6181 /// HADD V0_LO, V0_HI
6182 /// HADD V1_LO, V1_HI
6184 /// Otherwise, the first horizontal binop dag node takes as input the lower
6185 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6186 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6188 /// HADD V0_LO, V1_LO
6189 /// HADD V0_HI, V1_HI
6191 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6192 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6193 /// the upper 128-bits of the result.
6194 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6195 SDLoc DL, SelectionDAG &DAG,
6196 unsigned X86Opcode, bool Mode,
6197 bool isUndefLO, bool isUndefHI) {
6198 EVT VT = V0.getValueType();
6199 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6200 "Invalid nodes in input!");
6202 unsigned NumElts = VT.getVectorNumElements();
6203 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6204 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6205 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6206 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6207 EVT NewVT = V0_LO.getValueType();
6209 SDValue LO = DAG.getUNDEF(NewVT);
6210 SDValue HI = DAG.getUNDEF(NewVT);
6213 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6214 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6215 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6216 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6217 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6219 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6220 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6221 V1_LO->getOpcode() != ISD::UNDEF))
6222 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6224 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6225 V1_HI->getOpcode() != ISD::UNDEF))
6226 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6229 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6232 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6233 /// sequence of 'vadd + vsub + blendi'.
6234 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6235 const X86Subtarget *Subtarget) {
6237 EVT VT = BV->getValueType(0);
6238 unsigned NumElts = VT.getVectorNumElements();
6239 SDValue InVec0 = DAG.getUNDEF(VT);
6240 SDValue InVec1 = DAG.getUNDEF(VT);
6242 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6243 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6245 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6246 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6247 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6250 // Odd-numbered elements in the input build vector are obtained from
6251 // adding two integer/float elements.
6252 // Even-numbered elements in the input build vector are obtained from
6253 // subtracting two integer/float elements.
6254 unsigned ExpectedOpcode = ISD::FSUB;
6255 unsigned NextExpectedOpcode = ISD::FADD;
6256 bool AddFound = false;
6257 bool SubFound = false;
6259 for (unsigned i = 0, e = NumElts; i != e; i++) {
6260 SDValue Op = BV->getOperand(i);
6262 // Skip 'undef' values.
6263 unsigned Opcode = Op.getOpcode();
6264 if (Opcode == ISD::UNDEF) {
6265 std::swap(ExpectedOpcode, NextExpectedOpcode);
6269 // Early exit if we found an unexpected opcode.
6270 if (Opcode != ExpectedOpcode)
6273 SDValue Op0 = Op.getOperand(0);
6274 SDValue Op1 = Op.getOperand(1);
6276 // Try to match the following pattern:
6277 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6278 // Early exit if we cannot match that sequence.
6279 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6280 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6281 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6282 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6283 Op0.getOperand(1) != Op1.getOperand(1))
6286 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6290 // We found a valid add/sub node. Update the information accordingly.
6296 // Update InVec0 and InVec1.
6297 if (InVec0.getOpcode() == ISD::UNDEF)
6298 InVec0 = Op0.getOperand(0);
6299 if (InVec1.getOpcode() == ISD::UNDEF)
6300 InVec1 = Op1.getOperand(0);
6302 // Make sure that operands in input to each add/sub node always
6303 // come from a same pair of vectors.
6304 if (InVec0 != Op0.getOperand(0)) {
6305 if (ExpectedOpcode == ISD::FSUB)
6308 // FADD is commutable. Try to commute the operands
6309 // and then test again.
6310 std::swap(Op0, Op1);
6311 if (InVec0 != Op0.getOperand(0))
6315 if (InVec1 != Op1.getOperand(0))
6318 // Update the pair of expected opcodes.
6319 std::swap(ExpectedOpcode, NextExpectedOpcode);
6322 // Don't try to fold this build_vector into a VSELECT if it has
6323 // too many UNDEF operands.
6324 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6325 InVec1.getOpcode() != ISD::UNDEF) {
6326 // Emit a sequence of vector add and sub followed by a VSELECT.
6327 // The new VSELECT will be lowered into a BLENDI.
6328 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6329 // and emit a single ADDSUB instruction.
6330 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6331 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6333 // Construct the VSELECT mask.
6334 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6335 EVT SVT = MaskVT.getVectorElementType();
6336 unsigned SVTBits = SVT.getSizeInBits();
6337 SmallVector<SDValue, 8> Ops;
6339 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6340 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6341 APInt::getAllOnesValue(SVTBits);
6342 SDValue Constant = DAG.getConstant(Value, SVT);
6343 Ops.push_back(Constant);
6346 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6347 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6353 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6354 const X86Subtarget *Subtarget) {
6356 EVT VT = N->getValueType(0);
6357 unsigned NumElts = VT.getVectorNumElements();
6358 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6359 SDValue InVec0, InVec1;
6361 // Try to match an ADDSUB.
6362 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6363 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6364 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6365 if (Value.getNode())
6369 // Try to match horizontal ADD/SUB.
6370 unsigned NumUndefsLO = 0;
6371 unsigned NumUndefsHI = 0;
6372 unsigned Half = NumElts/2;
6374 // Count the number of UNDEF operands in the build_vector in input.
6375 for (unsigned i = 0, e = Half; i != e; ++i)
6376 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6379 for (unsigned i = Half, e = NumElts; i != e; ++i)
6380 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6383 // Early exit if this is either a build_vector of all UNDEFs or all the
6384 // operands but one are UNDEF.
6385 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6388 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6389 // Try to match an SSE3 float HADD/HSUB.
6390 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6391 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6393 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6394 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6395 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6396 // Try to match an SSSE3 integer HADD/HSUB.
6397 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6398 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6400 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6401 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6404 if (!Subtarget->hasAVX())
6407 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6408 // Try to match an AVX horizontal add/sub of packed single/double
6409 // precision floating point values from 256-bit vectors.
6410 SDValue InVec2, InVec3;
6411 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6412 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6413 ((InVec0.getOpcode() == ISD::UNDEF ||
6414 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6415 ((InVec1.getOpcode() == ISD::UNDEF ||
6416 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6417 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6419 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6420 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6421 ((InVec0.getOpcode() == ISD::UNDEF ||
6422 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6423 ((InVec1.getOpcode() == ISD::UNDEF ||
6424 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6425 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6426 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6427 // Try to match an AVX2 horizontal add/sub of signed integers.
6428 SDValue InVec2, InVec3;
6430 bool CanFold = true;
6432 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6433 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6434 ((InVec0.getOpcode() == ISD::UNDEF ||
6435 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6436 ((InVec1.getOpcode() == ISD::UNDEF ||
6437 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6438 X86Opcode = X86ISD::HADD;
6439 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6440 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6441 ((InVec0.getOpcode() == ISD::UNDEF ||
6442 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6443 ((InVec1.getOpcode() == ISD::UNDEF ||
6444 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6445 X86Opcode = X86ISD::HSUB;
6450 // Fold this build_vector into a single horizontal add/sub.
6451 // Do this only if the target has AVX2.
6452 if (Subtarget->hasAVX2())
6453 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6455 // Do not try to expand this build_vector into a pair of horizontal
6456 // add/sub if we can emit a pair of scalar add/sub.
6457 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6460 // Convert this build_vector into a pair of horizontal binop followed by
6462 bool isUndefLO = NumUndefsLO == Half;
6463 bool isUndefHI = NumUndefsHI == Half;
6464 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6465 isUndefLO, isUndefHI);
6469 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6470 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6472 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6473 X86Opcode = X86ISD::HADD;
6474 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6475 X86Opcode = X86ISD::HSUB;
6476 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6477 X86Opcode = X86ISD::FHADD;
6478 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6479 X86Opcode = X86ISD::FHSUB;
6483 // Don't try to expand this build_vector into a pair of horizontal add/sub
6484 // if we can simply emit a pair of scalar add/sub.
6485 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6488 // Convert this build_vector into two horizontal add/sub followed by
6490 bool isUndefLO = NumUndefsLO == Half;
6491 bool isUndefHI = NumUndefsHI == Half;
6492 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6493 isUndefLO, isUndefHI);
6500 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6503 MVT VT = Op.getSimpleValueType();
6504 MVT ExtVT = VT.getVectorElementType();
6505 unsigned NumElems = Op.getNumOperands();
6507 // Generate vectors for predicate vectors.
6508 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6509 return LowerBUILD_VECTORvXi1(Op, DAG);
6511 // Vectors containing all zeros can be matched by pxor and xorps later
6512 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6513 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6514 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6515 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6518 return getZeroVector(VT, Subtarget, DAG, dl);
6521 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6522 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6523 // vpcmpeqd on 256-bit vectors.
6524 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6525 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6528 if (!VT.is512BitVector())
6529 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6532 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6533 if (Broadcast.getNode())
6536 unsigned EVTBits = ExtVT.getSizeInBits();
6538 unsigned NumZero = 0;
6539 unsigned NumNonZero = 0;
6540 unsigned NonZeros = 0;
6541 bool IsAllConstants = true;
6542 SmallSet<SDValue, 8> Values;
6543 for (unsigned i = 0; i < NumElems; ++i) {
6544 SDValue Elt = Op.getOperand(i);
6545 if (Elt.getOpcode() == ISD::UNDEF)
6548 if (Elt.getOpcode() != ISD::Constant &&
6549 Elt.getOpcode() != ISD::ConstantFP)
6550 IsAllConstants = false;
6551 if (X86::isZeroNode(Elt))
6554 NonZeros |= (1 << i);
6559 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6560 if (NumNonZero == 0)
6561 return DAG.getUNDEF(VT);
6563 // Special case for single non-zero, non-undef, element.
6564 if (NumNonZero == 1) {
6565 unsigned Idx = countTrailingZeros(NonZeros);
6566 SDValue Item = Op.getOperand(Idx);
6568 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6569 // the value are obviously zero, truncate the value to i32 and do the
6570 // insertion that way. Only do this if the value is non-constant or if the
6571 // value is a constant being inserted into element 0. It is cheaper to do
6572 // a constant pool load than it is to do a movd + shuffle.
6573 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6574 (!IsAllConstants || Idx == 0)) {
6575 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6577 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6578 EVT VecVT = MVT::v4i32;
6579 unsigned VecElts = 4;
6581 // Truncate the value (which may itself be a constant) to i32, and
6582 // convert it to a vector with movd (S2V+shuffle to zero extend).
6583 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6584 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6585 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6587 // Now we have our 32-bit value zero extended in the low element of
6588 // a vector. If Idx != 0, swizzle it into place.
6590 SmallVector<int, 4> Mask;
6591 Mask.push_back(Idx);
6592 for (unsigned i = 1; i != VecElts; ++i)
6594 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6597 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6601 // If we have a constant or non-constant insertion into the low element of
6602 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6603 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6604 // depending on what the source datatype is.
6607 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6609 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6610 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6611 if (VT.is256BitVector() || VT.is512BitVector()) {
6612 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6613 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6614 Item, DAG.getIntPtrConstant(0));
6616 assert(VT.is128BitVector() && "Expected an SSE value type!");
6617 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6618 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6619 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6622 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6623 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6624 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6625 if (VT.is256BitVector()) {
6626 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6627 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6629 assert(VT.is128BitVector() && "Expected an SSE value type!");
6630 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6632 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6636 // Is it a vector logical left shift?
6637 if (NumElems == 2 && Idx == 1 &&
6638 X86::isZeroNode(Op.getOperand(0)) &&
6639 !X86::isZeroNode(Op.getOperand(1))) {
6640 unsigned NumBits = VT.getSizeInBits();
6641 return getVShift(true, VT,
6642 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6643 VT, Op.getOperand(1)),
6644 NumBits/2, DAG, *this, dl);
6647 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6650 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6651 // is a non-constant being inserted into an element other than the low one,
6652 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6653 // movd/movss) to move this into the low element, then shuffle it into
6655 if (EVTBits == 32) {
6656 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6658 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6659 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6660 SmallVector<int, 8> MaskVec;
6661 for (unsigned i = 0; i != NumElems; ++i)
6662 MaskVec.push_back(i == Idx ? 0 : 1);
6663 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6667 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6668 if (Values.size() == 1) {
6669 if (EVTBits == 32) {
6670 // Instead of a shuffle like this:
6671 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6672 // Check if it's possible to issue this instead.
6673 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6674 unsigned Idx = countTrailingZeros(NonZeros);
6675 SDValue Item = Op.getOperand(Idx);
6676 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6677 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6682 // A vector full of immediates; various special cases are already
6683 // handled, so this is best done with a single constant-pool load.
6687 // For AVX-length vectors, build the individual 128-bit pieces and use
6688 // shuffles to put them in place.
6689 if (VT.is256BitVector() || VT.is512BitVector()) {
6690 SmallVector<SDValue, 64> V;
6691 for (unsigned i = 0; i != NumElems; ++i)
6692 V.push_back(Op.getOperand(i));
6694 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6696 // Build both the lower and upper subvector.
6697 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6698 makeArrayRef(&V[0], NumElems/2));
6699 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6700 makeArrayRef(&V[NumElems / 2], NumElems/2));
6702 // Recreate the wider vector with the lower and upper part.
6703 if (VT.is256BitVector())
6704 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6705 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6708 // Let legalizer expand 2-wide build_vectors.
6709 if (EVTBits == 64) {
6710 if (NumNonZero == 1) {
6711 // One half is zero or undef.
6712 unsigned Idx = countTrailingZeros(NonZeros);
6713 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6714 Op.getOperand(Idx));
6715 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6720 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6721 if (EVTBits == 8 && NumElems == 16) {
6722 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6724 if (V.getNode()) return V;
6727 if (EVTBits == 16 && NumElems == 8) {
6728 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6730 if (V.getNode()) return V;
6733 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6734 if (EVTBits == 32 && NumElems == 4) {
6735 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6736 NumZero, DAG, Subtarget, *this);
6741 // If element VT is == 32 bits, turn it into a number of shuffles.
6742 SmallVector<SDValue, 8> V(NumElems);
6743 if (NumElems == 4 && NumZero > 0) {
6744 for (unsigned i = 0; i < 4; ++i) {
6745 bool isZero = !(NonZeros & (1 << i));
6747 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6749 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6752 for (unsigned i = 0; i < 2; ++i) {
6753 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6756 V[i] = V[i*2]; // Must be a zero vector.
6759 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6762 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6765 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6770 bool Reverse1 = (NonZeros & 0x3) == 2;
6771 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6775 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6776 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6778 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6781 if (Values.size() > 1 && VT.is128BitVector()) {
6782 // Check for a build vector of consecutive loads.
6783 for (unsigned i = 0; i < NumElems; ++i)
6784 V[i] = Op.getOperand(i);
6786 // Check for elements which are consecutive loads.
6787 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6791 // Check for a build vector from mostly shuffle plus few inserting.
6792 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6796 // For SSE 4.1, use insertps to put the high elements into the low element.
6797 if (getSubtarget()->hasSSE41()) {
6799 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6800 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6802 Result = DAG.getUNDEF(VT);
6804 for (unsigned i = 1; i < NumElems; ++i) {
6805 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6806 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6807 Op.getOperand(i), DAG.getIntPtrConstant(i));
6812 // Otherwise, expand into a number of unpckl*, start by extending each of
6813 // our (non-undef) elements to the full vector width with the element in the
6814 // bottom slot of the vector (which generates no code for SSE).
6815 for (unsigned i = 0; i < NumElems; ++i) {
6816 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6817 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6819 V[i] = DAG.getUNDEF(VT);
6822 // Next, we iteratively mix elements, e.g. for v4f32:
6823 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6824 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6825 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6826 unsigned EltStride = NumElems >> 1;
6827 while (EltStride != 0) {
6828 for (unsigned i = 0; i < EltStride; ++i) {
6829 // If V[i+EltStride] is undef and this is the first round of mixing,
6830 // then it is safe to just drop this shuffle: V[i] is already in the
6831 // right place, the one element (since it's the first round) being
6832 // inserted as undef can be dropped. This isn't safe for successive
6833 // rounds because they will permute elements within both vectors.
6834 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6835 EltStride == NumElems/2)
6838 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6847 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6848 // to create 256-bit vectors from two other 128-bit ones.
6849 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6851 MVT ResVT = Op.getSimpleValueType();
6853 assert((ResVT.is256BitVector() ||
6854 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6856 SDValue V1 = Op.getOperand(0);
6857 SDValue V2 = Op.getOperand(1);
6858 unsigned NumElems = ResVT.getVectorNumElements();
6859 if(ResVT.is256BitVector())
6860 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6862 if (Op.getNumOperands() == 4) {
6863 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6864 ResVT.getVectorNumElements()/2);
6865 SDValue V3 = Op.getOperand(2);
6866 SDValue V4 = Op.getOperand(3);
6867 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6868 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6870 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6873 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6874 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6875 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6876 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6877 Op.getNumOperands() == 4)));
6879 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6880 // from two other 128-bit ones.
6882 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6883 return LowerAVXCONCAT_VECTORS(Op, DAG);
6887 //===----------------------------------------------------------------------===//
6888 // Vector shuffle lowering
6890 // This is an experimental code path for lowering vector shuffles on x86. It is
6891 // designed to handle arbitrary vector shuffles and blends, gracefully
6892 // degrading performance as necessary. It works hard to recognize idiomatic
6893 // shuffles and lower them to optimal instruction patterns without leaving
6894 // a framework that allows reasonably efficient handling of all vector shuffle
6896 //===----------------------------------------------------------------------===//
6898 /// \brief Tiny helper function to identify a no-op mask.
6900 /// This is a somewhat boring predicate function. It checks whether the mask
6901 /// array input, which is assumed to be a single-input shuffle mask of the kind
6902 /// used by the X86 shuffle instructions (not a fully general
6903 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6904 /// in-place shuffle are 'no-op's.
6905 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6906 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6907 if (Mask[i] != -1 && Mask[i] != i)
6912 /// \brief Helper function to classify a mask as a single-input mask.
6914 /// This isn't a generic single-input test because in the vector shuffle
6915 /// lowering we canonicalize single inputs to be the first input operand. This
6916 /// means we can more quickly test for a single input by only checking whether
6917 /// an input from the second operand exists. We also assume that the size of
6918 /// mask corresponds to the size of the input vectors which isn't true in the
6919 /// fully general case.
6920 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6922 if (M >= (int)Mask.size())
6927 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6929 /// This helper function produces an 8-bit shuffle immediate corresponding to
6930 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6931 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6934 /// NB: We rely heavily on "undef" masks preserving the input lane.
6935 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6936 SelectionDAG &DAG) {
6937 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6938 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6939 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6940 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6941 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6944 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6945 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6946 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6947 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6948 return DAG.getConstant(Imm, MVT::i8);
6951 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6953 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6954 /// support for floating point shuffles but not integer shuffles. These
6955 /// instructions will incur a domain crossing penalty on some chips though so
6956 /// it is better to avoid lowering through this for integer vectors where
6958 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6959 const X86Subtarget *Subtarget,
6960 SelectionDAG &DAG) {
6962 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6963 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6964 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6965 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6966 ArrayRef<int> Mask = SVOp->getMask();
6967 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6969 if (isSingleInputShuffleMask(Mask)) {
6970 // Straight shuffle of a single input vector. Simulate this by using the
6971 // single input as both of the "inputs" to this instruction..
6972 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6973 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6974 DAG.getConstant(SHUFPDMask, MVT::i8));
6976 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6977 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6979 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6980 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6981 DAG.getConstant(SHUFPDMask, MVT::i8));
6984 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6986 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6987 /// the integer unit to minimize domain crossing penalties. However, for blends
6988 /// it falls back to the floating point shuffle operation with appropriate bit
6990 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6991 const X86Subtarget *Subtarget,
6992 SelectionDAG &DAG) {
6994 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
6995 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6996 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6997 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6998 ArrayRef<int> Mask = SVOp->getMask();
6999 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7001 if (isSingleInputShuffleMask(Mask)) {
7002 // Straight shuffle of a single input vector. For everything from SSE2
7003 // onward this has a single fast instruction with no scary immediates.
7004 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7005 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7006 int WidenedMask[4] = {
7007 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7008 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7010 ISD::BITCAST, DL, MVT::v2i64,
7011 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7012 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7015 // We implement this with SHUFPD which is pretty lame because it will likely
7016 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7017 // However, all the alternatives are still more cycles and newer chips don't
7018 // have this problem. It would be really nice if x86 had better shuffles here.
7019 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7020 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7021 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7022 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7025 /// \brief Lower 4-lane 32-bit floating point shuffles.
7027 /// Uses instructions exclusively from the floating point unit to minimize
7028 /// domain crossing penalties, as these are sufficient to implement all v4f32
7030 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7031 const X86Subtarget *Subtarget,
7032 SelectionDAG &DAG) {
7034 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7035 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7036 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7037 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7038 ArrayRef<int> Mask = SVOp->getMask();
7039 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7041 SDValue LowV = V1, HighV = V2;
7042 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7045 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7047 if (NumV2Elements == 0)
7048 // Straight shuffle of a single input vector. We pass the input vector to
7049 // both operands to simulate this with a SHUFPS.
7050 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7051 getV4X86ShuffleImm8ForMask(Mask, DAG));
7053 if (NumV2Elements == 1) {
7055 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7057 // Compute the index adjacent to V2Index and in the same half by toggling
7059 int V2AdjIndex = V2Index ^ 1;
7061 if (Mask[V2AdjIndex] == -1) {
7062 // Handles all the cases where we have a single V2 element and an undef.
7063 // This will only ever happen in the high lanes because we commute the
7064 // vector otherwise.
7066 std::swap(LowV, HighV);
7067 NewMask[V2Index] -= 4;
7069 // Handle the case where the V2 element ends up adjacent to a V1 element.
7070 // To make this work, blend them together as the first step.
7071 int V1Index = V2AdjIndex;
7072 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7073 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7074 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7076 // Now proceed to reconstruct the final blend as we have the necessary
7077 // high or low half formed.
7084 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7085 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7087 } else if (NumV2Elements == 2) {
7088 if (Mask[0] < 4 && Mask[1] < 4) {
7089 // Handle the easy case where we have V1 in the low lanes and V2 in the
7090 // high lanes. We never see this reversed because we sort the shuffle.
7094 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7095 // trying to place elements directly, just blend them and set up the final
7096 // shuffle to place them.
7098 // The first two blend mask elements are for V1, the second two are for
7100 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7101 Mask[2] < 4 ? Mask[2] : Mask[3],
7102 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7103 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7104 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7105 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7107 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7110 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7111 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7112 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7113 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7116 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7117 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7120 /// \brief Lower 4-lane i32 vector shuffles.
7122 /// We try to handle these with integer-domain shuffles where we can, but for
7123 /// blends we use the floating point domain blend instructions.
7124 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7125 const X86Subtarget *Subtarget,
7126 SelectionDAG &DAG) {
7128 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7129 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7130 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7131 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7132 ArrayRef<int> Mask = SVOp->getMask();
7133 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7135 if (isSingleInputShuffleMask(Mask))
7136 // Straight shuffle of a single input vector. For everything from SSE2
7137 // onward this has a single fast instruction with no scary immediates.
7138 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7139 getV4X86ShuffleImm8ForMask(Mask, DAG));
7141 // We implement this with SHUFPS because it can blend from two vectors.
7142 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7143 // up the inputs, bypassing domain shift penalties that we would encur if we
7144 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7146 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7147 DAG.getVectorShuffle(
7149 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7150 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7153 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7154 /// shuffle lowering, and the most complex part.
7156 /// The lowering strategy is to try to form pairs of input lanes which are
7157 /// targeted at the same half of the final vector, and then use a dword shuffle
7158 /// to place them onto the right half, and finally unpack the paired lanes into
7159 /// their final position.
7161 /// The exact breakdown of how to form these dword pairs and align them on the
7162 /// correct sides is really tricky. See the comments within the function for
7163 /// more of the details.
7164 static SDValue lowerV8I16SingleInputVectorShuffle(
7165 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7166 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7167 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7168 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7169 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7171 SmallVector<int, 4> LoInputs;
7172 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7173 [](int M) { return M >= 0; });
7174 std::sort(LoInputs.begin(), LoInputs.end());
7175 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7176 SmallVector<int, 4> HiInputs;
7177 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7178 [](int M) { return M >= 0; });
7179 std::sort(HiInputs.begin(), HiInputs.end());
7180 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7182 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7183 int NumHToL = LoInputs.size() - NumLToL;
7185 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7186 int NumHToH = HiInputs.size() - NumLToH;
7187 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7188 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7189 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7190 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7192 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7193 // such inputs we can swap two of the dwords across the half mark and end up
7194 // with <=2 inputs to each half in each half. Once there, we can fall through
7195 // to the generic code below. For example:
7197 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7198 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7200 // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7202 auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7203 int ThreeInputHalfSum, int OneInputHalfOffset) {
7204 // Compute the index of dword with only one word among the three inputs in
7205 // a half by taking the sum of the half with three inputs and subtracting
7206 // the sum of the actual three inputs. The difference is the remaining
7208 int DWordA = (ThreeInputHalfSum -
7209 std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7211 int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7213 int PSHUFDMask[] = {0, 1, 2, 3};
7214 PSHUFDMask[DWordA] = DWordB;
7215 PSHUFDMask[DWordB] = DWordA;
7216 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7217 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7218 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7219 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7221 // Adjust the mask to match the new locations of A and B.
7223 if (M != -1 && M/2 == DWordA)
7224 M = 2 * DWordB + M % 2;
7225 else if (M != -1 && M/2 == DWordB)
7226 M = 2 * DWordA + M % 2;
7228 // Recurse back into this routine to re-compute state now that this isn't
7229 // a 3 and 1 problem.
7230 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7233 if (NumLToL == 3 && NumHToL == 1)
7234 return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7235 else if (NumLToL == 1 && NumHToL == 3)
7236 return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7237 else if (NumLToH == 1 && NumHToH == 3)
7238 return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7239 else if (NumLToH == 3 && NumHToH == 1)
7240 return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7242 // At this point there are at most two inputs to the low and high halves from
7243 // each half. That means the inputs can always be grouped into dwords and
7244 // those dwords can then be moved to the correct half with a dword shuffle.
7245 // We use at most one low and one high word shuffle to collect these paired
7246 // inputs into dwords, and finally a dword shuffle to place them.
7247 int PSHUFLMask[4] = {-1, -1, -1, -1};
7248 int PSHUFHMask[4] = {-1, -1, -1, -1};
7249 int PSHUFDMask[4] = {-1, -1, -1, -1};
7251 // First fix the masks for all the inputs that are staying in their
7252 // original halves. This will then dictate the targets of the cross-half
7254 auto fixInPlaceInputs = [&PSHUFDMask](
7255 ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7256 MutableArrayRef<int> HalfMask, int HalfOffset) {
7257 if (InPlaceInputs.empty())
7259 if (InPlaceInputs.size() == 1) {
7260 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7261 InPlaceInputs[0] - HalfOffset;
7262 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7266 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7267 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7268 InPlaceInputs[0] - HalfOffset;
7269 // Put the second input next to the first so that they are packed into
7270 // a dword. We find the adjacent index by toggling the low bit.
7271 int AdjIndex = InPlaceInputs[0] ^ 1;
7272 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7273 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7274 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7276 if (!HToLInputs.empty())
7277 fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7278 if (!LToHInputs.empty())
7279 fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7281 // Now gather the cross-half inputs and place them into a free dword of
7282 // their target half.
7283 // FIXME: This operation could almost certainly be simplified dramatically to
7284 // look more like the 3-1 fixing operation.
7285 auto moveInputsToRightHalf = [&PSHUFDMask](
7286 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7287 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7288 int SourceOffset, int DestOffset) {
7289 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7290 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7292 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7294 int LowWord = Word & ~1;
7295 int HighWord = Word | 1;
7296 return isWordClobbered(SourceHalfMask, LowWord) ||
7297 isWordClobbered(SourceHalfMask, HighWord);
7300 if (IncomingInputs.empty())
7303 if (ExistingInputs.empty()) {
7304 // Map any dwords with inputs from them into the right half.
7305 for (int Input : IncomingInputs) {
7306 // If the source half mask maps over the inputs, turn those into
7307 // swaps and use the swapped lane.
7308 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7309 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7310 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7311 Input - SourceOffset;
7312 // We have to swap the uses in our half mask in one sweep.
7313 for (int &M : HalfMask)
7314 if (M == SourceHalfMask[Input - SourceOffset])
7316 else if (M == Input)
7317 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7319 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7320 Input - SourceOffset &&
7321 "Previous placement doesn't match!");
7323 // Note that this correctly re-maps both when we do a swap and when
7324 // we observe the other side of the swap above. We rely on that to
7325 // avoid swapping the members of the input list directly.
7326 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7329 // Map the input's dword into the correct half.
7330 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7331 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7333 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7335 "Previous placement doesn't match!");
7338 // And just directly shift any other-half mask elements to be same-half
7339 // as we will have mirrored the dword containing the element into the
7340 // same position within that half.
7341 for (int &M : HalfMask)
7342 if (M >= SourceOffset && M < SourceOffset + 4) {
7343 M = M - SourceOffset + DestOffset;
7344 assert(M >= 0 && "This should never wrap below zero!");
7349 // Ensure we have the input in a viable dword of its current half. This
7350 // is particularly tricky because the original position may be clobbered
7351 // by inputs being moved and *staying* in that half.
7352 if (IncomingInputs.size() == 1) {
7353 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7354 int InputFixed = std::find(std::begin(SourceHalfMask),
7355 std::end(SourceHalfMask), -1) -
7356 std::begin(SourceHalfMask) + SourceOffset;
7357 SourceHalfMask[InputFixed - SourceOffset] =
7358 IncomingInputs[0] - SourceOffset;
7359 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7361 IncomingInputs[0] = InputFixed;
7363 } else if (IncomingInputs.size() == 2) {
7364 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7365 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7366 int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7367 assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7368 "Not all dwords can be clobbered!");
7369 SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7370 SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7371 for (int &M : HalfMask)
7372 if (M == IncomingInputs[0])
7373 M = SourceDWordBase + SourceOffset;
7374 else if (M == IncomingInputs[1])
7375 M = SourceDWordBase + 1 + SourceOffset;
7376 IncomingInputs[0] = SourceDWordBase + SourceOffset;
7377 IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7380 llvm_unreachable("Unhandled input size!");
7383 // Now hoist the DWord down to the right half.
7384 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7385 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7386 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7387 for (int Input : IncomingInputs)
7388 std::replace(HalfMask.begin(), HalfMask.end(), Input,
7389 FreeDWord * 2 + Input % 2);
7391 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7392 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7393 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7394 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7396 // Now enact all the shuffles we've computed to move the inputs into their
7398 if (!isNoopShuffleMask(PSHUFLMask))
7399 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7400 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7401 if (!isNoopShuffleMask(PSHUFHMask))
7402 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7403 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7404 if (!isNoopShuffleMask(PSHUFDMask))
7405 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7406 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7407 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7408 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7410 // At this point, each half should contain all its inputs, and we can then
7411 // just shuffle them into their final position.
7412 assert(std::count_if(LoMask.begin(), LoMask.end(),
7413 [](int M) { return M >= 4; }) == 0 &&
7414 "Failed to lift all the high half inputs to the low mask!");
7415 assert(std::count_if(HiMask.begin(), HiMask.end(),
7416 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7417 "Failed to lift all the low half inputs to the high mask!");
7419 // Do a half shuffle for the low mask.
7420 if (!isNoopShuffleMask(LoMask))
7421 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7422 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7424 // Do a half shuffle with the high mask after shifting its values down.
7425 for (int &M : HiMask)
7428 if (!isNoopShuffleMask(HiMask))
7429 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7430 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7435 /// \brief Detect whether the mask pattern should be lowered through
7438 /// This essentially tests whether viewing the mask as an interleaving of two
7439 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7440 /// lowering it through interleaving is a significantly better strategy.
7441 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7442 int NumEvenInputs[2] = {0, 0};
7443 int NumOddInputs[2] = {0, 0};
7444 int NumLoInputs[2] = {0, 0};
7445 int NumHiInputs[2] = {0, 0};
7446 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7450 int InputIdx = Mask[i] >= Size;
7453 ++NumLoInputs[InputIdx];
7455 ++NumHiInputs[InputIdx];
7458 ++NumEvenInputs[InputIdx];
7460 ++NumOddInputs[InputIdx];
7463 // The minimum number of cross-input results for both the interleaved and
7464 // split cases. If interleaving results in fewer cross-input results, return
7466 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7467 NumEvenInputs[0] + NumOddInputs[1]);
7468 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7469 NumLoInputs[0] + NumHiInputs[1]);
7470 return InterleavedCrosses < SplitCrosses;
7473 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7475 /// This strategy only works when the inputs from each vector fit into a single
7476 /// half of that vector, and generally there are not so many inputs as to leave
7477 /// the in-place shuffles required highly constrained (and thus expensive). It
7478 /// shifts all the inputs into a single side of both input vectors and then
7479 /// uses an unpack to interleave these inputs in a single vector. At that
7480 /// point, we will fall back on the generic single input shuffle lowering.
7481 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7483 MutableArrayRef<int> Mask,
7484 const X86Subtarget *Subtarget,
7485 SelectionDAG &DAG) {
7486 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7487 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7488 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7489 for (int i = 0; i < 8; ++i)
7490 if (Mask[i] >= 0 && Mask[i] < 4)
7491 LoV1Inputs.push_back(i);
7492 else if (Mask[i] >= 4 && Mask[i] < 8)
7493 HiV1Inputs.push_back(i);
7494 else if (Mask[i] >= 8 && Mask[i] < 12)
7495 LoV2Inputs.push_back(i);
7496 else if (Mask[i] >= 12)
7497 HiV2Inputs.push_back(i);
7499 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7500 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7503 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7504 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7505 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7507 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7508 HiV1Inputs.size() + HiV2Inputs.size();
7510 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7511 ArrayRef<int> HiInputs, bool MoveToLo,
7513 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7514 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7515 if (BadInputs.empty())
7518 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7519 int MoveOffset = MoveToLo ? 0 : 4;
7521 if (GoodInputs.empty()) {
7522 for (int BadInput : BadInputs) {
7523 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7524 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7527 if (GoodInputs.size() == 2) {
7528 // If the low inputs are spread across two dwords, pack them into
7530 MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7531 Mask[GoodInputs[0]] - MaskOffset;
7532 MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7533 Mask[GoodInputs[1]] - MaskOffset;
7534 Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7535 Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7537 // Otherwise pin the low inputs.
7538 for (int GoodInput : GoodInputs)
7539 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7543 std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7544 std::begin(MoveMask);
7545 assert(MoveMaskIdx >= MoveOffset && "Established above");
7547 if (BadInputs.size() == 2) {
7548 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7549 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7550 MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7551 Mask[BadInputs[0]] - MaskOffset;
7552 MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7553 Mask[BadInputs[1]] - MaskOffset;
7554 Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7555 Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7557 assert(BadInputs.size() == 1 && "All sizes handled");
7558 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7559 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7563 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7566 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7568 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7571 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7572 // cross-half traffic in the final shuffle.
7574 // Munge the mask to be a single-input mask after the unpack merges the
7578 M = 2 * (M % 4) + (M / 8);
7580 return DAG.getVectorShuffle(
7581 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7582 DL, MVT::v8i16, V1, V2),
7583 DAG.getUNDEF(MVT::v8i16), Mask);
7586 /// \brief Generic lowering of 8-lane i16 shuffles.
7588 /// This handles both single-input shuffles and combined shuffle/blends with
7589 /// two inputs. The single input shuffles are immediately delegated to
7590 /// a dedicated lowering routine.
7592 /// The blends are lowered in one of three fundamental ways. If there are few
7593 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7594 /// of the input is significantly cheaper when lowered as an interleaving of
7595 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7596 /// halves of the inputs separately (making them have relatively few inputs)
7597 /// and then concatenate them.
7598 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7599 const X86Subtarget *Subtarget,
7600 SelectionDAG &DAG) {
7602 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7603 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7604 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7605 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7606 ArrayRef<int> OrigMask = SVOp->getMask();
7607 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7608 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7609 MutableArrayRef<int> Mask(MaskStorage);
7611 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7613 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7614 auto isV2 = [](int M) { return M >= 8; };
7616 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7617 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7619 if (NumV2Inputs == 0)
7620 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7622 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7623 "to be V1-input shuffles.");
7625 if (NumV1Inputs + NumV2Inputs <= 4)
7626 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7628 // Check whether an interleaving lowering is likely to be more efficient.
7629 // This isn't perfect but it is a strong heuristic that tends to work well on
7630 // the kinds of shuffles that show up in practice.
7632 // FIXME: Handle 1x, 2x, and 4x interleaving.
7633 if (shouldLowerAsInterleaving(Mask)) {
7634 // FIXME: Figure out whether we should pack these into the low or high
7637 int EMask[8], OMask[8];
7638 for (int i = 0; i < 4; ++i) {
7639 EMask[i] = Mask[2*i];
7640 OMask[i] = Mask[2*i + 1];
7645 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7646 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7648 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7651 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7652 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7654 for (int i = 0; i < 4; ++i) {
7655 LoBlendMask[i] = Mask[i];
7656 HiBlendMask[i] = Mask[i + 4];
7659 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7660 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7661 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7662 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7664 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7665 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7668 /// \brief Generic lowering of v16i8 shuffles.
7670 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7671 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7672 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7673 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7675 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7676 const X86Subtarget *Subtarget,
7677 SelectionDAG &DAG) {
7679 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7680 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7681 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7682 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7683 ArrayRef<int> OrigMask = SVOp->getMask();
7684 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7685 int MaskStorage[16] = {
7686 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7687 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
7688 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
7689 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7690 MutableArrayRef<int> Mask(MaskStorage);
7691 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7692 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7694 // For single-input shuffles, there are some nicer lowering tricks we can use.
7695 if (isSingleInputShuffleMask(Mask)) {
7696 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7697 // Notably, this handles splat and partial-splat shuffles more efficiently.
7699 // FIXME: We should check for other patterns which can be widened into an
7700 // i16 shuffle as well.
7701 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7702 for (int i = 0; i < 16; i += 2) {
7703 if (Mask[i] != Mask[i + 1])
7708 if (canWidenViaDuplication(Mask)) {
7709 SmallVector<int, 4> LoInputs;
7710 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7711 [](int M) { return M >= 0 && M < 8; });
7712 std::sort(LoInputs.begin(), LoInputs.end());
7713 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7715 SmallVector<int, 4> HiInputs;
7716 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7717 [](int M) { return M >= 8; });
7718 std::sort(HiInputs.begin(), HiInputs.end());
7719 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7722 bool TargetLo = LoInputs.size() >= HiInputs.size();
7723 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7724 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7727 SmallDenseMap<int, int, 8> LaneMap;
7728 for (int i = 0; i < 16; ++i)
7730 for (int I : InPlaceInputs) {
7734 int FreeByteIdx = 0;
7735 int TargetOffset = TargetLo ? 0 : 8;
7736 for (int I : MovingInputs) {
7737 // Walk the free index into the byte mask until we find an unoccupied
7738 // spot. We bound this to 8 steps to catch bugs, the pigeonhole
7739 // principle indicates that there *must* be a spot as we can only have
7740 // 8 duplicated inputs. We have to walk the index using modular
7741 // arithmetic to wrap around as necessary.
7742 // FIXME: We could do a much better job of picking an inexpensive slot
7743 // so this doesn't go through the worst case for the byte shuffle.
7744 for (int j = 0; j < 8 && ByteMask[FreeByteIdx + TargetOffset] != -1;
7745 ++j, FreeByteIdx = (FreeByteIdx + 1) % 8)
7747 assert(ByteMask[FreeByteIdx + TargetOffset] == -1 &&
7748 "Failed to find a free byte!");
7749 ByteMask[FreeByteIdx + TargetOffset] = I;
7750 LaneMap[I] = FreeByteIdx + TargetOffset;
7752 V1 = DAG.getVectorShuffle(MVT::v16i8, DL, V1, DAG.getUNDEF(MVT::v16i8),
7758 // Unpack the bytes to form the i16s that will be shuffled into place.
7759 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7760 MVT::v16i8, V1, V1);
7762 int I16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7763 for (int i = 0; i < 16; i += 2) {
7765 I16Shuffle[i / 2] = Mask[i] - (TargetLo ? 0 : 8);
7766 assert(I16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7768 return DAG.getVectorShuffle(MVT::v8i16, DL,
7769 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7770 DAG.getUNDEF(MVT::v8i16), I16Shuffle);
7774 // Check whether an interleaving lowering is likely to be more efficient.
7775 // This isn't perfect but it is a strong heuristic that tends to work well on
7776 // the kinds of shuffles that show up in practice.
7778 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7779 if (shouldLowerAsInterleaving(Mask)) {
7780 // FIXME: Figure out whether we should pack these into the low or high
7783 int EMask[16], OMask[16];
7784 for (int i = 0; i < 8; ++i) {
7785 EMask[i] = Mask[2*i];
7786 OMask[i] = Mask[2*i + 1];
7791 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7792 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7794 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7796 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7798 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7799 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, Zero));
7801 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7802 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, Zero));
7804 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7805 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V2, Zero));
7807 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7808 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V2, Zero));
7810 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7811 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7812 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7813 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7815 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7816 MutableArrayRef<int> V1HalfBlendMask,
7817 MutableArrayRef<int> V2HalfBlendMask) {
7818 for (int i = 0; i < 8; ++i)
7819 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7820 V1HalfBlendMask[i] = HalfMask[i];
7822 } else if (HalfMask[i] >= 16) {
7823 V2HalfBlendMask[i] = HalfMask[i] - 16;
7824 HalfMask[i] = i + 8;
7827 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7828 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7830 SDValue V1Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1LoBlendMask);
7831 SDValue V2Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2LoBlendMask);
7832 SDValue V1Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1HiBlendMask);
7833 SDValue V2Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2HiBlendMask);
7835 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7836 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7838 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7841 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7843 /// This routine breaks down the specific type of 128-bit shuffle and
7844 /// dispatches to the lowering routines accordingly.
7845 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7846 MVT VT, const X86Subtarget *Subtarget,
7847 SelectionDAG &DAG) {
7848 switch (VT.SimpleTy) {
7850 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7852 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7854 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7856 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7858 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7860 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7863 llvm_unreachable("Unimplemented!");
7867 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7868 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7869 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7870 if (Mask[i] + 1 != Mask[i+1])
7876 /// \brief Top-level lowering for x86 vector shuffles.
7878 /// This handles decomposition, canonicalization, and lowering of all x86
7879 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7880 /// above in helper routines. The canonicalization attempts to widen shuffles
7881 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7882 /// s.t. only one of the two inputs needs to be tested, etc.
7883 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7884 SelectionDAG &DAG) {
7885 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7886 ArrayRef<int> Mask = SVOp->getMask();
7887 SDValue V1 = Op.getOperand(0);
7888 SDValue V2 = Op.getOperand(1);
7889 MVT VT = Op.getSimpleValueType();
7890 int NumElements = VT.getVectorNumElements();
7893 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7895 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7896 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7897 if (V1IsUndef && V2IsUndef)
7898 return DAG.getUNDEF(VT);
7900 // When we create a shuffle node we put the UNDEF node to second operand,
7901 // but in some cases the first operand may be transformed to UNDEF.
7902 // In this case we should just commute the node.
7904 return CommuteVectorShuffle(SVOp, DAG);
7906 // Check for non-undef masks pointing at an undef vector and make the masks
7907 // undef as well. This makes it easier to match the shuffle based solely on
7911 if (M >= NumElements) {
7912 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7913 for (int &M : NewMask)
7914 if (M >= NumElements)
7916 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7919 // For integer vector shuffles, try to collapse them into a shuffle of fewer
7920 // lanes but wider integers. We cap this to not form integers larger than i64
7921 // but it might be interesting to form i128 integers to handle flipping the
7922 // low and high halves of AVX 256-bit vectors.
7923 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7924 areAdjacentMasksSequential(Mask)) {
7925 SmallVector<int, 8> NewMask;
7926 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7927 NewMask.push_back(Mask[i] / 2);
7929 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7930 VT.getVectorNumElements() / 2);
7931 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7932 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7933 return DAG.getNode(ISD::BITCAST, dl, VT,
7934 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7937 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7938 for (int M : SVOp->getMask())
7941 else if (M < NumElements)
7946 // Commute the shuffle as needed such that more elements come from V1 than
7947 // V2. This allows us to match the shuffle pattern strictly on how many
7948 // elements come from V1 without handling the symmetric cases.
7949 if (NumV2Elements > NumV1Elements)
7950 return CommuteVectorShuffle(SVOp, DAG);
7952 // When the number of V1 and V2 elements are the same, try to minimize the
7953 // number of uses of V2 in the low half of the vector.
7954 if (NumV1Elements == NumV2Elements) {
7955 int LowV1Elements = 0, LowV2Elements = 0;
7956 for (int M : SVOp->getMask().slice(0, NumElements / 2))
7957 if (M >= NumElements)
7961 if (LowV2Elements > LowV1Elements)
7962 return CommuteVectorShuffle(SVOp, DAG);
7965 // For each vector width, delegate to a specialized lowering routine.
7966 if (VT.getSizeInBits() == 128)
7967 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
7969 llvm_unreachable("Unimplemented!");
7973 //===----------------------------------------------------------------------===//
7974 // Legacy vector shuffle lowering
7976 // This code is the legacy code handling vector shuffles until the above
7977 // replaces its functionality and performance.
7978 //===----------------------------------------------------------------------===//
7980 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
7981 bool hasInt256, unsigned *MaskOut = nullptr) {
7982 MVT EltVT = VT.getVectorElementType();
7984 // There is no blend with immediate in AVX-512.
7985 if (VT.is512BitVector())
7988 if (!hasSSE41 || EltVT == MVT::i8)
7990 if (!hasInt256 && VT == MVT::v16i16)
7993 unsigned MaskValue = 0;
7994 unsigned NumElems = VT.getVectorNumElements();
7995 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
7996 unsigned NumLanes = (NumElems - 1) / 8 + 1;
7997 unsigned NumElemsInLane = NumElems / NumLanes;
7999 // Blend for v16i16 should be symetric for the both lanes.
8000 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8002 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8003 int EltIdx = MaskVals[i];
8005 if ((EltIdx < 0 || EltIdx == (int)i) &&
8006 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8009 if (((unsigned)EltIdx == (i + NumElems)) &&
8010 (SndLaneEltIdx < 0 ||
8011 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8012 MaskValue |= (1 << i);
8018 *MaskOut = MaskValue;
8022 // Try to lower a shuffle node into a simple blend instruction.
8023 // This function assumes isBlendMask returns true for this
8024 // SuffleVectorSDNode
8025 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8027 const X86Subtarget *Subtarget,
8028 SelectionDAG &DAG) {
8029 MVT VT = SVOp->getSimpleValueType(0);
8030 MVT EltVT = VT.getVectorElementType();
8031 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8032 Subtarget->hasInt256() && "Trying to lower a "
8033 "VECTOR_SHUFFLE to a Blend but "
8034 "with the wrong mask"));
8035 SDValue V1 = SVOp->getOperand(0);
8036 SDValue V2 = SVOp->getOperand(1);
8038 unsigned NumElems = VT.getVectorNumElements();
8040 // Convert i32 vectors to floating point if it is not AVX2.
8041 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8043 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8044 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8046 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8047 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8050 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8051 DAG.getConstant(MaskValue, MVT::i32));
8052 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8055 /// In vector type \p VT, return true if the element at index \p InputIdx
8056 /// falls on a different 128-bit lane than \p OutputIdx.
8057 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8058 unsigned OutputIdx) {
8059 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8060 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8063 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8064 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8065 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8066 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8068 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8069 SelectionDAG &DAG) {
8070 MVT VT = V1.getSimpleValueType();
8071 assert(VT.is128BitVector() || VT.is256BitVector());
8073 MVT EltVT = VT.getVectorElementType();
8074 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8075 unsigned NumElts = VT.getVectorNumElements();
8077 SmallVector<SDValue, 32> PshufbMask;
8078 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8079 int InputIdx = MaskVals[OutputIdx];
8080 unsigned InputByteIdx;
8082 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8083 InputByteIdx = 0x80;
8085 // Cross lane is not allowed.
8086 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8088 InputByteIdx = InputIdx * EltSizeInBytes;
8089 // Index is an byte offset within the 128-bit lane.
8090 InputByteIdx &= 0xf;
8093 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8094 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8095 if (InputByteIdx != 0x80)
8100 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8102 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8103 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8104 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8107 // v8i16 shuffles - Prefer shuffles in the following order:
8108 // 1. [all] pshuflw, pshufhw, optional move
8109 // 2. [ssse3] 1 x pshufb
8110 // 3. [ssse3] 2 x pshufb + 1 x por
8111 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8113 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8114 SelectionDAG &DAG) {
8115 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8116 SDValue V1 = SVOp->getOperand(0);
8117 SDValue V2 = SVOp->getOperand(1);
8119 SmallVector<int, 8> MaskVals;
8121 // Determine if more than 1 of the words in each of the low and high quadwords
8122 // of the result come from the same quadword of one of the two inputs. Undef
8123 // mask values count as coming from any quadword, for better codegen.
8125 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8126 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8127 unsigned LoQuad[] = { 0, 0, 0, 0 };
8128 unsigned HiQuad[] = { 0, 0, 0, 0 };
8129 // Indices of quads used.
8130 std::bitset<4> InputQuads;
8131 for (unsigned i = 0; i < 8; ++i) {
8132 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8133 int EltIdx = SVOp->getMaskElt(i);
8134 MaskVals.push_back(EltIdx);
8143 InputQuads.set(EltIdx / 4);
8146 int BestLoQuad = -1;
8147 unsigned MaxQuad = 1;
8148 for (unsigned i = 0; i < 4; ++i) {
8149 if (LoQuad[i] > MaxQuad) {
8151 MaxQuad = LoQuad[i];
8155 int BestHiQuad = -1;
8157 for (unsigned i = 0; i < 4; ++i) {
8158 if (HiQuad[i] > MaxQuad) {
8160 MaxQuad = HiQuad[i];
8164 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8165 // of the two input vectors, shuffle them into one input vector so only a
8166 // single pshufb instruction is necessary. If there are more than 2 input
8167 // quads, disable the next transformation since it does not help SSSE3.
8168 bool V1Used = InputQuads[0] || InputQuads[1];
8169 bool V2Used = InputQuads[2] || InputQuads[3];
8170 if (Subtarget->hasSSSE3()) {
8171 if (InputQuads.count() == 2 && V1Used && V2Used) {
8172 BestLoQuad = InputQuads[0] ? 0 : 1;
8173 BestHiQuad = InputQuads[2] ? 2 : 3;
8175 if (InputQuads.count() > 2) {
8181 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8182 // the shuffle mask. If a quad is scored as -1, that means that it contains
8183 // words from all 4 input quadwords.
8185 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8187 BestLoQuad < 0 ? 0 : BestLoQuad,
8188 BestHiQuad < 0 ? 1 : BestHiQuad
8190 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8191 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8192 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8193 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8195 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8196 // source words for the shuffle, to aid later transformations.
8197 bool AllWordsInNewV = true;
8198 bool InOrder[2] = { true, true };
8199 for (unsigned i = 0; i != 8; ++i) {
8200 int idx = MaskVals[i];
8202 InOrder[i/4] = false;
8203 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8205 AllWordsInNewV = false;
8209 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8210 if (AllWordsInNewV) {
8211 for (int i = 0; i != 8; ++i) {
8212 int idx = MaskVals[i];
8215 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8216 if ((idx != i) && idx < 4)
8218 if ((idx != i) && idx > 3)
8227 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8228 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8229 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8230 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8231 unsigned TargetMask = 0;
8232 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8233 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8234 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8235 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8236 getShufflePSHUFLWImmediate(SVOp);
8237 V1 = NewV.getOperand(0);
8238 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8242 // Promote splats to a larger type which usually leads to more efficient code.
8243 // FIXME: Is this true if pshufb is available?
8244 if (SVOp->isSplat())
8245 return PromoteSplat(SVOp, DAG);
8247 // If we have SSSE3, and all words of the result are from 1 input vector,
8248 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
8249 // is present, fall back to case 4.
8250 if (Subtarget->hasSSSE3()) {
8251 SmallVector<SDValue,16> pshufbMask;
8253 // If we have elements from both input vectors, set the high bit of the
8254 // shuffle mask element to zero out elements that come from V2 in the V1
8255 // mask, and elements that come from V1 in the V2 mask, so that the two
8256 // results can be OR'd together.
8257 bool TwoInputs = V1Used && V2Used;
8258 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8260 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8262 // Calculate the shuffle mask for the second input, shuffle it, and
8263 // OR it with the first shuffled input.
8264 CommuteVectorShuffleMask(MaskVals, 8);
8265 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8266 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8267 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8270 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8271 // and update MaskVals with new element order.
8272 std::bitset<8> InOrder;
8273 if (BestLoQuad >= 0) {
8274 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8275 for (int i = 0; i != 4; ++i) {
8276 int idx = MaskVals[i];
8279 } else if ((idx / 4) == BestLoQuad) {
8284 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8287 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8288 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8289 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8291 getShufflePSHUFLWImmediate(SVOp), DAG);
8295 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8296 // and update MaskVals with the new element order.
8297 if (BestHiQuad >= 0) {
8298 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8299 for (unsigned i = 4; i != 8; ++i) {
8300 int idx = MaskVals[i];
8303 } else if ((idx / 4) == BestHiQuad) {
8304 MaskV[i] = (idx & 3) + 4;
8308 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8311 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8312 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8313 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8315 getShufflePSHUFHWImmediate(SVOp), DAG);
8319 // In case BestHi & BestLo were both -1, which means each quadword has a word
8320 // from each of the four input quadwords, calculate the InOrder bitvector now
8321 // before falling through to the insert/extract cleanup.
8322 if (BestLoQuad == -1 && BestHiQuad == -1) {
8324 for (int i = 0; i != 8; ++i)
8325 if (MaskVals[i] < 0 || MaskVals[i] == i)
8329 // The other elements are put in the right place using pextrw and pinsrw.
8330 for (unsigned i = 0; i != 8; ++i) {
8333 int EltIdx = MaskVals[i];
8336 SDValue ExtOp = (EltIdx < 8) ?
8337 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8338 DAG.getIntPtrConstant(EltIdx)) :
8339 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8340 DAG.getIntPtrConstant(EltIdx - 8));
8341 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8342 DAG.getIntPtrConstant(i));
8347 /// \brief v16i16 shuffles
8349 /// FIXME: We only support generation of a single pshufb currently. We can
8350 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8351 /// well (e.g 2 x pshufb + 1 x por).
8353 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8354 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8355 SDValue V1 = SVOp->getOperand(0);
8356 SDValue V2 = SVOp->getOperand(1);
8359 if (V2.getOpcode() != ISD::UNDEF)
8362 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8363 return getPSHUFB(MaskVals, V1, dl, DAG);
8366 // v16i8 shuffles - Prefer shuffles in the following order:
8367 // 1. [ssse3] 1 x pshufb
8368 // 2. [ssse3] 2 x pshufb + 1 x por
8369 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
8370 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8371 const X86Subtarget* Subtarget,
8372 SelectionDAG &DAG) {
8373 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8374 SDValue V1 = SVOp->getOperand(0);
8375 SDValue V2 = SVOp->getOperand(1);
8377 ArrayRef<int> MaskVals = SVOp->getMask();
8379 // Promote splats to a larger type which usually leads to more efficient code.
8380 // FIXME: Is this true if pshufb is available?
8381 if (SVOp->isSplat())
8382 return PromoteSplat(SVOp, DAG);
8384 // If we have SSSE3, case 1 is generated when all result bytes come from
8385 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
8386 // present, fall back to case 3.
8388 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8389 if (Subtarget->hasSSSE3()) {
8390 SmallVector<SDValue,16> pshufbMask;
8392 // If all result elements are from one input vector, then only translate
8393 // undef mask values to 0x80 (zero out result) in the pshufb mask.
8395 // Otherwise, we have elements from both input vectors, and must zero out
8396 // elements that come from V2 in the first mask, and V1 in the second mask
8397 // so that we can OR them together.
8398 for (unsigned i = 0; i != 16; ++i) {
8399 int EltIdx = MaskVals[i];
8400 if (EltIdx < 0 || EltIdx >= 16)
8402 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8404 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8405 DAG.getNode(ISD::BUILD_VECTOR, dl,
8406 MVT::v16i8, pshufbMask));
8408 // As PSHUFB will zero elements with negative indices, it's safe to ignore
8409 // the 2nd operand if it's undefined or zero.
8410 if (V2.getOpcode() == ISD::UNDEF ||
8411 ISD::isBuildVectorAllZeros(V2.getNode()))
8414 // Calculate the shuffle mask for the second input, shuffle it, and
8415 // OR it with the first shuffled input.
8417 for (unsigned i = 0; i != 16; ++i) {
8418 int EltIdx = MaskVals[i];
8419 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8420 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8422 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8423 DAG.getNode(ISD::BUILD_VECTOR, dl,
8424 MVT::v16i8, pshufbMask));
8425 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8428 // No SSSE3 - Calculate in place words and then fix all out of place words
8429 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
8430 // the 16 different words that comprise the two doublequadword input vectors.
8431 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8432 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8434 for (int i = 0; i != 8; ++i) {
8435 int Elt0 = MaskVals[i*2];
8436 int Elt1 = MaskVals[i*2+1];
8438 // This word of the result is all undef, skip it.
8439 if (Elt0 < 0 && Elt1 < 0)
8442 // This word of the result is already in the correct place, skip it.
8443 if ((Elt0 == i*2) && (Elt1 == i*2+1))
8446 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8447 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8450 // If Elt0 and Elt1 are defined, are consecutive, and can be load
8451 // using a single extract together, load it and store it.
8452 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8453 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8454 DAG.getIntPtrConstant(Elt1 / 2));
8455 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8456 DAG.getIntPtrConstant(i));
8460 // If Elt1 is defined, extract it from the appropriate source. If the
8461 // source byte is not also odd, shift the extracted word left 8 bits
8462 // otherwise clear the bottom 8 bits if we need to do an or.
8464 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8465 DAG.getIntPtrConstant(Elt1 / 2));
8466 if ((Elt1 & 1) == 0)
8467 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8469 TLI.getShiftAmountTy(InsElt.getValueType())));
8471 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8472 DAG.getConstant(0xFF00, MVT::i16));
8474 // If Elt0 is defined, extract it from the appropriate source. If the
8475 // source byte is not also even, shift the extracted word right 8 bits. If
8476 // Elt1 was also defined, OR the extracted values together before
8477 // inserting them in the result.
8479 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8480 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8481 if ((Elt0 & 1) != 0)
8482 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8484 TLI.getShiftAmountTy(InsElt0.getValueType())));
8486 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8487 DAG.getConstant(0x00FF, MVT::i16));
8488 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8491 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8492 DAG.getIntPtrConstant(i));
8494 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8497 // v32i8 shuffles - Translate to VPSHUFB if possible.
8499 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8500 const X86Subtarget *Subtarget,
8501 SelectionDAG &DAG) {
8502 MVT VT = SVOp->getSimpleValueType(0);
8503 SDValue V1 = SVOp->getOperand(0);
8504 SDValue V2 = SVOp->getOperand(1);
8506 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8508 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8509 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8510 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8512 // VPSHUFB may be generated if
8513 // (1) one of input vector is undefined or zeroinitializer.
8514 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8515 // And (2) the mask indexes don't cross the 128-bit lane.
8516 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8517 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8520 if (V1IsAllZero && !V2IsAllZero) {
8521 CommuteVectorShuffleMask(MaskVals, 32);
8524 return getPSHUFB(MaskVals, V1, dl, DAG);
8527 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8528 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8529 /// done when every pair / quad of shuffle mask elements point to elements in
8530 /// the right sequence. e.g.
8531 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8533 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8534 SelectionDAG &DAG) {
8535 MVT VT = SVOp->getSimpleValueType(0);
8537 unsigned NumElems = VT.getVectorNumElements();
8540 switch (VT.SimpleTy) {
8541 default: llvm_unreachable("Unexpected!");
8544 return SDValue(SVOp, 0);
8545 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
8546 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
8547 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
8548 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
8549 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8550 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
8553 SmallVector<int, 8> MaskVec;
8554 for (unsigned i = 0; i != NumElems; i += Scale) {
8556 for (unsigned j = 0; j != Scale; ++j) {
8557 int EltIdx = SVOp->getMaskElt(i+j);
8561 StartIdx = (EltIdx / Scale);
8562 if (EltIdx != (int)(StartIdx*Scale + j))
8565 MaskVec.push_back(StartIdx);
8568 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8569 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8570 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8573 /// getVZextMovL - Return a zero-extending vector move low node.
8575 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8576 SDValue SrcOp, SelectionDAG &DAG,
8577 const X86Subtarget *Subtarget, SDLoc dl) {
8578 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8579 LoadSDNode *LD = nullptr;
8580 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8581 LD = dyn_cast<LoadSDNode>(SrcOp);
8583 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8585 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8586 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8587 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8588 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8589 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8591 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8592 return DAG.getNode(ISD::BITCAST, dl, VT,
8593 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8594 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8602 return DAG.getNode(ISD::BITCAST, dl, VT,
8603 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8604 DAG.getNode(ISD::BITCAST, dl,
8608 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8609 /// which could not be matched by any known target speficic shuffle
8611 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8613 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8614 if (NewOp.getNode())
8617 MVT VT = SVOp->getSimpleValueType(0);
8619 unsigned NumElems = VT.getVectorNumElements();
8620 unsigned NumLaneElems = NumElems / 2;
8623 MVT EltVT = VT.getVectorElementType();
8624 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8627 SmallVector<int, 16> Mask;
8628 for (unsigned l = 0; l < 2; ++l) {
8629 // Build a shuffle mask for the output, discovering on the fly which
8630 // input vectors to use as shuffle operands (recorded in InputUsed).
8631 // If building a suitable shuffle vector proves too hard, then bail
8632 // out with UseBuildVector set.
8633 bool UseBuildVector = false;
8634 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8635 unsigned LaneStart = l * NumLaneElems;
8636 for (unsigned i = 0; i != NumLaneElems; ++i) {
8637 // The mask element. This indexes into the input.
8638 int Idx = SVOp->getMaskElt(i+LaneStart);
8640 // the mask element does not index into any input vector.
8645 // The input vector this mask element indexes into.
8646 int Input = Idx / NumLaneElems;
8648 // Turn the index into an offset from the start of the input vector.
8649 Idx -= Input * NumLaneElems;
8651 // Find or create a shuffle vector operand to hold this input.
8653 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8654 if (InputUsed[OpNo] == Input)
8655 // This input vector is already an operand.
8657 if (InputUsed[OpNo] < 0) {
8658 // Create a new operand for this input vector.
8659 InputUsed[OpNo] = Input;
8664 if (OpNo >= array_lengthof(InputUsed)) {
8665 // More than two input vectors used! Give up on trying to create a
8666 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
8667 UseBuildVector = true;
8671 // Add the mask index for the new shuffle vector.
8672 Mask.push_back(Idx + OpNo * NumLaneElems);
8675 if (UseBuildVector) {
8676 SmallVector<SDValue, 16> SVOps;
8677 for (unsigned i = 0; i != NumLaneElems; ++i) {
8678 // The mask element. This indexes into the input.
8679 int Idx = SVOp->getMaskElt(i+LaneStart);
8681 SVOps.push_back(DAG.getUNDEF(EltVT));
8685 // The input vector this mask element indexes into.
8686 int Input = Idx / NumElems;
8688 // Turn the index into an offset from the start of the input vector.
8689 Idx -= Input * NumElems;
8691 // Extract the vector element by hand.
8692 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8693 SVOp->getOperand(Input),
8694 DAG.getIntPtrConstant(Idx)));
8697 // Construct the output using a BUILD_VECTOR.
8698 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8699 } else if (InputUsed[0] < 0) {
8700 // No input vectors were used! The result is undefined.
8701 Output[l] = DAG.getUNDEF(NVT);
8703 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8704 (InputUsed[0] % 2) * NumLaneElems,
8706 // If only one input was used, use an undefined vector for the other.
8707 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8708 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8709 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8710 // At least one input vector was used. Create a new shuffle vector.
8711 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8717 // Concatenate the result back
8718 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8721 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8722 /// 4 elements, and match them with several different shuffle types.
8724 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8725 SDValue V1 = SVOp->getOperand(0);
8726 SDValue V2 = SVOp->getOperand(1);
8728 MVT VT = SVOp->getSimpleValueType(0);
8730 assert(VT.is128BitVector() && "Unsupported vector size");
8732 std::pair<int, int> Locs[4];
8733 int Mask1[] = { -1, -1, -1, -1 };
8734 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8738 for (unsigned i = 0; i != 4; ++i) {
8739 int Idx = PermMask[i];
8741 Locs[i] = std::make_pair(-1, -1);
8743 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8745 Locs[i] = std::make_pair(0, NumLo);
8749 Locs[i] = std::make_pair(1, NumHi);
8751 Mask1[2+NumHi] = Idx;
8757 if (NumLo <= 2 && NumHi <= 2) {
8758 // If no more than two elements come from either vector. This can be
8759 // implemented with two shuffles. First shuffle gather the elements.
8760 // The second shuffle, which takes the first shuffle as both of its
8761 // vector operands, put the elements into the right order.
8762 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8764 int Mask2[] = { -1, -1, -1, -1 };
8766 for (unsigned i = 0; i != 4; ++i)
8767 if (Locs[i].first != -1) {
8768 unsigned Idx = (i < 2) ? 0 : 4;
8769 Idx += Locs[i].first * 2 + Locs[i].second;
8773 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8776 if (NumLo == 3 || NumHi == 3) {
8777 // Otherwise, we must have three elements from one vector, call it X, and
8778 // one element from the other, call it Y. First, use a shufps to build an
8779 // intermediate vector with the one element from Y and the element from X
8780 // that will be in the same half in the final destination (the indexes don't
8781 // matter). Then, use a shufps to build the final vector, taking the half
8782 // containing the element from Y from the intermediate, and the other half
8785 // Normalize it so the 3 elements come from V1.
8786 CommuteVectorShuffleMask(PermMask, 4);
8790 // Find the element from V2.
8792 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8793 int Val = PermMask[HiIndex];
8800 Mask1[0] = PermMask[HiIndex];
8802 Mask1[2] = PermMask[HiIndex^1];
8804 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8807 Mask1[0] = PermMask[0];
8808 Mask1[1] = PermMask[1];
8809 Mask1[2] = HiIndex & 1 ? 6 : 4;
8810 Mask1[3] = HiIndex & 1 ? 4 : 6;
8811 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8814 Mask1[0] = HiIndex & 1 ? 2 : 0;
8815 Mask1[1] = HiIndex & 1 ? 0 : 2;
8816 Mask1[2] = PermMask[2];
8817 Mask1[3] = PermMask[3];
8822 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8825 // Break it into (shuffle shuffle_hi, shuffle_lo).
8826 int LoMask[] = { -1, -1, -1, -1 };
8827 int HiMask[] = { -1, -1, -1, -1 };
8829 int *MaskPtr = LoMask;
8830 unsigned MaskIdx = 0;
8833 for (unsigned i = 0; i != 4; ++i) {
8840 int Idx = PermMask[i];
8842 Locs[i] = std::make_pair(-1, -1);
8843 } else if (Idx < 4) {
8844 Locs[i] = std::make_pair(MaskIdx, LoIdx);
8845 MaskPtr[LoIdx] = Idx;
8848 Locs[i] = std::make_pair(MaskIdx, HiIdx);
8849 MaskPtr[HiIdx] = Idx;
8854 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8855 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8856 int MaskOps[] = { -1, -1, -1, -1 };
8857 for (unsigned i = 0; i != 4; ++i)
8858 if (Locs[i].first != -1)
8859 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8860 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8863 static bool MayFoldVectorLoad(SDValue V) {
8864 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8865 V = V.getOperand(0);
8867 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8868 V = V.getOperand(0);
8869 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8870 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8871 // BUILD_VECTOR (load), undef
8872 V = V.getOperand(0);
8874 return MayFoldLoad(V);
8878 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8879 MVT VT = Op.getSimpleValueType();
8881 // Canonizalize to v2f64.
8882 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8883 return DAG.getNode(ISD::BITCAST, dl, VT,
8884 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8889 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8891 SDValue V1 = Op.getOperand(0);
8892 SDValue V2 = Op.getOperand(1);
8893 MVT VT = Op.getSimpleValueType();
8895 assert(VT != MVT::v2i64 && "unsupported shuffle type");
8897 if (HasSSE2 && VT == MVT::v2f64)
8898 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8900 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8901 return DAG.getNode(ISD::BITCAST, dl, VT,
8902 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8903 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8904 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8908 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8909 SDValue V1 = Op.getOperand(0);
8910 SDValue V2 = Op.getOperand(1);
8911 MVT VT = Op.getSimpleValueType();
8913 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8914 "unsupported shuffle type");
8916 if (V2.getOpcode() == ISD::UNDEF)
8920 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8924 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8925 SDValue V1 = Op.getOperand(0);
8926 SDValue V2 = Op.getOperand(1);
8927 MVT VT = Op.getSimpleValueType();
8928 unsigned NumElems = VT.getVectorNumElements();
8930 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8931 // operand of these instructions is only memory, so check if there's a
8932 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8934 bool CanFoldLoad = false;
8936 // Trivial case, when V2 comes from a load.
8937 if (MayFoldVectorLoad(V2))
8940 // When V1 is a load, it can be folded later into a store in isel, example:
8941 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8943 // (MOVLPSmr addr:$src1, VR128:$src2)
8944 // So, recognize this potential and also use MOVLPS or MOVLPD
8945 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8948 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8950 if (HasSSE2 && NumElems == 2)
8951 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
8954 // If we don't care about the second element, proceed to use movss.
8955 if (SVOp->getMaskElt(1) != -1)
8956 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
8959 // movl and movlp will both match v2i64, but v2i64 is never matched by
8960 // movl earlier because we make it strict to avoid messing with the movlp load
8961 // folding logic (see the code above getMOVLP call). Match it here then,
8962 // this is horrible, but will stay like this until we move all shuffle
8963 // matching to x86 specific nodes. Note that for the 1st condition all
8964 // types are matched with movsd.
8966 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
8967 // as to remove this logic from here, as much as possible
8968 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
8969 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8970 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8973 assert(VT != MVT::v4i32 && "unsupported shuffle type");
8975 // Invert the operand order and use SHUFPS to match it.
8976 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
8977 getShuffleSHUFImmediate(SVOp), DAG);
8980 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
8981 SelectionDAG &DAG) {
8983 MVT VT = Load->getSimpleValueType(0);
8984 MVT EVT = VT.getVectorElementType();
8985 SDValue Addr = Load->getOperand(1);
8986 SDValue NewAddr = DAG.getNode(
8987 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
8988 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
8991 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
8992 DAG.getMachineFunction().getMachineMemOperand(
8993 Load->getMemOperand(), 0, EVT.getStoreSize()));
8997 // It is only safe to call this function if isINSERTPSMask is true for
8998 // this shufflevector mask.
8999 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9000 SelectionDAG &DAG) {
9001 // Generate an insertps instruction when inserting an f32 from memory onto a
9002 // v4f32 or when copying a member from one v4f32 to another.
9003 // We also use it for transferring i32 from one register to another,
9004 // since it simply copies the same bits.
9005 // If we're transferring an i32 from memory to a specific element in a
9006 // register, we output a generic DAG that will match the PINSRD
9008 MVT VT = SVOp->getSimpleValueType(0);
9009 MVT EVT = VT.getVectorElementType();
9010 SDValue V1 = SVOp->getOperand(0);
9011 SDValue V2 = SVOp->getOperand(1);
9012 auto Mask = SVOp->getMask();
9013 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9014 "unsupported vector type for insertps/pinsrd");
9016 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9017 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9018 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9026 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9029 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9030 "More than one element from V1 and from V2, or no elements from one "
9031 "of the vectors. This case should not have returned true from "
9036 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9039 unsigned SrcIndex = Mask[DestIndex] % 4;
9040 if (MayFoldLoad(From)) {
9041 // Trivial case, when From comes from a load and is only used by the
9042 // shuffle. Make it use insertps from the vector that we need from that
9045 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9046 if (!NewLoad.getNode())
9049 if (EVT == MVT::f32) {
9050 // Create this as a scalar to vector to match the instruction pattern.
9051 SDValue LoadScalarToVector =
9052 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9053 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9054 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9056 } else { // EVT == MVT::i32
9057 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9058 // instruction, to match the PINSRD instruction, which loads an i32 to a
9059 // certain vector element.
9060 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9061 DAG.getConstant(DestIndex, MVT::i32));
9065 // Vector-element-to-vector
9066 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9067 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9070 // Reduce a vector shuffle to zext.
9071 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9072 SelectionDAG &DAG) {
9073 // PMOVZX is only available from SSE41.
9074 if (!Subtarget->hasSSE41())
9077 MVT VT = Op.getSimpleValueType();
9079 // Only AVX2 support 256-bit vector integer extending.
9080 if (!Subtarget->hasInt256() && VT.is256BitVector())
9083 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9085 SDValue V1 = Op.getOperand(0);
9086 SDValue V2 = Op.getOperand(1);
9087 unsigned NumElems = VT.getVectorNumElements();
9089 // Extending is an unary operation and the element type of the source vector
9090 // won't be equal to or larger than i64.
9091 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9092 VT.getVectorElementType() == MVT::i64)
9095 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9096 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9097 while ((1U << Shift) < NumElems) {
9098 if (SVOp->getMaskElt(1U << Shift) == 1)
9101 // The maximal ratio is 8, i.e. from i8 to i64.
9106 // Check the shuffle mask.
9107 unsigned Mask = (1U << Shift) - 1;
9108 for (unsigned i = 0; i != NumElems; ++i) {
9109 int EltIdx = SVOp->getMaskElt(i);
9110 if ((i & Mask) != 0 && EltIdx != -1)
9112 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9116 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9117 MVT NeVT = MVT::getIntegerVT(NBits);
9118 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9120 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9123 // Simplify the operand as it's prepared to be fed into shuffle.
9124 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9125 if (V1.getOpcode() == ISD::BITCAST &&
9126 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9127 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9128 V1.getOperand(0).getOperand(0)
9129 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9130 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9131 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9132 ConstantSDNode *CIdx =
9133 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9134 // If it's foldable, i.e. normal load with single use, we will let code
9135 // selection to fold it. Otherwise, we will short the conversion sequence.
9136 if (CIdx && CIdx->getZExtValue() == 0 &&
9137 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9138 MVT FullVT = V.getSimpleValueType();
9139 MVT V1VT = V1.getSimpleValueType();
9140 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9141 // The "ext_vec_elt" node is wider than the result node.
9142 // In this case we should extract subvector from V.
9143 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9144 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9145 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9146 FullVT.getVectorNumElements()/Ratio);
9147 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9148 DAG.getIntPtrConstant(0));
9150 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9154 return DAG.getNode(ISD::BITCAST, DL, VT,
9155 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9158 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9159 SelectionDAG &DAG) {
9160 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9161 MVT VT = Op.getSimpleValueType();
9163 SDValue V1 = Op.getOperand(0);
9164 SDValue V2 = Op.getOperand(1);
9166 if (isZeroShuffle(SVOp))
9167 return getZeroVector(VT, Subtarget, DAG, dl);
9169 // Handle splat operations
9170 if (SVOp->isSplat()) {
9171 // Use vbroadcast whenever the splat comes from a foldable load
9172 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9173 if (Broadcast.getNode())
9177 // Check integer expanding shuffles.
9178 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9179 if (NewOp.getNode())
9182 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9184 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9186 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9187 if (NewOp.getNode())
9188 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9189 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9190 // FIXME: Figure out a cleaner way to do this.
9191 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9192 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9193 if (NewOp.getNode()) {
9194 MVT NewVT = NewOp.getSimpleValueType();
9195 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9196 NewVT, true, false))
9197 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9200 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9201 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9202 if (NewOp.getNode()) {
9203 MVT NewVT = NewOp.getSimpleValueType();
9204 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9205 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9214 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9215 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9216 SDValue V1 = Op.getOperand(0);
9217 SDValue V2 = Op.getOperand(1);
9218 MVT VT = Op.getSimpleValueType();
9220 unsigned NumElems = VT.getVectorNumElements();
9221 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9222 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9223 bool V1IsSplat = false;
9224 bool V2IsSplat = false;
9225 bool HasSSE2 = Subtarget->hasSSE2();
9226 bool HasFp256 = Subtarget->hasFp256();
9227 bool HasInt256 = Subtarget->hasInt256();
9228 MachineFunction &MF = DAG.getMachineFunction();
9229 bool OptForSize = MF.getFunction()->getAttributes().
9230 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9232 // Check if we should use the experimental vector shuffle lowering. If so,
9233 // delegate completely to that code path.
9234 if (ExperimentalVectorShuffleLowering)
9235 return lowerVectorShuffle(Op, Subtarget, DAG);
9237 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9239 if (V1IsUndef && V2IsUndef)
9240 return DAG.getUNDEF(VT);
9242 // When we create a shuffle node we put the UNDEF node to second operand,
9243 // but in some cases the first operand may be transformed to UNDEF.
9244 // In this case we should just commute the node.
9246 return CommuteVectorShuffle(SVOp, DAG);
9248 // Vector shuffle lowering takes 3 steps:
9250 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9251 // narrowing and commutation of operands should be handled.
9252 // 2) Matching of shuffles with known shuffle masks to x86 target specific
9254 // 3) Rewriting of unmatched masks into new generic shuffle operations,
9255 // so the shuffle can be broken into other shuffles and the legalizer can
9256 // try the lowering again.
9258 // The general idea is that no vector_shuffle operation should be left to
9259 // be matched during isel, all of them must be converted to a target specific
9262 // Normalize the input vectors. Here splats, zeroed vectors, profitable
9263 // narrowing and commutation of operands should be handled. The actual code
9264 // doesn't include all of those, work in progress...
9265 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9266 if (NewOp.getNode())
9269 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9271 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9272 // unpckh_undef). Only use pshufd if speed is more important than size.
9273 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9274 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9275 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9276 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9278 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9279 V2IsUndef && MayFoldVectorLoad(V1))
9280 return getMOVDDup(Op, dl, V1, DAG);
9282 if (isMOVHLPS_v_undef_Mask(M, VT))
9283 return getMOVHighToLow(Op, dl, DAG);
9285 // Use to match splats
9286 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9287 (VT == MVT::v2f64 || VT == MVT::v2i64))
9288 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9290 if (isPSHUFDMask(M, VT)) {
9291 // The actual implementation will match the mask in the if above and then
9292 // during isel it can match several different instructions, not only pshufd
9293 // as its name says, sad but true, emulate the behavior for now...
9294 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9295 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9297 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9299 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9300 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9302 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9303 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9306 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9310 if (isPALIGNRMask(M, VT, Subtarget))
9311 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9312 getShufflePALIGNRImmediate(SVOp),
9315 // Check if this can be converted into a logical shift.
9316 bool isLeft = false;
9319 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9320 if (isShift && ShVal.hasOneUse()) {
9321 // If the shifted value has multiple uses, it may be cheaper to use
9322 // v_set0 + movlhps or movhlps, etc.
9323 MVT EltVT = VT.getVectorElementType();
9324 ShAmt *= EltVT.getSizeInBits();
9325 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9328 if (isMOVLMask(M, VT)) {
9329 if (ISD::isBuildVectorAllZeros(V1.getNode()))
9330 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9331 if (!isMOVLPMask(M, VT)) {
9332 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9333 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9335 if (VT == MVT::v4i32 || VT == MVT::v4f32)
9336 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9340 // FIXME: fold these into legal mask.
9341 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9342 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9344 if (isMOVHLPSMask(M, VT))
9345 return getMOVHighToLow(Op, dl, DAG);
9347 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9348 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9350 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9351 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9353 if (isMOVLPMask(M, VT))
9354 return getMOVLP(Op, dl, DAG, HasSSE2);
9356 if (ShouldXformToMOVHLPS(M, VT) ||
9357 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9358 return CommuteVectorShuffle(SVOp, DAG);
9361 // No better options. Use a vshldq / vsrldq.
9362 MVT EltVT = VT.getVectorElementType();
9363 ShAmt *= EltVT.getSizeInBits();
9364 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9367 bool Commuted = false;
9368 // FIXME: This should also accept a bitcast of a splat? Be careful, not
9369 // 1,1,1,1 -> v8i16 though.
9370 V1IsSplat = isSplatVector(V1.getNode());
9371 V2IsSplat = isSplatVector(V2.getNode());
9373 // Canonicalize the splat or undef, if present, to be on the RHS.
9374 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9375 CommuteVectorShuffleMask(M, NumElems);
9377 std::swap(V1IsSplat, V2IsSplat);
9381 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9382 // Shuffling low element of v1 into undef, just return v1.
9385 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9386 // the instruction selector will not match, so get a canonical MOVL with
9387 // swapped operands to undo the commute.
9388 return getMOVL(DAG, dl, VT, V2, V1);
9391 if (isUNPCKLMask(M, VT, HasInt256))
9392 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9394 if (isUNPCKHMask(M, VT, HasInt256))
9395 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9398 // Normalize mask so all entries that point to V2 points to its first
9399 // element then try to match unpck{h|l} again. If match, return a
9400 // new vector_shuffle with the corrected mask.p
9401 SmallVector<int, 8> NewMask(M.begin(), M.end());
9402 NormalizeMask(NewMask, NumElems);
9403 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9404 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9405 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9406 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9410 // Commute is back and try unpck* again.
9411 // FIXME: this seems wrong.
9412 CommuteVectorShuffleMask(M, NumElems);
9414 std::swap(V1IsSplat, V2IsSplat);
9416 if (isUNPCKLMask(M, VT, HasInt256))
9417 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9419 if (isUNPCKHMask(M, VT, HasInt256))
9420 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9423 // Normalize the node to match x86 shuffle ops if needed
9424 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9425 return CommuteVectorShuffle(SVOp, DAG);
9427 // The checks below are all present in isShuffleMaskLegal, but they are
9428 // inlined here right now to enable us to directly emit target specific
9429 // nodes, and remove one by one until they don't return Op anymore.
9431 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9432 SVOp->getSplatIndex() == 0 && V2IsUndef) {
9433 if (VT == MVT::v2f64 || VT == MVT::v2i64)
9434 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9437 if (isPSHUFHWMask(M, VT, HasInt256))
9438 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9439 getShufflePSHUFHWImmediate(SVOp),
9442 if (isPSHUFLWMask(M, VT, HasInt256))
9443 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9444 getShufflePSHUFLWImmediate(SVOp),
9448 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9450 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9452 if (isSHUFPMask(M, VT))
9453 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9454 getShuffleSHUFImmediate(SVOp), DAG);
9456 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9457 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9458 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9459 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9461 //===--------------------------------------------------------------------===//
9462 // Generate target specific nodes for 128 or 256-bit shuffles only
9463 // supported in the AVX instruction set.
9466 // Handle VMOVDDUPY permutations
9467 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9468 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9470 // Handle VPERMILPS/D* permutations
9471 if (isVPERMILPMask(M, VT)) {
9472 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9473 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9474 getShuffleSHUFImmediate(SVOp), DAG);
9475 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9476 getShuffleSHUFImmediate(SVOp), DAG);
9480 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9481 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9482 Idx*(NumElems/2), DAG, dl);
9484 // Handle VPERM2F128/VPERM2I128 permutations
9485 if (isVPERM2X128Mask(M, VT, HasFp256))
9486 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9487 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9489 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9490 return getINSERTPS(SVOp, dl, DAG);
9493 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9494 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9496 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9497 VT.is512BitVector()) {
9498 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9499 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9500 SmallVector<SDValue, 16> permclMask;
9501 for (unsigned i = 0; i != NumElems; ++i) {
9502 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9505 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9507 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9508 return DAG.getNode(X86ISD::VPERMV, dl, VT,
9509 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9510 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9511 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9514 //===--------------------------------------------------------------------===//
9515 // Since no target specific shuffle was selected for this generic one,
9516 // lower it into other known shuffles. FIXME: this isn't true yet, but
9517 // this is the plan.
9520 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9521 if (VT == MVT::v8i16) {
9522 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9523 if (NewOp.getNode())
9527 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9528 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9529 if (NewOp.getNode())
9533 if (VT == MVT::v16i8) {
9534 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9535 if (NewOp.getNode())
9539 if (VT == MVT::v32i8) {
9540 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9541 if (NewOp.getNode())
9545 // Handle all 128-bit wide vectors with 4 elements, and match them with
9546 // several different shuffle types.
9547 if (NumElems == 4 && VT.is128BitVector())
9548 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9550 // Handle general 256-bit shuffles
9551 if (VT.is256BitVector())
9552 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9557 // This function assumes its argument is a BUILD_VECTOR of constants or
9558 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9560 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9561 unsigned &MaskValue) {
9563 unsigned NumElems = BuildVector->getNumOperands();
9564 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9565 unsigned NumLanes = (NumElems - 1) / 8 + 1;
9566 unsigned NumElemsInLane = NumElems / NumLanes;
9568 // Blend for v16i16 should be symetric for the both lanes.
9569 for (unsigned i = 0; i < NumElemsInLane; ++i) {
9570 SDValue EltCond = BuildVector->getOperand(i);
9571 SDValue SndLaneEltCond =
9572 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9574 int Lane1Cond = -1, Lane2Cond = -1;
9575 if (isa<ConstantSDNode>(EltCond))
9576 Lane1Cond = !isZero(EltCond);
9577 if (isa<ConstantSDNode>(SndLaneEltCond))
9578 Lane2Cond = !isZero(SndLaneEltCond);
9580 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9581 // Lane1Cond != 0, means we want the first argument.
9582 // Lane1Cond == 0, means we want the second argument.
9583 // The encoding of this argument is 0 for the first argument, 1
9584 // for the second. Therefore, invert the condition.
9585 MaskValue |= !Lane1Cond << i;
9586 else if (Lane1Cond < 0)
9587 MaskValue |= !Lane2Cond << i;
9594 // Try to lower a vselect node into a simple blend instruction.
9595 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9596 SelectionDAG &DAG) {
9597 SDValue Cond = Op.getOperand(0);
9598 SDValue LHS = Op.getOperand(1);
9599 SDValue RHS = Op.getOperand(2);
9601 MVT VT = Op.getSimpleValueType();
9602 MVT EltVT = VT.getVectorElementType();
9603 unsigned NumElems = VT.getVectorNumElements();
9605 // There is no blend with immediate in AVX-512.
9606 if (VT.is512BitVector())
9609 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9611 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9614 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9617 // Check the mask for BLEND and build the value.
9618 unsigned MaskValue = 0;
9619 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9622 // Convert i32 vectors to floating point if it is not AVX2.
9623 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9625 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9626 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9628 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9629 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9632 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9633 DAG.getConstant(MaskValue, MVT::i32));
9634 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9637 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9638 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9639 if (BlendOp.getNode())
9642 // Some types for vselect were previously set to Expand, not Legal or
9643 // Custom. Return an empty SDValue so we fall-through to Expand, after
9644 // the Custom lowering phase.
9645 MVT VT = Op.getSimpleValueType();
9646 switch (VT.SimpleTy) {
9654 // We couldn't create a "Blend with immediate" node.
9655 // This node should still be legal, but we'll have to emit a blendv*
9660 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9661 MVT VT = Op.getSimpleValueType();
9664 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9667 if (VT.getSizeInBits() == 8) {
9668 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9669 Op.getOperand(0), Op.getOperand(1));
9670 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9671 DAG.getValueType(VT));
9672 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9675 if (VT.getSizeInBits() == 16) {
9676 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9677 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9679 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9680 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9681 DAG.getNode(ISD::BITCAST, dl,
9685 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9686 Op.getOperand(0), Op.getOperand(1));
9687 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9688 DAG.getValueType(VT));
9689 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9692 if (VT == MVT::f32) {
9693 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9694 // the result back to FR32 register. It's only worth matching if the
9695 // result has a single use which is a store or a bitcast to i32. And in
9696 // the case of a store, it's not worth it if the index is a constant 0,
9697 // because a MOVSSmr can be used instead, which is smaller and faster.
9698 if (!Op.hasOneUse())
9700 SDNode *User = *Op.getNode()->use_begin();
9701 if ((User->getOpcode() != ISD::STORE ||
9702 (isa<ConstantSDNode>(Op.getOperand(1)) &&
9703 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9704 (User->getOpcode() != ISD::BITCAST ||
9705 User->getValueType(0) != MVT::i32))
9707 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9708 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9711 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9714 if (VT == MVT::i32 || VT == MVT::i64) {
9715 // ExtractPS/pextrq works with constant index.
9716 if (isa<ConstantSDNode>(Op.getOperand(1)))
9722 /// Extract one bit from mask vector, like v16i1 or v8i1.
9723 /// AVX-512 feature.
9725 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9726 SDValue Vec = Op.getOperand(0);
9728 MVT VecVT = Vec.getSimpleValueType();
9729 SDValue Idx = Op.getOperand(1);
9730 MVT EltVT = Op.getSimpleValueType();
9732 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9734 // variable index can't be handled in mask registers,
9735 // extend vector to VR512
9736 if (!isa<ConstantSDNode>(Idx)) {
9737 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9738 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9739 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9740 ExtVT.getVectorElementType(), Ext, Idx);
9741 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9744 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9745 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9746 unsigned MaxSift = rc->getSize()*8 - 1;
9747 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9748 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9749 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9750 DAG.getConstant(MaxSift, MVT::i8));
9751 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9752 DAG.getIntPtrConstant(0));
9756 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9757 SelectionDAG &DAG) const {
9759 SDValue Vec = Op.getOperand(0);
9760 MVT VecVT = Vec.getSimpleValueType();
9761 SDValue Idx = Op.getOperand(1);
9763 if (Op.getSimpleValueType() == MVT::i1)
9764 return ExtractBitFromMaskVector(Op, DAG);
9766 if (!isa<ConstantSDNode>(Idx)) {
9767 if (VecVT.is512BitVector() ||
9768 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9769 VecVT.getVectorElementType().getSizeInBits() == 32)) {
9772 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9773 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9774 MaskEltVT.getSizeInBits());
9776 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9777 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9778 getZeroVector(MaskVT, Subtarget, DAG, dl),
9779 Idx, DAG.getConstant(0, getPointerTy()));
9780 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9781 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9782 Perm, DAG.getConstant(0, getPointerTy()));
9787 // If this is a 256-bit vector result, first extract the 128-bit vector and
9788 // then extract the element from the 128-bit vector.
9789 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9791 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9792 // Get the 128-bit vector.
9793 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9794 MVT EltVT = VecVT.getVectorElementType();
9796 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9798 //if (IdxVal >= NumElems/2)
9799 // IdxVal -= NumElems/2;
9800 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9801 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9802 DAG.getConstant(IdxVal, MVT::i32));
9805 assert(VecVT.is128BitVector() && "Unexpected vector length");
9807 if (Subtarget->hasSSE41()) {
9808 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9813 MVT VT = Op.getSimpleValueType();
9814 // TODO: handle v16i8.
9815 if (VT.getSizeInBits() == 16) {
9816 SDValue Vec = Op.getOperand(0);
9817 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9819 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9820 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9821 DAG.getNode(ISD::BITCAST, dl,
9824 // Transform it so it match pextrw which produces a 32-bit result.
9825 MVT EltVT = MVT::i32;
9826 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9827 Op.getOperand(0), Op.getOperand(1));
9828 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9829 DAG.getValueType(VT));
9830 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9833 if (VT.getSizeInBits() == 32) {
9834 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9838 // SHUFPS the element to the lowest double word, then movss.
9839 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9840 MVT VVT = Op.getOperand(0).getSimpleValueType();
9841 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9842 DAG.getUNDEF(VVT), Mask);
9843 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9844 DAG.getIntPtrConstant(0));
9847 if (VT.getSizeInBits() == 64) {
9848 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9849 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9850 // to match extract_elt for f64.
9851 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9855 // UNPCKHPD the element to the lowest double word, then movsd.
9856 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9857 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9858 int Mask[2] = { 1, -1 };
9859 MVT VVT = Op.getOperand(0).getSimpleValueType();
9860 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9861 DAG.getUNDEF(VVT), Mask);
9862 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9863 DAG.getIntPtrConstant(0));
9869 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9870 MVT VT = Op.getSimpleValueType();
9871 MVT EltVT = VT.getVectorElementType();
9874 SDValue N0 = Op.getOperand(0);
9875 SDValue N1 = Op.getOperand(1);
9876 SDValue N2 = Op.getOperand(2);
9878 if (!VT.is128BitVector())
9881 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9882 isa<ConstantSDNode>(N2)) {
9884 if (VT == MVT::v8i16)
9885 Opc = X86ISD::PINSRW;
9886 else if (VT == MVT::v16i8)
9887 Opc = X86ISD::PINSRB;
9889 Opc = X86ISD::PINSRB;
9891 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9893 if (N1.getValueType() != MVT::i32)
9894 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9895 if (N2.getValueType() != MVT::i32)
9896 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9897 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9900 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9901 // Bits [7:6] of the constant are the source select. This will always be
9902 // zero here. The DAG Combiner may combine an extract_elt index into these
9903 // bits. For example (insert (extract, 3), 2) could be matched by putting
9904 // the '3' into bits [7:6] of X86ISD::INSERTPS.
9905 // Bits [5:4] of the constant are the destination select. This is the
9906 // value of the incoming immediate.
9907 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
9908 // combine either bitwise AND or insert of float 0.0 to set these bits.
9909 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9910 // Create this as a scalar to vector..
9911 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9912 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9915 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9916 // PINSR* works with constant index.
9922 /// Insert one bit to mask vector, like v16i1 or v8i1.
9923 /// AVX-512 feature.
9925 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9927 SDValue Vec = Op.getOperand(0);
9928 SDValue Elt = Op.getOperand(1);
9929 SDValue Idx = Op.getOperand(2);
9930 MVT VecVT = Vec.getSimpleValueType();
9932 if (!isa<ConstantSDNode>(Idx)) {
9933 // Non constant index. Extend source and destination,
9934 // insert element and then truncate the result.
9935 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9936 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
9937 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
9938 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9939 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9940 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9943 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9944 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9945 if (Vec.getOpcode() == ISD::UNDEF)
9946 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9947 DAG.getConstant(IdxVal, MVT::i8));
9948 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9949 unsigned MaxSift = rc->getSize()*8 - 1;
9950 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9951 DAG.getConstant(MaxSift, MVT::i8));
9952 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
9953 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9954 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
9957 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
9958 MVT VT = Op.getSimpleValueType();
9959 MVT EltVT = VT.getVectorElementType();
9961 if (EltVT == MVT::i1)
9962 return InsertBitToMaskVector(Op, DAG);
9965 SDValue N0 = Op.getOperand(0);
9966 SDValue N1 = Op.getOperand(1);
9967 SDValue N2 = Op.getOperand(2);
9969 // If this is a 256-bit vector result, first extract the 128-bit vector,
9970 // insert the element into the extracted half and then place it back.
9971 if (VT.is256BitVector() || VT.is512BitVector()) {
9972 if (!isa<ConstantSDNode>(N2))
9975 // Get the desired 128-bit vector half.
9976 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
9977 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
9979 // Insert the element into the desired half.
9980 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
9981 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
9983 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
9984 DAG.getConstant(IdxIn128, MVT::i32));
9986 // Insert the changed part back to the 256-bit vector
9987 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
9990 if (Subtarget->hasSSE41())
9991 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
9993 if (EltVT == MVT::i8)
9996 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
9997 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
9998 // as its second argument.
9999 if (N1.getValueType() != MVT::i32)
10000 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10001 if (N2.getValueType() != MVT::i32)
10002 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10003 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10008 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10010 MVT OpVT = Op.getSimpleValueType();
10012 // If this is a 256-bit vector result, first insert into a 128-bit
10013 // vector and then insert into the 256-bit vector.
10014 if (!OpVT.is128BitVector()) {
10015 // Insert into a 128-bit vector.
10016 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10017 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10018 OpVT.getVectorNumElements() / SizeFactor);
10020 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10022 // Insert the 128-bit vector.
10023 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10026 if (OpVT == MVT::v1i64 &&
10027 Op.getOperand(0).getValueType() == MVT::i64)
10028 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10030 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10031 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10032 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10033 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10036 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10037 // a simple subregister reference or explicit instructions to grab
10038 // upper bits of a vector.
10039 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10040 SelectionDAG &DAG) {
10042 SDValue In = Op.getOperand(0);
10043 SDValue Idx = Op.getOperand(1);
10044 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10045 MVT ResVT = Op.getSimpleValueType();
10046 MVT InVT = In.getSimpleValueType();
10048 if (Subtarget->hasFp256()) {
10049 if (ResVT.is128BitVector() &&
10050 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10051 isa<ConstantSDNode>(Idx)) {
10052 return Extract128BitVector(In, IdxVal, DAG, dl);
10054 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10055 isa<ConstantSDNode>(Idx)) {
10056 return Extract256BitVector(In, IdxVal, DAG, dl);
10062 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10063 // simple superregister reference or explicit instructions to insert
10064 // the upper bits of a vector.
10065 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10066 SelectionDAG &DAG) {
10067 if (Subtarget->hasFp256()) {
10068 SDLoc dl(Op.getNode());
10069 SDValue Vec = Op.getNode()->getOperand(0);
10070 SDValue SubVec = Op.getNode()->getOperand(1);
10071 SDValue Idx = Op.getNode()->getOperand(2);
10073 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10074 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10075 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10076 isa<ConstantSDNode>(Idx)) {
10077 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10078 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10081 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10082 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10083 isa<ConstantSDNode>(Idx)) {
10084 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10085 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10091 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10092 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10093 // one of the above mentioned nodes. It has to be wrapped because otherwise
10094 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10095 // be used to form addressing mode. These wrapped nodes will be selected
10098 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10099 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10101 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10102 // global base reg.
10103 unsigned char OpFlag = 0;
10104 unsigned WrapperKind = X86ISD::Wrapper;
10105 CodeModel::Model M = DAG.getTarget().getCodeModel();
10107 if (Subtarget->isPICStyleRIPRel() &&
10108 (M == CodeModel::Small || M == CodeModel::Kernel))
10109 WrapperKind = X86ISD::WrapperRIP;
10110 else if (Subtarget->isPICStyleGOT())
10111 OpFlag = X86II::MO_GOTOFF;
10112 else if (Subtarget->isPICStyleStubPIC())
10113 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10115 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10116 CP->getAlignment(),
10117 CP->getOffset(), OpFlag);
10119 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10120 // With PIC, the address is actually $g + Offset.
10122 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10123 DAG.getNode(X86ISD::GlobalBaseReg,
10124 SDLoc(), getPointerTy()),
10131 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10132 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10134 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10135 // global base reg.
10136 unsigned char OpFlag = 0;
10137 unsigned WrapperKind = X86ISD::Wrapper;
10138 CodeModel::Model M = DAG.getTarget().getCodeModel();
10140 if (Subtarget->isPICStyleRIPRel() &&
10141 (M == CodeModel::Small || M == CodeModel::Kernel))
10142 WrapperKind = X86ISD::WrapperRIP;
10143 else if (Subtarget->isPICStyleGOT())
10144 OpFlag = X86II::MO_GOTOFF;
10145 else if (Subtarget->isPICStyleStubPIC())
10146 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10148 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10151 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10153 // With PIC, the address is actually $g + Offset.
10155 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10156 DAG.getNode(X86ISD::GlobalBaseReg,
10157 SDLoc(), getPointerTy()),
10164 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10165 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10167 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10168 // global base reg.
10169 unsigned char OpFlag = 0;
10170 unsigned WrapperKind = X86ISD::Wrapper;
10171 CodeModel::Model M = DAG.getTarget().getCodeModel();
10173 if (Subtarget->isPICStyleRIPRel() &&
10174 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10175 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10176 OpFlag = X86II::MO_GOTPCREL;
10177 WrapperKind = X86ISD::WrapperRIP;
10178 } else if (Subtarget->isPICStyleGOT()) {
10179 OpFlag = X86II::MO_GOT;
10180 } else if (Subtarget->isPICStyleStubPIC()) {
10181 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10182 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10183 OpFlag = X86II::MO_DARWIN_NONLAZY;
10186 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10189 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10191 // With PIC, the address is actually $g + Offset.
10192 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10193 !Subtarget->is64Bit()) {
10194 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10195 DAG.getNode(X86ISD::GlobalBaseReg,
10196 SDLoc(), getPointerTy()),
10200 // For symbols that require a load from a stub to get the address, emit the
10202 if (isGlobalStubReference(OpFlag))
10203 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10204 MachinePointerInfo::getGOT(), false, false, false, 0);
10210 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10211 // Create the TargetBlockAddressAddress node.
10212 unsigned char OpFlags =
10213 Subtarget->ClassifyBlockAddressReference();
10214 CodeModel::Model M = DAG.getTarget().getCodeModel();
10215 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10216 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10218 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10221 if (Subtarget->isPICStyleRIPRel() &&
10222 (M == CodeModel::Small || M == CodeModel::Kernel))
10223 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10225 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10227 // With PIC, the address is actually $g + Offset.
10228 if (isGlobalRelativeToPICBase(OpFlags)) {
10229 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10230 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10238 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10239 int64_t Offset, SelectionDAG &DAG) const {
10240 // Create the TargetGlobalAddress node, folding in the constant
10241 // offset if it is legal.
10242 unsigned char OpFlags =
10243 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10244 CodeModel::Model M = DAG.getTarget().getCodeModel();
10246 if (OpFlags == X86II::MO_NO_FLAG &&
10247 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10248 // A direct static reference to a global.
10249 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10252 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10255 if (Subtarget->isPICStyleRIPRel() &&
10256 (M == CodeModel::Small || M == CodeModel::Kernel))
10257 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10259 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10261 // With PIC, the address is actually $g + Offset.
10262 if (isGlobalRelativeToPICBase(OpFlags)) {
10263 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10264 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10268 // For globals that require a load from a stub to get the address, emit the
10270 if (isGlobalStubReference(OpFlags))
10271 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10272 MachinePointerInfo::getGOT(), false, false, false, 0);
10274 // If there was a non-zero offset that we didn't fold, create an explicit
10275 // addition for it.
10277 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10278 DAG.getConstant(Offset, getPointerTy()));
10284 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10285 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10286 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10287 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10291 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10292 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10293 unsigned char OperandFlags, bool LocalDynamic = false) {
10294 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10295 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10297 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10298 GA->getValueType(0),
10302 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10306 SDValue Ops[] = { Chain, TGA, *InFlag };
10307 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10309 SDValue Ops[] = { Chain, TGA };
10310 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10313 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10314 MFI->setAdjustsStack(true);
10316 SDValue Flag = Chain.getValue(1);
10317 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10320 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10322 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10325 SDLoc dl(GA); // ? function entry point might be better
10326 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10327 DAG.getNode(X86ISD::GlobalBaseReg,
10328 SDLoc(), PtrVT), InFlag);
10329 InFlag = Chain.getValue(1);
10331 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10334 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10336 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10338 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10339 X86::RAX, X86II::MO_TLSGD);
10342 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10348 // Get the start address of the TLS block for this module.
10349 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10350 .getInfo<X86MachineFunctionInfo>();
10351 MFI->incNumLocalDynamicTLSAccesses();
10355 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10356 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10359 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10360 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10361 InFlag = Chain.getValue(1);
10362 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10363 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10366 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10370 unsigned char OperandFlags = X86II::MO_DTPOFF;
10371 unsigned WrapperKind = X86ISD::Wrapper;
10372 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10373 GA->getValueType(0),
10374 GA->getOffset(), OperandFlags);
10375 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10377 // Add x@dtpoff with the base.
10378 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10381 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10382 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10383 const EVT PtrVT, TLSModel::Model model,
10384 bool is64Bit, bool isPIC) {
10387 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10388 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10389 is64Bit ? 257 : 256));
10391 SDValue ThreadPointer =
10392 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10393 MachinePointerInfo(Ptr), false, false, false, 0);
10395 unsigned char OperandFlags = 0;
10396 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10398 unsigned WrapperKind = X86ISD::Wrapper;
10399 if (model == TLSModel::LocalExec) {
10400 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10401 } else if (model == TLSModel::InitialExec) {
10403 OperandFlags = X86II::MO_GOTTPOFF;
10404 WrapperKind = X86ISD::WrapperRIP;
10406 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10409 llvm_unreachable("Unexpected model");
10412 // emit "addl x@ntpoff,%eax" (local exec)
10413 // or "addl x@indntpoff,%eax" (initial exec)
10414 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10416 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10417 GA->getOffset(), OperandFlags);
10418 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10420 if (model == TLSModel::InitialExec) {
10421 if (isPIC && !is64Bit) {
10422 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10423 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10427 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10428 MachinePointerInfo::getGOT(), false, false, false, 0);
10431 // The address of the thread local variable is the add of the thread
10432 // pointer with the offset of the variable.
10433 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10437 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10439 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10440 const GlobalValue *GV = GA->getGlobal();
10442 if (Subtarget->isTargetELF()) {
10443 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10446 case TLSModel::GeneralDynamic:
10447 if (Subtarget->is64Bit())
10448 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10449 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10450 case TLSModel::LocalDynamic:
10451 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10452 Subtarget->is64Bit());
10453 case TLSModel::InitialExec:
10454 case TLSModel::LocalExec:
10455 return LowerToTLSExecModel(
10456 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10457 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10459 llvm_unreachable("Unknown TLS model.");
10462 if (Subtarget->isTargetDarwin()) {
10463 // Darwin only has one model of TLS. Lower to that.
10464 unsigned char OpFlag = 0;
10465 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10466 X86ISD::WrapperRIP : X86ISD::Wrapper;
10468 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10469 // global base reg.
10470 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10471 !Subtarget->is64Bit();
10473 OpFlag = X86II::MO_TLVP_PIC_BASE;
10475 OpFlag = X86II::MO_TLVP;
10477 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10478 GA->getValueType(0),
10479 GA->getOffset(), OpFlag);
10480 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10482 // With PIC32, the address is actually $g + Offset.
10484 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10485 DAG.getNode(X86ISD::GlobalBaseReg,
10486 SDLoc(), getPointerTy()),
10489 // Lowering the machine isd will make sure everything is in the right
10491 SDValue Chain = DAG.getEntryNode();
10492 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10493 SDValue Args[] = { Chain, Offset };
10494 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10496 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10497 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10498 MFI->setAdjustsStack(true);
10500 // And our return value (tls address) is in the standard call return value
10502 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10503 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10504 Chain.getValue(1));
10507 if (Subtarget->isTargetKnownWindowsMSVC() ||
10508 Subtarget->isTargetWindowsGNU()) {
10509 // Just use the implicit TLS architecture
10510 // Need to generate someting similar to:
10511 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10513 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
10514 // mov rcx, qword [rdx+rcx*8]
10515 // mov eax, .tls$:tlsvar
10516 // [rax+rcx] contains the address
10517 // Windows 64bit: gs:0x58
10518 // Windows 32bit: fs:__tls_array
10521 SDValue Chain = DAG.getEntryNode();
10523 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10524 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10525 // use its literal value of 0x2C.
10526 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10527 ? Type::getInt8PtrTy(*DAG.getContext(),
10529 : Type::getInt32PtrTy(*DAG.getContext(),
10533 Subtarget->is64Bit()
10534 ? DAG.getIntPtrConstant(0x58)
10535 : (Subtarget->isTargetWindowsGNU()
10536 ? DAG.getIntPtrConstant(0x2C)
10537 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10539 SDValue ThreadPointer =
10540 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10541 MachinePointerInfo(Ptr), false, false, false, 0);
10543 // Load the _tls_index variable
10544 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10545 if (Subtarget->is64Bit())
10546 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10547 IDX, MachinePointerInfo(), MVT::i32,
10550 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10551 false, false, false, 0);
10553 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10555 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10557 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10558 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10559 false, false, false, 0);
10561 // Get the offset of start of .tls section
10562 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10563 GA->getValueType(0),
10564 GA->getOffset(), X86II::MO_SECREL);
10565 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10567 // The address of the thread local variable is the add of the thread
10568 // pointer with the offset of the variable.
10569 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10572 llvm_unreachable("TLS not implemented for this target.");
10575 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10576 /// and take a 2 x i32 value to shift plus a shift amount.
10577 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10578 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10579 MVT VT = Op.getSimpleValueType();
10580 unsigned VTBits = VT.getSizeInBits();
10582 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10583 SDValue ShOpLo = Op.getOperand(0);
10584 SDValue ShOpHi = Op.getOperand(1);
10585 SDValue ShAmt = Op.getOperand(2);
10586 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10587 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10589 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10590 DAG.getConstant(VTBits - 1, MVT::i8));
10591 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10592 DAG.getConstant(VTBits - 1, MVT::i8))
10593 : DAG.getConstant(0, VT);
10595 SDValue Tmp2, Tmp3;
10596 if (Op.getOpcode() == ISD::SHL_PARTS) {
10597 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10598 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10600 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10601 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10604 // If the shift amount is larger or equal than the width of a part we can't
10605 // rely on the results of shld/shrd. Insert a test and select the appropriate
10606 // values for large shift amounts.
10607 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10608 DAG.getConstant(VTBits, MVT::i8));
10609 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10610 AndNode, DAG.getConstant(0, MVT::i8));
10613 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10614 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10615 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10617 if (Op.getOpcode() == ISD::SHL_PARTS) {
10618 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10619 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10621 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10622 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10625 SDValue Ops[2] = { Lo, Hi };
10626 return DAG.getMergeValues(Ops, dl);
10629 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10630 SelectionDAG &DAG) const {
10631 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10633 if (SrcVT.isVector())
10636 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10637 "Unknown SINT_TO_FP to lower!");
10639 // These are really Legal; return the operand so the caller accepts it as
10641 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10643 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10644 Subtarget->is64Bit()) {
10649 unsigned Size = SrcVT.getSizeInBits()/8;
10650 MachineFunction &MF = DAG.getMachineFunction();
10651 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10652 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10653 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10655 MachinePointerInfo::getFixedStack(SSFI),
10657 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10660 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10662 SelectionDAG &DAG) const {
10666 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10668 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10670 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10672 unsigned ByteSize = SrcVT.getSizeInBits()/8;
10674 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10675 MachineMemOperand *MMO;
10677 int SSFI = FI->getIndex();
10679 DAG.getMachineFunction()
10680 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10681 MachineMemOperand::MOLoad, ByteSize, ByteSize);
10683 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10684 StackSlot = StackSlot.getOperand(1);
10686 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10687 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10689 Tys, Ops, SrcVT, MMO);
10692 Chain = Result.getValue(1);
10693 SDValue InFlag = Result.getValue(2);
10695 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10696 // shouldn't be necessary except that RFP cannot be live across
10697 // multiple blocks. When stackifier is fixed, they can be uncoupled.
10698 MachineFunction &MF = DAG.getMachineFunction();
10699 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10700 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10701 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10702 Tys = DAG.getVTList(MVT::Other);
10704 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10706 MachineMemOperand *MMO =
10707 DAG.getMachineFunction()
10708 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10709 MachineMemOperand::MOStore, SSFISize, SSFISize);
10711 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10712 Ops, Op.getValueType(), MMO);
10713 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10714 MachinePointerInfo::getFixedStack(SSFI),
10715 false, false, false, 0);
10721 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10722 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10723 SelectionDAG &DAG) const {
10724 // This algorithm is not obvious. Here it is what we're trying to output:
10727 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10728 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10730 haddpd %xmm0, %xmm0
10732 pshufd $0x4e, %xmm0, %xmm1
10738 LLVMContext *Context = DAG.getContext();
10740 // Build some magic constants.
10741 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10742 Constant *C0 = ConstantDataVector::get(*Context, CV0);
10743 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10745 SmallVector<Constant*,2> CV1;
10747 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10748 APInt(64, 0x4330000000000000ULL))));
10750 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10751 APInt(64, 0x4530000000000000ULL))));
10752 Constant *C1 = ConstantVector::get(CV1);
10753 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10755 // Load the 64-bit value into an XMM register.
10756 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10758 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10759 MachinePointerInfo::getConstantPool(),
10760 false, false, false, 16);
10761 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10762 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10765 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10766 MachinePointerInfo::getConstantPool(),
10767 false, false, false, 16);
10768 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10769 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10772 if (Subtarget->hasSSE3()) {
10773 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10774 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10776 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10777 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10779 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10780 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10784 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10785 DAG.getIntPtrConstant(0));
10788 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10789 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10790 SelectionDAG &DAG) const {
10792 // FP constant to bias correct the final result.
10793 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10796 // Load the 32-bit value into an XMM register.
10797 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10800 // Zero out the upper parts of the register.
10801 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10803 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10804 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10805 DAG.getIntPtrConstant(0));
10807 // Or the load with the bias.
10808 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10809 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10810 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10811 MVT::v2f64, Load)),
10812 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10813 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10814 MVT::v2f64, Bias)));
10815 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10816 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10817 DAG.getIntPtrConstant(0));
10819 // Subtract the bias.
10820 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10822 // Handle final rounding.
10823 EVT DestVT = Op.getValueType();
10825 if (DestVT.bitsLT(MVT::f64))
10826 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10827 DAG.getIntPtrConstant(0));
10828 if (DestVT.bitsGT(MVT::f64))
10829 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10831 // Handle final rounding.
10835 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10836 SelectionDAG &DAG) const {
10837 SDValue N0 = Op.getOperand(0);
10838 MVT SVT = N0.getSimpleValueType();
10841 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10842 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10843 "Custom UINT_TO_FP is not supported!");
10845 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10846 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10847 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10850 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10851 SelectionDAG &DAG) const {
10852 SDValue N0 = Op.getOperand(0);
10855 if (Op.getValueType().isVector())
10856 return lowerUINT_TO_FP_vec(Op, DAG);
10858 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10859 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10860 // the optimization here.
10861 if (DAG.SignBitIsZero(N0))
10862 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10864 MVT SrcVT = N0.getSimpleValueType();
10865 MVT DstVT = Op.getSimpleValueType();
10866 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10867 return LowerUINT_TO_FP_i64(Op, DAG);
10868 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10869 return LowerUINT_TO_FP_i32(Op, DAG);
10870 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10873 // Make a 64-bit buffer, and use it to build an FILD.
10874 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10875 if (SrcVT == MVT::i32) {
10876 SDValue WordOff = DAG.getConstant(4, getPointerTy());
10877 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10878 getPointerTy(), StackSlot, WordOff);
10879 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10880 StackSlot, MachinePointerInfo(),
10882 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10883 OffsetSlot, MachinePointerInfo(),
10885 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10889 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10890 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10891 StackSlot, MachinePointerInfo(),
10893 // For i64 source, we need to add the appropriate power of 2 if the input
10894 // was negative. This is the same as the optimization in
10895 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10896 // we must be careful to do the computation in x87 extended precision, not
10897 // in SSE. (The generic code can't know it's OK to do this, or how to.)
10898 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10899 MachineMemOperand *MMO =
10900 DAG.getMachineFunction()
10901 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10902 MachineMemOperand::MOLoad, 8, 8);
10904 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10905 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10906 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10909 APInt FF(32, 0x5F800000ULL);
10911 // Check whether the sign bit is set.
10912 SDValue SignSet = DAG.getSetCC(dl,
10913 getSetCCResultType(*DAG.getContext(), MVT::i64),
10914 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10917 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10918 SDValue FudgePtr = DAG.getConstantPool(
10919 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10922 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10923 SDValue Zero = DAG.getIntPtrConstant(0);
10924 SDValue Four = DAG.getIntPtrConstant(4);
10925 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10927 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10929 // Load the value out, extending it from f32 to f80.
10930 // FIXME: Avoid the extend by constructing the right constant pool?
10931 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10932 FudgePtr, MachinePointerInfo::getConstantPool(),
10933 MVT::f32, false, false, 4);
10934 // Extend everything to 80 bits to force it to be done on x87.
10935 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10936 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10939 std::pair<SDValue,SDValue>
10940 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10941 bool IsSigned, bool IsReplace) const {
10944 EVT DstTy = Op.getValueType();
10946 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10947 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
10951 assert(DstTy.getSimpleVT() <= MVT::i64 &&
10952 DstTy.getSimpleVT() >= MVT::i16 &&
10953 "Unknown FP_TO_INT to lower!");
10955 // These are really Legal.
10956 if (DstTy == MVT::i32 &&
10957 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10958 return std::make_pair(SDValue(), SDValue());
10959 if (Subtarget->is64Bit() &&
10960 DstTy == MVT::i64 &&
10961 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10962 return std::make_pair(SDValue(), SDValue());
10964 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
10965 // stack slot, or into the FTOL runtime function.
10966 MachineFunction &MF = DAG.getMachineFunction();
10967 unsigned MemSize = DstTy.getSizeInBits()/8;
10968 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
10969 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10972 if (!IsSigned && isIntegerTypeFTOL(DstTy))
10973 Opc = X86ISD::WIN_FTOL;
10975 switch (DstTy.getSimpleVT().SimpleTy) {
10976 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
10977 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
10978 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
10979 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
10982 SDValue Chain = DAG.getEntryNode();
10983 SDValue Value = Op.getOperand(0);
10984 EVT TheVT = Op.getOperand(0).getValueType();
10985 // FIXME This causes a redundant load/store if the SSE-class value is already
10986 // in memory, such as if it is on the callstack.
10987 if (isScalarFPTypeInSSEReg(TheVT)) {
10988 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
10989 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
10990 MachinePointerInfo::getFixedStack(SSFI),
10992 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
10994 Chain, StackSlot, DAG.getValueType(TheVT)
10997 MachineMemOperand *MMO =
10998 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10999 MachineMemOperand::MOLoad, MemSize, MemSize);
11000 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11001 Chain = Value.getValue(1);
11002 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11003 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11006 MachineMemOperand *MMO =
11007 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11008 MachineMemOperand::MOStore, MemSize, MemSize);
11010 if (Opc != X86ISD::WIN_FTOL) {
11011 // Build the FP_TO_INT*_IN_MEM
11012 SDValue Ops[] = { Chain, Value, StackSlot };
11013 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11015 return std::make_pair(FIST, StackSlot);
11017 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11018 DAG.getVTList(MVT::Other, MVT::Glue),
11020 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11021 MVT::i32, ftol.getValue(1));
11022 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11023 MVT::i32, eax.getValue(2));
11024 SDValue Ops[] = { eax, edx };
11025 SDValue pair = IsReplace
11026 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11027 : DAG.getMergeValues(Ops, DL);
11028 return std::make_pair(pair, SDValue());
11032 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11033 const X86Subtarget *Subtarget) {
11034 MVT VT = Op->getSimpleValueType(0);
11035 SDValue In = Op->getOperand(0);
11036 MVT InVT = In.getSimpleValueType();
11039 // Optimize vectors in AVX mode:
11042 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11043 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11044 // Concat upper and lower parts.
11047 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11048 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11049 // Concat upper and lower parts.
11052 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11053 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11054 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11057 if (Subtarget->hasInt256())
11058 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11060 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11061 SDValue Undef = DAG.getUNDEF(InVT);
11062 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11063 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11064 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11066 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11067 VT.getVectorNumElements()/2);
11069 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11070 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11072 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11075 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11076 SelectionDAG &DAG) {
11077 MVT VT = Op->getSimpleValueType(0);
11078 SDValue In = Op->getOperand(0);
11079 MVT InVT = In.getSimpleValueType();
11081 unsigned int NumElts = VT.getVectorNumElements();
11082 if (NumElts != 8 && NumElts != 16)
11085 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11086 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11088 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11089 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11090 // Now we have only mask extension
11091 assert(InVT.getVectorElementType() == MVT::i1);
11092 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11093 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11094 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11095 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11096 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11097 MachinePointerInfo::getConstantPool(),
11098 false, false, false, Alignment);
11100 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11101 if (VT.is512BitVector())
11103 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11106 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11107 SelectionDAG &DAG) {
11108 if (Subtarget->hasFp256()) {
11109 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11117 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11118 SelectionDAG &DAG) {
11120 MVT VT = Op.getSimpleValueType();
11121 SDValue In = Op.getOperand(0);
11122 MVT SVT = In.getSimpleValueType();
11124 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11125 return LowerZERO_EXTEND_AVX512(Op, DAG);
11127 if (Subtarget->hasFp256()) {
11128 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11133 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11134 VT.getVectorNumElements() != SVT.getVectorNumElements());
11138 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11140 MVT VT = Op.getSimpleValueType();
11141 SDValue In = Op.getOperand(0);
11142 MVT InVT = In.getSimpleValueType();
11144 if (VT == MVT::i1) {
11145 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11146 "Invalid scalar TRUNCATE operation");
11147 if (InVT == MVT::i32)
11149 if (InVT.getSizeInBits() == 64)
11150 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11151 else if (InVT.getSizeInBits() < 32)
11152 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11153 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11155 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11156 "Invalid TRUNCATE operation");
11158 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11159 if (VT.getVectorElementType().getSizeInBits() >=8)
11160 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11162 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11163 unsigned NumElts = InVT.getVectorNumElements();
11164 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11165 if (InVT.getSizeInBits() < 512) {
11166 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11167 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11171 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11172 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11173 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11174 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11175 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11176 MachinePointerInfo::getConstantPool(),
11177 false, false, false, Alignment);
11178 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11179 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11180 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11183 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11184 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11185 if (Subtarget->hasInt256()) {
11186 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11187 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11188 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11190 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11191 DAG.getIntPtrConstant(0));
11194 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11195 DAG.getIntPtrConstant(0));
11196 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11197 DAG.getIntPtrConstant(2));
11198 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11199 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11200 static const int ShufMask[] = {0, 2, 4, 6};
11201 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11204 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11205 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11206 if (Subtarget->hasInt256()) {
11207 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11209 SmallVector<SDValue,32> pshufbMask;
11210 for (unsigned i = 0; i < 2; ++i) {
11211 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11212 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11213 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11214 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11215 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11216 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11217 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11218 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11219 for (unsigned j = 0; j < 8; ++j)
11220 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11222 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11223 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11224 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11226 static const int ShufMask[] = {0, 2, -1, -1};
11227 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11229 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11230 DAG.getIntPtrConstant(0));
11231 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11234 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11235 DAG.getIntPtrConstant(0));
11237 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11238 DAG.getIntPtrConstant(4));
11240 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11241 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11243 // The PSHUFB mask:
11244 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11245 -1, -1, -1, -1, -1, -1, -1, -1};
11247 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11248 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11249 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11251 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11252 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11254 // The MOVLHPS Mask:
11255 static const int ShufMask2[] = {0, 1, 4, 5};
11256 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11257 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11260 // Handle truncation of V256 to V128 using shuffles.
11261 if (!VT.is128BitVector() || !InVT.is256BitVector())
11264 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11266 unsigned NumElems = VT.getVectorNumElements();
11267 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11269 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11270 // Prepare truncation shuffle mask
11271 for (unsigned i = 0; i != NumElems; ++i)
11272 MaskVec[i] = i * 2;
11273 SDValue V = DAG.getVectorShuffle(NVT, DL,
11274 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11275 DAG.getUNDEF(NVT), &MaskVec[0]);
11276 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11277 DAG.getIntPtrConstant(0));
11280 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11281 SelectionDAG &DAG) const {
11282 assert(!Op.getSimpleValueType().isVector());
11284 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11285 /*IsSigned=*/ true, /*IsReplace=*/ false);
11286 SDValue FIST = Vals.first, StackSlot = Vals.second;
11287 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11288 if (!FIST.getNode()) return Op;
11290 if (StackSlot.getNode())
11291 // Load the result.
11292 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11293 FIST, StackSlot, MachinePointerInfo(),
11294 false, false, false, 0);
11296 // The node is the result.
11300 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11301 SelectionDAG &DAG) const {
11302 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11303 /*IsSigned=*/ false, /*IsReplace=*/ false);
11304 SDValue FIST = Vals.first, StackSlot = Vals.second;
11305 assert(FIST.getNode() && "Unexpected failure");
11307 if (StackSlot.getNode())
11308 // Load the result.
11309 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11310 FIST, StackSlot, MachinePointerInfo(),
11311 false, false, false, 0);
11313 // The node is the result.
11317 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11319 MVT VT = Op.getSimpleValueType();
11320 SDValue In = Op.getOperand(0);
11321 MVT SVT = In.getSimpleValueType();
11323 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11325 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11326 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11327 In, DAG.getUNDEF(SVT)));
11330 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11331 LLVMContext *Context = DAG.getContext();
11333 MVT VT = Op.getSimpleValueType();
11335 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11336 if (VT.isVector()) {
11337 EltVT = VT.getVectorElementType();
11338 NumElts = VT.getVectorNumElements();
11341 if (EltVT == MVT::f64)
11342 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11343 APInt(64, ~(1ULL << 63))));
11345 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11346 APInt(32, ~(1U << 31))));
11347 C = ConstantVector::getSplat(NumElts, C);
11348 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11349 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11350 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11351 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11352 MachinePointerInfo::getConstantPool(),
11353 false, false, false, Alignment);
11354 if (VT.isVector()) {
11355 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11356 return DAG.getNode(ISD::BITCAST, dl, VT,
11357 DAG.getNode(ISD::AND, dl, ANDVT,
11358 DAG.getNode(ISD::BITCAST, dl, ANDVT,
11360 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11362 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11365 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11366 LLVMContext *Context = DAG.getContext();
11368 MVT VT = Op.getSimpleValueType();
11370 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11371 if (VT.isVector()) {
11372 EltVT = VT.getVectorElementType();
11373 NumElts = VT.getVectorNumElements();
11376 if (EltVT == MVT::f64)
11377 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11378 APInt(64, 1ULL << 63)));
11380 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11381 APInt(32, 1U << 31)));
11382 C = ConstantVector::getSplat(NumElts, C);
11383 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11384 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11385 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11386 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11387 MachinePointerInfo::getConstantPool(),
11388 false, false, false, Alignment);
11389 if (VT.isVector()) {
11390 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11391 return DAG.getNode(ISD::BITCAST, dl, VT,
11392 DAG.getNode(ISD::XOR, dl, XORVT,
11393 DAG.getNode(ISD::BITCAST, dl, XORVT,
11395 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11398 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11401 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11402 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11403 LLVMContext *Context = DAG.getContext();
11404 SDValue Op0 = Op.getOperand(0);
11405 SDValue Op1 = Op.getOperand(1);
11407 MVT VT = Op.getSimpleValueType();
11408 MVT SrcVT = Op1.getSimpleValueType();
11410 // If second operand is smaller, extend it first.
11411 if (SrcVT.bitsLT(VT)) {
11412 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11415 // And if it is bigger, shrink it first.
11416 if (SrcVT.bitsGT(VT)) {
11417 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11421 // At this point the operands and the result should have the same
11422 // type, and that won't be f80 since that is not custom lowered.
11424 // First get the sign bit of second operand.
11425 SmallVector<Constant*,4> CV;
11426 if (SrcVT == MVT::f64) {
11427 const fltSemantics &Sem = APFloat::IEEEdouble;
11428 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11429 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11431 const fltSemantics &Sem = APFloat::IEEEsingle;
11432 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11433 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11434 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11435 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11437 Constant *C = ConstantVector::get(CV);
11438 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11439 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11440 MachinePointerInfo::getConstantPool(),
11441 false, false, false, 16);
11442 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11444 // Shift sign bit right or left if the two operands have different types.
11445 if (SrcVT.bitsGT(VT)) {
11446 // Op0 is MVT::f32, Op1 is MVT::f64.
11447 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11448 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11449 DAG.getConstant(32, MVT::i32));
11450 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11451 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11452 DAG.getIntPtrConstant(0));
11455 // Clear first operand sign bit.
11457 if (VT == MVT::f64) {
11458 const fltSemantics &Sem = APFloat::IEEEdouble;
11459 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11460 APInt(64, ~(1ULL << 63)))));
11461 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11463 const fltSemantics &Sem = APFloat::IEEEsingle;
11464 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11465 APInt(32, ~(1U << 31)))));
11466 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11467 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11468 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11470 C = ConstantVector::get(CV);
11471 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11472 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11473 MachinePointerInfo::getConstantPool(),
11474 false, false, false, 16);
11475 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11477 // Or the value with the sign bit.
11478 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11481 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11482 SDValue N0 = Op.getOperand(0);
11484 MVT VT = Op.getSimpleValueType();
11486 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11487 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11488 DAG.getConstant(1, VT));
11489 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11492 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11494 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11495 SelectionDAG &DAG) {
11496 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11498 if (!Subtarget->hasSSE41())
11501 if (!Op->hasOneUse())
11504 SDNode *N = Op.getNode();
11507 SmallVector<SDValue, 8> Opnds;
11508 DenseMap<SDValue, unsigned> VecInMap;
11509 SmallVector<SDValue, 8> VecIns;
11510 EVT VT = MVT::Other;
11512 // Recognize a special case where a vector is casted into wide integer to
11514 Opnds.push_back(N->getOperand(0));
11515 Opnds.push_back(N->getOperand(1));
11517 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11518 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11519 // BFS traverse all OR'd operands.
11520 if (I->getOpcode() == ISD::OR) {
11521 Opnds.push_back(I->getOperand(0));
11522 Opnds.push_back(I->getOperand(1));
11523 // Re-evaluate the number of nodes to be traversed.
11524 e += 2; // 2 more nodes (LHS and RHS) are pushed.
11528 // Quit if a non-EXTRACT_VECTOR_ELT
11529 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11532 // Quit if without a constant index.
11533 SDValue Idx = I->getOperand(1);
11534 if (!isa<ConstantSDNode>(Idx))
11537 SDValue ExtractedFromVec = I->getOperand(0);
11538 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11539 if (M == VecInMap.end()) {
11540 VT = ExtractedFromVec.getValueType();
11541 // Quit if not 128/256-bit vector.
11542 if (!VT.is128BitVector() && !VT.is256BitVector())
11544 // Quit if not the same type.
11545 if (VecInMap.begin() != VecInMap.end() &&
11546 VT != VecInMap.begin()->first.getValueType())
11548 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11549 VecIns.push_back(ExtractedFromVec);
11551 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11554 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11555 "Not extracted from 128-/256-bit vector.");
11557 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11559 for (DenseMap<SDValue, unsigned>::const_iterator
11560 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11561 // Quit if not all elements are used.
11562 if (I->second != FullMask)
11566 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11568 // Cast all vectors into TestVT for PTEST.
11569 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11570 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11572 // If more than one full vectors are evaluated, OR them first before PTEST.
11573 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11574 // Each iteration will OR 2 nodes and append the result until there is only
11575 // 1 node left, i.e. the final OR'd value of all vectors.
11576 SDValue LHS = VecIns[Slot];
11577 SDValue RHS = VecIns[Slot + 1];
11578 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11581 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11582 VecIns.back(), VecIns.back());
11585 /// \brief return true if \c Op has a use that doesn't just read flags.
11586 static bool hasNonFlagsUse(SDValue Op) {
11587 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11589 SDNode *User = *UI;
11590 unsigned UOpNo = UI.getOperandNo();
11591 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11592 // Look pass truncate.
11593 UOpNo = User->use_begin().getOperandNo();
11594 User = *User->use_begin();
11597 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11598 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11604 /// Emit nodes that will be selected as "test Op0,Op0", or something
11606 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11607 SelectionDAG &DAG) const {
11608 if (Op.getValueType() == MVT::i1)
11609 // KORTEST instruction should be selected
11610 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11611 DAG.getConstant(0, Op.getValueType()));
11613 // CF and OF aren't always set the way we want. Determine which
11614 // of these we need.
11615 bool NeedCF = false;
11616 bool NeedOF = false;
11619 case X86::COND_A: case X86::COND_AE:
11620 case X86::COND_B: case X86::COND_BE:
11623 case X86::COND_G: case X86::COND_GE:
11624 case X86::COND_L: case X86::COND_LE:
11625 case X86::COND_O: case X86::COND_NO: {
11626 // Check if we really need to set the
11627 // Overflow flag. If NoSignedWrap is present
11628 // that is not actually needed.
11629 switch (Op->getOpcode()) {
11634 const BinaryWithFlagsSDNode *BinNode =
11635 cast<BinaryWithFlagsSDNode>(Op.getNode());
11636 if (BinNode->hasNoSignedWrap())
11646 // See if we can use the EFLAGS value from the operand instead of
11647 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11648 // we prove that the arithmetic won't overflow, we can't use OF or CF.
11649 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11650 // Emit a CMP with 0, which is the TEST pattern.
11651 //if (Op.getValueType() == MVT::i1)
11652 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11653 // DAG.getConstant(0, MVT::i1));
11654 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11655 DAG.getConstant(0, Op.getValueType()));
11657 unsigned Opcode = 0;
11658 unsigned NumOperands = 0;
11660 // Truncate operations may prevent the merge of the SETCC instruction
11661 // and the arithmetic instruction before it. Attempt to truncate the operands
11662 // of the arithmetic instruction and use a reduced bit-width instruction.
11663 bool NeedTruncation = false;
11664 SDValue ArithOp = Op;
11665 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11666 SDValue Arith = Op->getOperand(0);
11667 // Both the trunc and the arithmetic op need to have one user each.
11668 if (Arith->hasOneUse())
11669 switch (Arith.getOpcode()) {
11676 NeedTruncation = true;
11682 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11683 // which may be the result of a CAST. We use the variable 'Op', which is the
11684 // non-casted variable when we check for possible users.
11685 switch (ArithOp.getOpcode()) {
11687 // Due to an isel shortcoming, be conservative if this add is likely to be
11688 // selected as part of a load-modify-store instruction. When the root node
11689 // in a match is a store, isel doesn't know how to remap non-chain non-flag
11690 // uses of other nodes in the match, such as the ADD in this case. This
11691 // leads to the ADD being left around and reselected, with the result being
11692 // two adds in the output. Alas, even if none our users are stores, that
11693 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
11694 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
11695 // climbing the DAG back to the root, and it doesn't seem to be worth the
11697 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11698 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11699 if (UI->getOpcode() != ISD::CopyToReg &&
11700 UI->getOpcode() != ISD::SETCC &&
11701 UI->getOpcode() != ISD::STORE)
11704 if (ConstantSDNode *C =
11705 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11706 // An add of one will be selected as an INC.
11707 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11708 Opcode = X86ISD::INC;
11713 // An add of negative one (subtract of one) will be selected as a DEC.
11714 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11715 Opcode = X86ISD::DEC;
11721 // Otherwise use a regular EFLAGS-setting add.
11722 Opcode = X86ISD::ADD;
11727 // If we have a constant logical shift that's only used in a comparison
11728 // against zero turn it into an equivalent AND. This allows turning it into
11729 // a TEST instruction later.
11730 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11731 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11732 EVT VT = Op.getValueType();
11733 unsigned BitWidth = VT.getSizeInBits();
11734 unsigned ShAmt = Op->getConstantOperandVal(1);
11735 if (ShAmt >= BitWidth) // Avoid undefined shifts.
11737 APInt Mask = ArithOp.getOpcode() == ISD::SRL
11738 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11739 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11740 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11742 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11743 DAG.getConstant(Mask, VT));
11744 DAG.ReplaceAllUsesWith(Op, New);
11750 // If the primary and result isn't used, don't bother using X86ISD::AND,
11751 // because a TEST instruction will be better.
11752 if (!hasNonFlagsUse(Op))
11758 // Due to the ISEL shortcoming noted above, be conservative if this op is
11759 // likely to be selected as part of a load-modify-store instruction.
11760 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11761 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11762 if (UI->getOpcode() == ISD::STORE)
11765 // Otherwise use a regular EFLAGS-setting instruction.
11766 switch (ArithOp.getOpcode()) {
11767 default: llvm_unreachable("unexpected operator!");
11768 case ISD::SUB: Opcode = X86ISD::SUB; break;
11769 case ISD::XOR: Opcode = X86ISD::XOR; break;
11770 case ISD::AND: Opcode = X86ISD::AND; break;
11772 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11773 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11774 if (EFLAGS.getNode())
11777 Opcode = X86ISD::OR;
11791 return SDValue(Op.getNode(), 1);
11797 // If we found that truncation is beneficial, perform the truncation and
11799 if (NeedTruncation) {
11800 EVT VT = Op.getValueType();
11801 SDValue WideVal = Op->getOperand(0);
11802 EVT WideVT = WideVal.getValueType();
11803 unsigned ConvertedOp = 0;
11804 // Use a target machine opcode to prevent further DAGCombine
11805 // optimizations that may separate the arithmetic operations
11806 // from the setcc node.
11807 switch (WideVal.getOpcode()) {
11809 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11810 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11811 case ISD::AND: ConvertedOp = X86ISD::AND; break;
11812 case ISD::OR: ConvertedOp = X86ISD::OR; break;
11813 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11817 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11818 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11819 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11820 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11821 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11827 // Emit a CMP with 0, which is the TEST pattern.
11828 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11829 DAG.getConstant(0, Op.getValueType()));
11831 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11832 SmallVector<SDValue, 4> Ops;
11833 for (unsigned i = 0; i != NumOperands; ++i)
11834 Ops.push_back(Op.getOperand(i));
11836 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11837 DAG.ReplaceAllUsesWith(Op, New);
11838 return SDValue(New.getNode(), 1);
11841 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11843 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11844 SDLoc dl, SelectionDAG &DAG) const {
11845 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11846 if (C->getAPIntValue() == 0)
11847 return EmitTest(Op0, X86CC, dl, DAG);
11849 if (Op0.getValueType() == MVT::i1)
11850 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11853 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11854 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11855 // Do the comparison at i32 if it's smaller, besides the Atom case.
11856 // This avoids subregister aliasing issues. Keep the smaller reference
11857 // if we're optimizing for size, however, as that'll allow better folding
11858 // of memory operations.
11859 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11860 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11861 AttributeSet::FunctionIndex, Attribute::MinSize) &&
11862 !Subtarget->isAtom()) {
11863 unsigned ExtendOp =
11864 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11865 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11866 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11868 // Use SUB instead of CMP to enable CSE between SUB and CMP.
11869 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11870 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11872 return SDValue(Sub.getNode(), 1);
11874 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11877 /// Convert a comparison if required by the subtarget.
11878 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11879 SelectionDAG &DAG) const {
11880 // If the subtarget does not support the FUCOMI instruction, floating-point
11881 // comparisons have to be converted.
11882 if (Subtarget->hasCMov() ||
11883 Cmp.getOpcode() != X86ISD::CMP ||
11884 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11885 !Cmp.getOperand(1).getValueType().isFloatingPoint())
11888 // The instruction selector will select an FUCOM instruction instead of
11889 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11890 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11891 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11893 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11894 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11895 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11896 DAG.getConstant(8, MVT::i8));
11897 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11898 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11901 static bool isAllOnes(SDValue V) {
11902 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11903 return C && C->isAllOnesValue();
11906 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11907 /// if it's possible.
11908 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11909 SDLoc dl, SelectionDAG &DAG) const {
11910 SDValue Op0 = And.getOperand(0);
11911 SDValue Op1 = And.getOperand(1);
11912 if (Op0.getOpcode() == ISD::TRUNCATE)
11913 Op0 = Op0.getOperand(0);
11914 if (Op1.getOpcode() == ISD::TRUNCATE)
11915 Op1 = Op1.getOperand(0);
11918 if (Op1.getOpcode() == ISD::SHL)
11919 std::swap(Op0, Op1);
11920 if (Op0.getOpcode() == ISD::SHL) {
11921 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11922 if (And00C->getZExtValue() == 1) {
11923 // If we looked past a truncate, check that it's only truncating away
11925 unsigned BitWidth = Op0.getValueSizeInBits();
11926 unsigned AndBitWidth = And.getValueSizeInBits();
11927 if (BitWidth > AndBitWidth) {
11929 DAG.computeKnownBits(Op0, Zeros, Ones);
11930 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11934 RHS = Op0.getOperand(1);
11936 } else if (Op1.getOpcode() == ISD::Constant) {
11937 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11938 uint64_t AndRHSVal = AndRHS->getZExtValue();
11939 SDValue AndLHS = Op0;
11941 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11942 LHS = AndLHS.getOperand(0);
11943 RHS = AndLHS.getOperand(1);
11946 // Use BT if the immediate can't be encoded in a TEST instruction.
11947 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
11949 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
11953 if (LHS.getNode()) {
11954 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
11955 // instruction. Since the shift amount is in-range-or-undefined, we know
11956 // that doing a bittest on the i32 value is ok. We extend to i32 because
11957 // the encoding for the i16 version is larger than the i32 version.
11958 // Also promote i16 to i32 for performance / code size reason.
11959 if (LHS.getValueType() == MVT::i8 ||
11960 LHS.getValueType() == MVT::i16)
11961 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
11963 // If the operand types disagree, extend the shift amount to match. Since
11964 // BT ignores high bits (like shifts) we can use anyextend.
11965 if (LHS.getValueType() != RHS.getValueType())
11966 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
11968 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
11969 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
11970 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11971 DAG.getConstant(Cond, MVT::i8), BT);
11977 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
11979 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
11984 // SSE Condition code mapping:
11993 switch (SetCCOpcode) {
11994 default: llvm_unreachable("Unexpected SETCC condition");
11996 case ISD::SETEQ: SSECC = 0; break;
11998 case ISD::SETGT: Swap = true; // Fallthrough
12000 case ISD::SETOLT: SSECC = 1; break;
12002 case ISD::SETGE: Swap = true; // Fallthrough
12004 case ISD::SETOLE: SSECC = 2; break;
12005 case ISD::SETUO: SSECC = 3; break;
12007 case ISD::SETNE: SSECC = 4; break;
12008 case ISD::SETULE: Swap = true; // Fallthrough
12009 case ISD::SETUGE: SSECC = 5; break;
12010 case ISD::SETULT: Swap = true; // Fallthrough
12011 case ISD::SETUGT: SSECC = 6; break;
12012 case ISD::SETO: SSECC = 7; break;
12014 case ISD::SETONE: SSECC = 8; break;
12017 std::swap(Op0, Op1);
12022 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12023 // ones, and then concatenate the result back.
12024 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12025 MVT VT = Op.getSimpleValueType();
12027 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12028 "Unsupported value type for operation");
12030 unsigned NumElems = VT.getVectorNumElements();
12032 SDValue CC = Op.getOperand(2);
12034 // Extract the LHS vectors
12035 SDValue LHS = Op.getOperand(0);
12036 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12037 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12039 // Extract the RHS vectors
12040 SDValue RHS = Op.getOperand(1);
12041 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12042 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12044 // Issue the operation on the smaller types and concatenate the result back
12045 MVT EltVT = VT.getVectorElementType();
12046 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12047 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12048 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12049 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12052 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12053 const X86Subtarget *Subtarget) {
12054 SDValue Op0 = Op.getOperand(0);
12055 SDValue Op1 = Op.getOperand(1);
12056 SDValue CC = Op.getOperand(2);
12057 MVT VT = Op.getSimpleValueType();
12060 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12061 Op.getValueType().getScalarType() == MVT::i1 &&
12062 "Cannot set masked compare for this operation");
12064 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12066 bool Unsigned = false;
12069 switch (SetCCOpcode) {
12070 default: llvm_unreachable("Unexpected SETCC condition");
12071 case ISD::SETNE: SSECC = 4; break;
12072 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12073 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12074 case ISD::SETLT: Swap = true; //fall-through
12075 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12076 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12077 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12078 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12079 case ISD::SETULE: Unsigned = true; //fall-through
12080 case ISD::SETLE: SSECC = 2; break;
12084 std::swap(Op0, Op1);
12086 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12087 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12088 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12089 DAG.getConstant(SSECC, MVT::i8));
12092 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12093 /// operand \p Op1. If non-trivial (for example because it's not constant)
12094 /// return an empty value.
12095 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12097 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12101 MVT VT = Op1.getSimpleValueType();
12102 MVT EVT = VT.getVectorElementType();
12103 unsigned n = VT.getVectorNumElements();
12104 SmallVector<SDValue, 8> ULTOp1;
12106 for (unsigned i = 0; i < n; ++i) {
12107 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12108 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12111 // Avoid underflow.
12112 APInt Val = Elt->getAPIntValue();
12116 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12119 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12122 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12123 SelectionDAG &DAG) {
12124 SDValue Op0 = Op.getOperand(0);
12125 SDValue Op1 = Op.getOperand(1);
12126 SDValue CC = Op.getOperand(2);
12127 MVT VT = Op.getSimpleValueType();
12128 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12129 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12134 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12135 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12138 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12139 unsigned Opc = X86ISD::CMPP;
12140 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12141 assert(VT.getVectorNumElements() <= 16);
12142 Opc = X86ISD::CMPM;
12144 // In the two special cases we can't handle, emit two comparisons.
12147 unsigned CombineOpc;
12148 if (SetCCOpcode == ISD::SETUEQ) {
12149 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12151 assert(SetCCOpcode == ISD::SETONE);
12152 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12155 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12156 DAG.getConstant(CC0, MVT::i8));
12157 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12158 DAG.getConstant(CC1, MVT::i8));
12159 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12161 // Handle all other FP comparisons here.
12162 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12163 DAG.getConstant(SSECC, MVT::i8));
12166 // Break 256-bit integer vector compare into smaller ones.
12167 if (VT.is256BitVector() && !Subtarget->hasInt256())
12168 return Lower256IntVSETCC(Op, DAG);
12170 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12171 EVT OpVT = Op1.getValueType();
12172 if (Subtarget->hasAVX512()) {
12173 if (Op1.getValueType().is512BitVector() ||
12174 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12175 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12177 // In AVX-512 architecture setcc returns mask with i1 elements,
12178 // But there is no compare instruction for i8 and i16 elements.
12179 // We are not talking about 512-bit operands in this case, these
12180 // types are illegal.
12182 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12183 OpVT.getVectorElementType().getSizeInBits() >= 8))
12184 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12185 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12188 // We are handling one of the integer comparisons here. Since SSE only has
12189 // GT and EQ comparisons for integer, swapping operands and multiple
12190 // operations may be required for some comparisons.
12192 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12193 bool Subus = false;
12195 switch (SetCCOpcode) {
12196 default: llvm_unreachable("Unexpected SETCC condition");
12197 case ISD::SETNE: Invert = true;
12198 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12199 case ISD::SETLT: Swap = true;
12200 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12201 case ISD::SETGE: Swap = true;
12202 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12203 Invert = true; break;
12204 case ISD::SETULT: Swap = true;
12205 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12206 FlipSigns = true; break;
12207 case ISD::SETUGE: Swap = true;
12208 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12209 FlipSigns = true; Invert = true; break;
12212 // Special case: Use min/max operations for SETULE/SETUGE
12213 MVT VET = VT.getVectorElementType();
12215 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12216 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12219 switch (SetCCOpcode) {
12221 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12222 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12225 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12228 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12229 if (!MinMax && hasSubus) {
12230 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12232 // t = psubus Op0, Op1
12233 // pcmpeq t, <0..0>
12234 switch (SetCCOpcode) {
12236 case ISD::SETULT: {
12237 // If the comparison is against a constant we can turn this into a
12238 // setule. With psubus, setule does not require a swap. This is
12239 // beneficial because the constant in the register is no longer
12240 // destructed as the destination so it can be hoisted out of a loop.
12241 // Only do this pre-AVX since vpcmp* is no longer destructive.
12242 if (Subtarget->hasAVX())
12244 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12245 if (ULEOp1.getNode()) {
12247 Subus = true; Invert = false; Swap = false;
12251 // Psubus is better than flip-sign because it requires no inversion.
12252 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12253 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12257 Opc = X86ISD::SUBUS;
12263 std::swap(Op0, Op1);
12265 // Check that the operation in question is available (most are plain SSE2,
12266 // but PCMPGTQ and PCMPEQQ have different requirements).
12267 if (VT == MVT::v2i64) {
12268 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12269 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12271 // First cast everything to the right type.
12272 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12273 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12275 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12276 // bits of the inputs before performing those operations. The lower
12277 // compare is always unsigned.
12280 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12282 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12283 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12284 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12285 Sign, Zero, Sign, Zero);
12287 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12288 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12290 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12291 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12292 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12294 // Create masks for only the low parts/high parts of the 64 bit integers.
12295 static const int MaskHi[] = { 1, 1, 3, 3 };
12296 static const int MaskLo[] = { 0, 0, 2, 2 };
12297 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12298 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12299 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12301 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12302 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12305 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12307 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12310 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12311 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12312 // pcmpeqd + pshufd + pand.
12313 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12315 // First cast everything to the right type.
12316 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12317 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12320 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12322 // Make sure the lower and upper halves are both all-ones.
12323 static const int Mask[] = { 1, 0, 3, 2 };
12324 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12325 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12328 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12330 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12334 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12335 // bits of the inputs before performing those operations.
12337 EVT EltVT = VT.getVectorElementType();
12338 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12339 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12340 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12343 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12345 // If the logical-not of the result is required, perform that now.
12347 Result = DAG.getNOT(dl, Result, VT);
12350 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12353 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12354 getZeroVector(VT, Subtarget, DAG, dl));
12359 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12361 MVT VT = Op.getSimpleValueType();
12363 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12365 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12366 && "SetCC type must be 8-bit or 1-bit integer");
12367 SDValue Op0 = Op.getOperand(0);
12368 SDValue Op1 = Op.getOperand(1);
12370 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12372 // Optimize to BT if possible.
12373 // Lower (X & (1 << N)) == 0 to BT(X, N).
12374 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12375 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12376 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12377 Op1.getOpcode() == ISD::Constant &&
12378 cast<ConstantSDNode>(Op1)->isNullValue() &&
12379 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12380 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12381 if (NewSetCC.getNode())
12385 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
12387 if (Op1.getOpcode() == ISD::Constant &&
12388 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12389 cast<ConstantSDNode>(Op1)->isNullValue()) &&
12390 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12392 // If the input is a setcc, then reuse the input setcc or use a new one with
12393 // the inverted condition.
12394 if (Op0.getOpcode() == X86ISD::SETCC) {
12395 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12396 bool Invert = (CC == ISD::SETNE) ^
12397 cast<ConstantSDNode>(Op1)->isNullValue();
12401 CCode = X86::GetOppositeBranchCondition(CCode);
12402 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12403 DAG.getConstant(CCode, MVT::i8),
12404 Op0.getOperand(1));
12406 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12410 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12411 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12412 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12414 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12415 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12418 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12419 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12420 if (X86CC == X86::COND_INVALID)
12423 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12424 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12425 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12426 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12428 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12432 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12433 static bool isX86LogicalCmp(SDValue Op) {
12434 unsigned Opc = Op.getNode()->getOpcode();
12435 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12436 Opc == X86ISD::SAHF)
12438 if (Op.getResNo() == 1 &&
12439 (Opc == X86ISD::ADD ||
12440 Opc == X86ISD::SUB ||
12441 Opc == X86ISD::ADC ||
12442 Opc == X86ISD::SBB ||
12443 Opc == X86ISD::SMUL ||
12444 Opc == X86ISD::UMUL ||
12445 Opc == X86ISD::INC ||
12446 Opc == X86ISD::DEC ||
12447 Opc == X86ISD::OR ||
12448 Opc == X86ISD::XOR ||
12449 Opc == X86ISD::AND))
12452 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12458 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12459 if (V.getOpcode() != ISD::TRUNCATE)
12462 SDValue VOp0 = V.getOperand(0);
12463 unsigned InBits = VOp0.getValueSizeInBits();
12464 unsigned Bits = V.getValueSizeInBits();
12465 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12468 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12469 bool addTest = true;
12470 SDValue Cond = Op.getOperand(0);
12471 SDValue Op1 = Op.getOperand(1);
12472 SDValue Op2 = Op.getOperand(2);
12474 EVT VT = Op1.getValueType();
12477 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12478 // are available. Otherwise fp cmovs get lowered into a less efficient branch
12479 // sequence later on.
12480 if (Cond.getOpcode() == ISD::SETCC &&
12481 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12482 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12483 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12484 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12485 int SSECC = translateX86FSETCC(
12486 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12489 if (Subtarget->hasAVX512()) {
12490 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12491 DAG.getConstant(SSECC, MVT::i8));
12492 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12494 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12495 DAG.getConstant(SSECC, MVT::i8));
12496 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12497 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12498 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12502 if (Cond.getOpcode() == ISD::SETCC) {
12503 SDValue NewCond = LowerSETCC(Cond, DAG);
12504 if (NewCond.getNode())
12508 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12509 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12510 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12511 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12512 if (Cond.getOpcode() == X86ISD::SETCC &&
12513 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12514 isZero(Cond.getOperand(1).getOperand(1))) {
12515 SDValue Cmp = Cond.getOperand(1);
12517 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12519 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12520 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12521 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12523 SDValue CmpOp0 = Cmp.getOperand(0);
12524 // Apply further optimizations for special cases
12525 // (select (x != 0), -1, 0) -> neg & sbb
12526 // (select (x == 0), 0, -1) -> neg & sbb
12527 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12528 if (YC->isNullValue() &&
12529 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12530 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12531 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12532 DAG.getConstant(0, CmpOp0.getValueType()),
12534 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12535 DAG.getConstant(X86::COND_B, MVT::i8),
12536 SDValue(Neg.getNode(), 1));
12540 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12541 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12542 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12544 SDValue Res = // Res = 0 or -1.
12545 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12546 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12548 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12549 Res = DAG.getNOT(DL, Res, Res.getValueType());
12551 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12552 if (!N2C || !N2C->isNullValue())
12553 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12558 // Look past (and (setcc_carry (cmp ...)), 1).
12559 if (Cond.getOpcode() == ISD::AND &&
12560 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12561 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12562 if (C && C->getAPIntValue() == 1)
12563 Cond = Cond.getOperand(0);
12566 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12567 // setting operand in place of the X86ISD::SETCC.
12568 unsigned CondOpcode = Cond.getOpcode();
12569 if (CondOpcode == X86ISD::SETCC ||
12570 CondOpcode == X86ISD::SETCC_CARRY) {
12571 CC = Cond.getOperand(0);
12573 SDValue Cmp = Cond.getOperand(1);
12574 unsigned Opc = Cmp.getOpcode();
12575 MVT VT = Op.getSimpleValueType();
12577 bool IllegalFPCMov = false;
12578 if (VT.isFloatingPoint() && !VT.isVector() &&
12579 !isScalarFPTypeInSSEReg(VT)) // FPStack?
12580 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12582 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12583 Opc == X86ISD::BT) { // FIXME
12587 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12588 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12589 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12590 Cond.getOperand(0).getValueType() != MVT::i8)) {
12591 SDValue LHS = Cond.getOperand(0);
12592 SDValue RHS = Cond.getOperand(1);
12593 unsigned X86Opcode;
12596 switch (CondOpcode) {
12597 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12598 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12599 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12600 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12601 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12602 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12603 default: llvm_unreachable("unexpected overflowing operator");
12605 if (CondOpcode == ISD::UMULO)
12606 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12609 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12611 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12613 if (CondOpcode == ISD::UMULO)
12614 Cond = X86Op.getValue(2);
12616 Cond = X86Op.getValue(1);
12618 CC = DAG.getConstant(X86Cond, MVT::i8);
12623 // Look pass the truncate if the high bits are known zero.
12624 if (isTruncWithZeroHighBitsInput(Cond, DAG))
12625 Cond = Cond.getOperand(0);
12627 // We know the result of AND is compared against zero. Try to match
12629 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12630 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12631 if (NewSetCC.getNode()) {
12632 CC = NewSetCC.getOperand(0);
12633 Cond = NewSetCC.getOperand(1);
12640 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12641 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12644 // a < b ? -1 : 0 -> RES = ~setcc_carry
12645 // a < b ? 0 : -1 -> RES = setcc_carry
12646 // a >= b ? -1 : 0 -> RES = setcc_carry
12647 // a >= b ? 0 : -1 -> RES = ~setcc_carry
12648 if (Cond.getOpcode() == X86ISD::SUB) {
12649 Cond = ConvertCmpIfNecessary(Cond, DAG);
12650 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12652 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12653 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12654 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12655 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12656 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12657 return DAG.getNOT(DL, Res, Res.getValueType());
12662 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12663 // widen the cmov and push the truncate through. This avoids introducing a new
12664 // branch during isel and doesn't add any extensions.
12665 if (Op.getValueType() == MVT::i8 &&
12666 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12667 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12668 if (T1.getValueType() == T2.getValueType() &&
12669 // Blacklist CopyFromReg to avoid partial register stalls.
12670 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12671 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12672 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12673 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12677 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12678 // condition is true.
12679 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12680 SDValue Ops[] = { Op2, Op1, CC, Cond };
12681 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12684 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12685 MVT VT = Op->getSimpleValueType(0);
12686 SDValue In = Op->getOperand(0);
12687 MVT InVT = In.getSimpleValueType();
12690 unsigned int NumElts = VT.getVectorNumElements();
12691 if (NumElts != 8 && NumElts != 16)
12694 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12695 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12697 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12698 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12700 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12701 Constant *C = ConstantInt::get(*DAG.getContext(),
12702 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12704 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12705 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12706 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12707 MachinePointerInfo::getConstantPool(),
12708 false, false, false, Alignment);
12709 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12710 if (VT.is512BitVector())
12712 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12715 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12716 SelectionDAG &DAG) {
12717 MVT VT = Op->getSimpleValueType(0);
12718 SDValue In = Op->getOperand(0);
12719 MVT InVT = In.getSimpleValueType();
12722 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12723 return LowerSIGN_EXTEND_AVX512(Op, DAG);
12725 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12726 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12727 (VT != MVT::v16i16 || InVT != MVT::v16i8))
12730 if (Subtarget->hasInt256())
12731 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12733 // Optimize vectors in AVX mode
12734 // Sign extend v8i16 to v8i32 and
12737 // Divide input vector into two parts
12738 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12739 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12740 // concat the vectors to original VT
12742 unsigned NumElems = InVT.getVectorNumElements();
12743 SDValue Undef = DAG.getUNDEF(InVT);
12745 SmallVector<int,8> ShufMask1(NumElems, -1);
12746 for (unsigned i = 0; i != NumElems/2; ++i)
12749 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12751 SmallVector<int,8> ShufMask2(NumElems, -1);
12752 for (unsigned i = 0; i != NumElems/2; ++i)
12753 ShufMask2[i] = i + NumElems/2;
12755 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12757 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12758 VT.getVectorNumElements()/2);
12760 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12761 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12763 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12766 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12767 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12768 // from the AND / OR.
12769 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12770 Opc = Op.getOpcode();
12771 if (Opc != ISD::OR && Opc != ISD::AND)
12773 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12774 Op.getOperand(0).hasOneUse() &&
12775 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12776 Op.getOperand(1).hasOneUse());
12779 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12780 // 1 and that the SETCC node has a single use.
12781 static bool isXor1OfSetCC(SDValue Op) {
12782 if (Op.getOpcode() != ISD::XOR)
12784 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12785 if (N1C && N1C->getAPIntValue() == 1) {
12786 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12787 Op.getOperand(0).hasOneUse();
12792 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12793 bool addTest = true;
12794 SDValue Chain = Op.getOperand(0);
12795 SDValue Cond = Op.getOperand(1);
12796 SDValue Dest = Op.getOperand(2);
12799 bool Inverted = false;
12801 if (Cond.getOpcode() == ISD::SETCC) {
12802 // Check for setcc([su]{add,sub,mul}o == 0).
12803 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12804 isa<ConstantSDNode>(Cond.getOperand(1)) &&
12805 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12806 Cond.getOperand(0).getResNo() == 1 &&
12807 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12808 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12809 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12810 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12811 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12812 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12814 Cond = Cond.getOperand(0);
12816 SDValue NewCond = LowerSETCC(Cond, DAG);
12817 if (NewCond.getNode())
12822 // FIXME: LowerXALUO doesn't handle these!!
12823 else if (Cond.getOpcode() == X86ISD::ADD ||
12824 Cond.getOpcode() == X86ISD::SUB ||
12825 Cond.getOpcode() == X86ISD::SMUL ||
12826 Cond.getOpcode() == X86ISD::UMUL)
12827 Cond = LowerXALUO(Cond, DAG);
12830 // Look pass (and (setcc_carry (cmp ...)), 1).
12831 if (Cond.getOpcode() == ISD::AND &&
12832 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12833 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12834 if (C && C->getAPIntValue() == 1)
12835 Cond = Cond.getOperand(0);
12838 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12839 // setting operand in place of the X86ISD::SETCC.
12840 unsigned CondOpcode = Cond.getOpcode();
12841 if (CondOpcode == X86ISD::SETCC ||
12842 CondOpcode == X86ISD::SETCC_CARRY) {
12843 CC = Cond.getOperand(0);
12845 SDValue Cmp = Cond.getOperand(1);
12846 unsigned Opc = Cmp.getOpcode();
12847 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12848 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12852 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12856 // These can only come from an arithmetic instruction with overflow,
12857 // e.g. SADDO, UADDO.
12858 Cond = Cond.getNode()->getOperand(1);
12864 CondOpcode = Cond.getOpcode();
12865 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12866 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12867 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12868 Cond.getOperand(0).getValueType() != MVT::i8)) {
12869 SDValue LHS = Cond.getOperand(0);
12870 SDValue RHS = Cond.getOperand(1);
12871 unsigned X86Opcode;
12874 // Keep this in sync with LowerXALUO, otherwise we might create redundant
12875 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12877 switch (CondOpcode) {
12878 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12880 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12882 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12885 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12886 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12888 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12890 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12893 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12894 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12895 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12896 default: llvm_unreachable("unexpected overflowing operator");
12899 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12900 if (CondOpcode == ISD::UMULO)
12901 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12904 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12906 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12908 if (CondOpcode == ISD::UMULO)
12909 Cond = X86Op.getValue(2);
12911 Cond = X86Op.getValue(1);
12913 CC = DAG.getConstant(X86Cond, MVT::i8);
12917 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12918 SDValue Cmp = Cond.getOperand(0).getOperand(1);
12919 if (CondOpc == ISD::OR) {
12920 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12921 // two branches instead of an explicit OR instruction with a
12923 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12924 isX86LogicalCmp(Cmp)) {
12925 CC = Cond.getOperand(0).getOperand(0);
12926 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12927 Chain, Dest, CC, Cmp);
12928 CC = Cond.getOperand(1).getOperand(0);
12932 } else { // ISD::AND
12933 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12934 // two branches instead of an explicit AND instruction with a
12935 // separate test. However, we only do this if this block doesn't
12936 // have a fall-through edge, because this requires an explicit
12937 // jmp when the condition is false.
12938 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12939 isX86LogicalCmp(Cmp) &&
12940 Op.getNode()->hasOneUse()) {
12941 X86::CondCode CCode =
12942 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12943 CCode = X86::GetOppositeBranchCondition(CCode);
12944 CC = DAG.getConstant(CCode, MVT::i8);
12945 SDNode *User = *Op.getNode()->use_begin();
12946 // Look for an unconditional branch following this conditional branch.
12947 // We need this because we need to reverse the successors in order
12948 // to implement FCMP_OEQ.
12949 if (User->getOpcode() == ISD::BR) {
12950 SDValue FalseBB = User->getOperand(1);
12952 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12953 assert(NewBR == User);
12957 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12958 Chain, Dest, CC, Cmp);
12959 X86::CondCode CCode =
12960 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
12961 CCode = X86::GetOppositeBranchCondition(CCode);
12962 CC = DAG.getConstant(CCode, MVT::i8);
12968 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
12969 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
12970 // It should be transformed during dag combiner except when the condition
12971 // is set by a arithmetics with overflow node.
12972 X86::CondCode CCode =
12973 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12974 CCode = X86::GetOppositeBranchCondition(CCode);
12975 CC = DAG.getConstant(CCode, MVT::i8);
12976 Cond = Cond.getOperand(0).getOperand(1);
12978 } else if (Cond.getOpcode() == ISD::SETCC &&
12979 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
12980 // For FCMP_OEQ, we can emit
12981 // two branches instead of an explicit AND instruction with a
12982 // separate test. However, we only do this if this block doesn't
12983 // have a fall-through edge, because this requires an explicit
12984 // jmp when the condition is false.
12985 if (Op.getNode()->hasOneUse()) {
12986 SDNode *User = *Op.getNode()->use_begin();
12987 // Look for an unconditional branch following this conditional branch.
12988 // We need this because we need to reverse the successors in order
12989 // to implement FCMP_OEQ.
12990 if (User->getOpcode() == ISD::BR) {
12991 SDValue FalseBB = User->getOperand(1);
12993 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12994 assert(NewBR == User);
12998 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12999 Cond.getOperand(0), Cond.getOperand(1));
13000 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13001 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13002 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13003 Chain, Dest, CC, Cmp);
13004 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13009 } else if (Cond.getOpcode() == ISD::SETCC &&
13010 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13011 // For FCMP_UNE, we can emit
13012 // two branches instead of an explicit AND instruction with a
13013 // separate test. However, we only do this if this block doesn't
13014 // have a fall-through edge, because this requires an explicit
13015 // jmp when the condition is false.
13016 if (Op.getNode()->hasOneUse()) {
13017 SDNode *User = *Op.getNode()->use_begin();
13018 // Look for an unconditional branch following this conditional branch.
13019 // We need this because we need to reverse the successors in order
13020 // to implement FCMP_UNE.
13021 if (User->getOpcode() == ISD::BR) {
13022 SDValue FalseBB = User->getOperand(1);
13024 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13025 assert(NewBR == User);
13028 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13029 Cond.getOperand(0), Cond.getOperand(1));
13030 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13031 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13032 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13033 Chain, Dest, CC, Cmp);
13034 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13044 // Look pass the truncate if the high bits are known zero.
13045 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13046 Cond = Cond.getOperand(0);
13048 // We know the result of AND is compared against zero. Try to match
13050 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13051 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13052 if (NewSetCC.getNode()) {
13053 CC = NewSetCC.getOperand(0);
13054 Cond = NewSetCC.getOperand(1);
13061 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13062 CC = DAG.getConstant(X86Cond, MVT::i8);
13063 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13065 Cond = ConvertCmpIfNecessary(Cond, DAG);
13066 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13067 Chain, Dest, CC, Cond);
13070 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13071 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13072 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13073 // that the guard pages used by the OS virtual memory manager are allocated in
13074 // correct sequence.
13076 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13077 SelectionDAG &DAG) const {
13078 MachineFunction &MF = DAG.getMachineFunction();
13079 bool SplitStack = MF.shouldSplitStack();
13080 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13085 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13086 SDNode* Node = Op.getNode();
13088 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13089 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13090 " not tell us which reg is the stack pointer!");
13091 EVT VT = Node->getValueType(0);
13092 SDValue Tmp1 = SDValue(Node, 0);
13093 SDValue Tmp2 = SDValue(Node, 1);
13094 SDValue Tmp3 = Node->getOperand(2);
13095 SDValue Chain = Tmp1.getOperand(0);
13097 // Chain the dynamic stack allocation so that it doesn't modify the stack
13098 // pointer when other instructions are using the stack.
13099 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13102 SDValue Size = Tmp2.getOperand(1);
13103 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13104 Chain = SP.getValue(1);
13105 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13106 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13107 unsigned StackAlign = TFI.getStackAlignment();
13108 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13109 if (Align > StackAlign)
13110 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13111 DAG.getConstant(-(uint64_t)Align, VT));
13112 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13114 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13115 DAG.getIntPtrConstant(0, true), SDValue(),
13118 SDValue Ops[2] = { Tmp1, Tmp2 };
13119 return DAG.getMergeValues(Ops, dl);
13123 SDValue Chain = Op.getOperand(0);
13124 SDValue Size = Op.getOperand(1);
13125 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13126 EVT VT = Op.getNode()->getValueType(0);
13128 bool Is64Bit = Subtarget->is64Bit();
13129 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13132 MachineRegisterInfo &MRI = MF.getRegInfo();
13135 // The 64 bit implementation of segmented stacks needs to clobber both r10
13136 // r11. This makes it impossible to use it along with nested parameters.
13137 const Function *F = MF.getFunction();
13139 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13141 if (I->hasNestAttr())
13142 report_fatal_error("Cannot use segmented stacks with functions that "
13143 "have nested arguments.");
13146 const TargetRegisterClass *AddrRegClass =
13147 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13148 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13149 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13150 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13151 DAG.getRegister(Vreg, SPTy));
13152 SDValue Ops1[2] = { Value, Chain };
13153 return DAG.getMergeValues(Ops1, dl);
13156 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13158 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13159 Flag = Chain.getValue(1);
13160 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13162 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13164 const X86RegisterInfo *RegInfo =
13165 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13166 unsigned SPReg = RegInfo->getStackRegister();
13167 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13168 Chain = SP.getValue(1);
13171 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13172 DAG.getConstant(-(uint64_t)Align, VT));
13173 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13176 SDValue Ops1[2] = { SP, Chain };
13177 return DAG.getMergeValues(Ops1, dl);
13181 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13182 MachineFunction &MF = DAG.getMachineFunction();
13183 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13185 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13188 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13189 // vastart just stores the address of the VarArgsFrameIndex slot into the
13190 // memory location argument.
13191 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13193 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13194 MachinePointerInfo(SV), false, false, 0);
13198 // gp_offset (0 - 6 * 8)
13199 // fp_offset (48 - 48 + 8 * 16)
13200 // overflow_arg_area (point to parameters coming in memory).
13202 SmallVector<SDValue, 8> MemOps;
13203 SDValue FIN = Op.getOperand(1);
13205 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13206 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13208 FIN, MachinePointerInfo(SV), false, false, 0);
13209 MemOps.push_back(Store);
13212 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13213 FIN, DAG.getIntPtrConstant(4));
13214 Store = DAG.getStore(Op.getOperand(0), DL,
13215 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13217 FIN, MachinePointerInfo(SV, 4), false, false, 0);
13218 MemOps.push_back(Store);
13220 // Store ptr to overflow_arg_area
13221 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13222 FIN, DAG.getIntPtrConstant(4));
13223 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13225 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13226 MachinePointerInfo(SV, 8),
13228 MemOps.push_back(Store);
13230 // Store ptr to reg_save_area.
13231 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13232 FIN, DAG.getIntPtrConstant(8));
13233 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13235 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13236 MachinePointerInfo(SV, 16), false, false, 0);
13237 MemOps.push_back(Store);
13238 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13241 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13242 assert(Subtarget->is64Bit() &&
13243 "LowerVAARG only handles 64-bit va_arg!");
13244 assert((Subtarget->isTargetLinux() ||
13245 Subtarget->isTargetDarwin()) &&
13246 "Unhandled target in LowerVAARG");
13247 assert(Op.getNode()->getNumOperands() == 4);
13248 SDValue Chain = Op.getOperand(0);
13249 SDValue SrcPtr = Op.getOperand(1);
13250 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13251 unsigned Align = Op.getConstantOperandVal(3);
13254 EVT ArgVT = Op.getNode()->getValueType(0);
13255 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13256 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13259 // Decide which area this value should be read from.
13260 // TODO: Implement the AMD64 ABI in its entirety. This simple
13261 // selection mechanism works only for the basic types.
13262 if (ArgVT == MVT::f80) {
13263 llvm_unreachable("va_arg for f80 not yet implemented");
13264 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13265 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
13266 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13267 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
13269 llvm_unreachable("Unhandled argument type in LowerVAARG");
13272 if (ArgMode == 2) {
13273 // Sanity Check: Make sure using fp_offset makes sense.
13274 assert(!DAG.getTarget().Options.UseSoftFloat &&
13275 !(DAG.getMachineFunction()
13276 .getFunction()->getAttributes()
13277 .hasAttribute(AttributeSet::FunctionIndex,
13278 Attribute::NoImplicitFloat)) &&
13279 Subtarget->hasSSE1());
13282 // Insert VAARG_64 node into the DAG
13283 // VAARG_64 returns two values: Variable Argument Address, Chain
13284 SmallVector<SDValue, 11> InstOps;
13285 InstOps.push_back(Chain);
13286 InstOps.push_back(SrcPtr);
13287 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13288 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13289 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13290 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13291 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13292 VTs, InstOps, MVT::i64,
13293 MachinePointerInfo(SV),
13295 /*Volatile=*/false,
13297 /*WriteMem=*/true);
13298 Chain = VAARG.getValue(1);
13300 // Load the next argument and return it
13301 return DAG.getLoad(ArgVT, dl,
13304 MachinePointerInfo(),
13305 false, false, false, 0);
13308 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13309 SelectionDAG &DAG) {
13310 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13311 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13312 SDValue Chain = Op.getOperand(0);
13313 SDValue DstPtr = Op.getOperand(1);
13314 SDValue SrcPtr = Op.getOperand(2);
13315 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13316 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13319 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13320 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13322 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13325 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13326 // amount is a constant. Takes immediate version of shift as input.
13327 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13328 SDValue SrcOp, uint64_t ShiftAmt,
13329 SelectionDAG &DAG) {
13330 MVT ElementType = VT.getVectorElementType();
13332 // Fold this packed shift into its first operand if ShiftAmt is 0.
13336 // Check for ShiftAmt >= element width
13337 if (ShiftAmt >= ElementType.getSizeInBits()) {
13338 if (Opc == X86ISD::VSRAI)
13339 ShiftAmt = ElementType.getSizeInBits() - 1;
13341 return DAG.getConstant(0, VT);
13344 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13345 && "Unknown target vector shift-by-constant node");
13347 // Fold this packed vector shift into a build vector if SrcOp is a
13348 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13349 if (VT == SrcOp.getSimpleValueType() &&
13350 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13351 SmallVector<SDValue, 8> Elts;
13352 unsigned NumElts = SrcOp->getNumOperands();
13353 ConstantSDNode *ND;
13356 default: llvm_unreachable(nullptr);
13357 case X86ISD::VSHLI:
13358 for (unsigned i=0; i!=NumElts; ++i) {
13359 SDValue CurrentOp = SrcOp->getOperand(i);
13360 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13361 Elts.push_back(CurrentOp);
13364 ND = cast<ConstantSDNode>(CurrentOp);
13365 const APInt &C = ND->getAPIntValue();
13366 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13369 case X86ISD::VSRLI:
13370 for (unsigned i=0; i!=NumElts; ++i) {
13371 SDValue CurrentOp = SrcOp->getOperand(i);
13372 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13373 Elts.push_back(CurrentOp);
13376 ND = cast<ConstantSDNode>(CurrentOp);
13377 const APInt &C = ND->getAPIntValue();
13378 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13381 case X86ISD::VSRAI:
13382 for (unsigned i=0; i!=NumElts; ++i) {
13383 SDValue CurrentOp = SrcOp->getOperand(i);
13384 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13385 Elts.push_back(CurrentOp);
13388 ND = cast<ConstantSDNode>(CurrentOp);
13389 const APInt &C = ND->getAPIntValue();
13390 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13395 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13398 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13401 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13402 // may or may not be a constant. Takes immediate version of shift as input.
13403 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13404 SDValue SrcOp, SDValue ShAmt,
13405 SelectionDAG &DAG) {
13406 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13408 // Catch shift-by-constant.
13409 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13410 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13411 CShAmt->getZExtValue(), DAG);
13413 // Change opcode to non-immediate version
13415 default: llvm_unreachable("Unknown target vector shift node");
13416 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13417 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13418 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13421 // Need to build a vector containing shift amount
13422 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13425 ShOps[1] = DAG.getConstant(0, MVT::i32);
13426 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13427 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13429 // The return type has to be a 128-bit type with the same element
13430 // type as the input type.
13431 MVT EltVT = VT.getVectorElementType();
13432 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13434 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13435 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13438 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13440 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13442 default: return SDValue(); // Don't custom lower most intrinsics.
13443 // Comparison intrinsics.
13444 case Intrinsic::x86_sse_comieq_ss:
13445 case Intrinsic::x86_sse_comilt_ss:
13446 case Intrinsic::x86_sse_comile_ss:
13447 case Intrinsic::x86_sse_comigt_ss:
13448 case Intrinsic::x86_sse_comige_ss:
13449 case Intrinsic::x86_sse_comineq_ss:
13450 case Intrinsic::x86_sse_ucomieq_ss:
13451 case Intrinsic::x86_sse_ucomilt_ss:
13452 case Intrinsic::x86_sse_ucomile_ss:
13453 case Intrinsic::x86_sse_ucomigt_ss:
13454 case Intrinsic::x86_sse_ucomige_ss:
13455 case Intrinsic::x86_sse_ucomineq_ss:
13456 case Intrinsic::x86_sse2_comieq_sd:
13457 case Intrinsic::x86_sse2_comilt_sd:
13458 case Intrinsic::x86_sse2_comile_sd:
13459 case Intrinsic::x86_sse2_comigt_sd:
13460 case Intrinsic::x86_sse2_comige_sd:
13461 case Intrinsic::x86_sse2_comineq_sd:
13462 case Intrinsic::x86_sse2_ucomieq_sd:
13463 case Intrinsic::x86_sse2_ucomilt_sd:
13464 case Intrinsic::x86_sse2_ucomile_sd:
13465 case Intrinsic::x86_sse2_ucomigt_sd:
13466 case Intrinsic::x86_sse2_ucomige_sd:
13467 case Intrinsic::x86_sse2_ucomineq_sd: {
13471 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13472 case Intrinsic::x86_sse_comieq_ss:
13473 case Intrinsic::x86_sse2_comieq_sd:
13474 Opc = X86ISD::COMI;
13477 case Intrinsic::x86_sse_comilt_ss:
13478 case Intrinsic::x86_sse2_comilt_sd:
13479 Opc = X86ISD::COMI;
13482 case Intrinsic::x86_sse_comile_ss:
13483 case Intrinsic::x86_sse2_comile_sd:
13484 Opc = X86ISD::COMI;
13487 case Intrinsic::x86_sse_comigt_ss:
13488 case Intrinsic::x86_sse2_comigt_sd:
13489 Opc = X86ISD::COMI;
13492 case Intrinsic::x86_sse_comige_ss:
13493 case Intrinsic::x86_sse2_comige_sd:
13494 Opc = X86ISD::COMI;
13497 case Intrinsic::x86_sse_comineq_ss:
13498 case Intrinsic::x86_sse2_comineq_sd:
13499 Opc = X86ISD::COMI;
13502 case Intrinsic::x86_sse_ucomieq_ss:
13503 case Intrinsic::x86_sse2_ucomieq_sd:
13504 Opc = X86ISD::UCOMI;
13507 case Intrinsic::x86_sse_ucomilt_ss:
13508 case Intrinsic::x86_sse2_ucomilt_sd:
13509 Opc = X86ISD::UCOMI;
13512 case Intrinsic::x86_sse_ucomile_ss:
13513 case Intrinsic::x86_sse2_ucomile_sd:
13514 Opc = X86ISD::UCOMI;
13517 case Intrinsic::x86_sse_ucomigt_ss:
13518 case Intrinsic::x86_sse2_ucomigt_sd:
13519 Opc = X86ISD::UCOMI;
13522 case Intrinsic::x86_sse_ucomige_ss:
13523 case Intrinsic::x86_sse2_ucomige_sd:
13524 Opc = X86ISD::UCOMI;
13527 case Intrinsic::x86_sse_ucomineq_ss:
13528 case Intrinsic::x86_sse2_ucomineq_sd:
13529 Opc = X86ISD::UCOMI;
13534 SDValue LHS = Op.getOperand(1);
13535 SDValue RHS = Op.getOperand(2);
13536 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13537 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13538 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13539 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13540 DAG.getConstant(X86CC, MVT::i8), Cond);
13541 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13544 // Arithmetic intrinsics.
13545 case Intrinsic::x86_sse2_pmulu_dq:
13546 case Intrinsic::x86_avx2_pmulu_dq:
13547 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13548 Op.getOperand(1), Op.getOperand(2));
13550 case Intrinsic::x86_sse41_pmuldq:
13551 case Intrinsic::x86_avx2_pmul_dq:
13552 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13553 Op.getOperand(1), Op.getOperand(2));
13555 case Intrinsic::x86_sse2_pmulhu_w:
13556 case Intrinsic::x86_avx2_pmulhu_w:
13557 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13558 Op.getOperand(1), Op.getOperand(2));
13560 case Intrinsic::x86_sse2_pmulh_w:
13561 case Intrinsic::x86_avx2_pmulh_w:
13562 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13563 Op.getOperand(1), Op.getOperand(2));
13565 // SSE2/AVX2 sub with unsigned saturation intrinsics
13566 case Intrinsic::x86_sse2_psubus_b:
13567 case Intrinsic::x86_sse2_psubus_w:
13568 case Intrinsic::x86_avx2_psubus_b:
13569 case Intrinsic::x86_avx2_psubus_w:
13570 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13571 Op.getOperand(1), Op.getOperand(2));
13573 // SSE3/AVX horizontal add/sub intrinsics
13574 case Intrinsic::x86_sse3_hadd_ps:
13575 case Intrinsic::x86_sse3_hadd_pd:
13576 case Intrinsic::x86_avx_hadd_ps_256:
13577 case Intrinsic::x86_avx_hadd_pd_256:
13578 case Intrinsic::x86_sse3_hsub_ps:
13579 case Intrinsic::x86_sse3_hsub_pd:
13580 case Intrinsic::x86_avx_hsub_ps_256:
13581 case Intrinsic::x86_avx_hsub_pd_256:
13582 case Intrinsic::x86_ssse3_phadd_w_128:
13583 case Intrinsic::x86_ssse3_phadd_d_128:
13584 case Intrinsic::x86_avx2_phadd_w:
13585 case Intrinsic::x86_avx2_phadd_d:
13586 case Intrinsic::x86_ssse3_phsub_w_128:
13587 case Intrinsic::x86_ssse3_phsub_d_128:
13588 case Intrinsic::x86_avx2_phsub_w:
13589 case Intrinsic::x86_avx2_phsub_d: {
13592 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13593 case Intrinsic::x86_sse3_hadd_ps:
13594 case Intrinsic::x86_sse3_hadd_pd:
13595 case Intrinsic::x86_avx_hadd_ps_256:
13596 case Intrinsic::x86_avx_hadd_pd_256:
13597 Opcode = X86ISD::FHADD;
13599 case Intrinsic::x86_sse3_hsub_ps:
13600 case Intrinsic::x86_sse3_hsub_pd:
13601 case Intrinsic::x86_avx_hsub_ps_256:
13602 case Intrinsic::x86_avx_hsub_pd_256:
13603 Opcode = X86ISD::FHSUB;
13605 case Intrinsic::x86_ssse3_phadd_w_128:
13606 case Intrinsic::x86_ssse3_phadd_d_128:
13607 case Intrinsic::x86_avx2_phadd_w:
13608 case Intrinsic::x86_avx2_phadd_d:
13609 Opcode = X86ISD::HADD;
13611 case Intrinsic::x86_ssse3_phsub_w_128:
13612 case Intrinsic::x86_ssse3_phsub_d_128:
13613 case Intrinsic::x86_avx2_phsub_w:
13614 case Intrinsic::x86_avx2_phsub_d:
13615 Opcode = X86ISD::HSUB;
13618 return DAG.getNode(Opcode, dl, Op.getValueType(),
13619 Op.getOperand(1), Op.getOperand(2));
13622 // SSE2/SSE41/AVX2 integer max/min intrinsics.
13623 case Intrinsic::x86_sse2_pmaxu_b:
13624 case Intrinsic::x86_sse41_pmaxuw:
13625 case Intrinsic::x86_sse41_pmaxud:
13626 case Intrinsic::x86_avx2_pmaxu_b:
13627 case Intrinsic::x86_avx2_pmaxu_w:
13628 case Intrinsic::x86_avx2_pmaxu_d:
13629 case Intrinsic::x86_sse2_pminu_b:
13630 case Intrinsic::x86_sse41_pminuw:
13631 case Intrinsic::x86_sse41_pminud:
13632 case Intrinsic::x86_avx2_pminu_b:
13633 case Intrinsic::x86_avx2_pminu_w:
13634 case Intrinsic::x86_avx2_pminu_d:
13635 case Intrinsic::x86_sse41_pmaxsb:
13636 case Intrinsic::x86_sse2_pmaxs_w:
13637 case Intrinsic::x86_sse41_pmaxsd:
13638 case Intrinsic::x86_avx2_pmaxs_b:
13639 case Intrinsic::x86_avx2_pmaxs_w:
13640 case Intrinsic::x86_avx2_pmaxs_d:
13641 case Intrinsic::x86_sse41_pminsb:
13642 case Intrinsic::x86_sse2_pmins_w:
13643 case Intrinsic::x86_sse41_pminsd:
13644 case Intrinsic::x86_avx2_pmins_b:
13645 case Intrinsic::x86_avx2_pmins_w:
13646 case Intrinsic::x86_avx2_pmins_d: {
13649 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13650 case Intrinsic::x86_sse2_pmaxu_b:
13651 case Intrinsic::x86_sse41_pmaxuw:
13652 case Intrinsic::x86_sse41_pmaxud:
13653 case Intrinsic::x86_avx2_pmaxu_b:
13654 case Intrinsic::x86_avx2_pmaxu_w:
13655 case Intrinsic::x86_avx2_pmaxu_d:
13656 Opcode = X86ISD::UMAX;
13658 case Intrinsic::x86_sse2_pminu_b:
13659 case Intrinsic::x86_sse41_pminuw:
13660 case Intrinsic::x86_sse41_pminud:
13661 case Intrinsic::x86_avx2_pminu_b:
13662 case Intrinsic::x86_avx2_pminu_w:
13663 case Intrinsic::x86_avx2_pminu_d:
13664 Opcode = X86ISD::UMIN;
13666 case Intrinsic::x86_sse41_pmaxsb:
13667 case Intrinsic::x86_sse2_pmaxs_w:
13668 case Intrinsic::x86_sse41_pmaxsd:
13669 case Intrinsic::x86_avx2_pmaxs_b:
13670 case Intrinsic::x86_avx2_pmaxs_w:
13671 case Intrinsic::x86_avx2_pmaxs_d:
13672 Opcode = X86ISD::SMAX;
13674 case Intrinsic::x86_sse41_pminsb:
13675 case Intrinsic::x86_sse2_pmins_w:
13676 case Intrinsic::x86_sse41_pminsd:
13677 case Intrinsic::x86_avx2_pmins_b:
13678 case Intrinsic::x86_avx2_pmins_w:
13679 case Intrinsic::x86_avx2_pmins_d:
13680 Opcode = X86ISD::SMIN;
13683 return DAG.getNode(Opcode, dl, Op.getValueType(),
13684 Op.getOperand(1), Op.getOperand(2));
13687 // SSE/SSE2/AVX floating point max/min intrinsics.
13688 case Intrinsic::x86_sse_max_ps:
13689 case Intrinsic::x86_sse2_max_pd:
13690 case Intrinsic::x86_avx_max_ps_256:
13691 case Intrinsic::x86_avx_max_pd_256:
13692 case Intrinsic::x86_sse_min_ps:
13693 case Intrinsic::x86_sse2_min_pd:
13694 case Intrinsic::x86_avx_min_ps_256:
13695 case Intrinsic::x86_avx_min_pd_256: {
13698 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13699 case Intrinsic::x86_sse_max_ps:
13700 case Intrinsic::x86_sse2_max_pd:
13701 case Intrinsic::x86_avx_max_ps_256:
13702 case Intrinsic::x86_avx_max_pd_256:
13703 Opcode = X86ISD::FMAX;
13705 case Intrinsic::x86_sse_min_ps:
13706 case Intrinsic::x86_sse2_min_pd:
13707 case Intrinsic::x86_avx_min_ps_256:
13708 case Intrinsic::x86_avx_min_pd_256:
13709 Opcode = X86ISD::FMIN;
13712 return DAG.getNode(Opcode, dl, Op.getValueType(),
13713 Op.getOperand(1), Op.getOperand(2));
13716 // AVX2 variable shift intrinsics
13717 case Intrinsic::x86_avx2_psllv_d:
13718 case Intrinsic::x86_avx2_psllv_q:
13719 case Intrinsic::x86_avx2_psllv_d_256:
13720 case Intrinsic::x86_avx2_psllv_q_256:
13721 case Intrinsic::x86_avx2_psrlv_d:
13722 case Intrinsic::x86_avx2_psrlv_q:
13723 case Intrinsic::x86_avx2_psrlv_d_256:
13724 case Intrinsic::x86_avx2_psrlv_q_256:
13725 case Intrinsic::x86_avx2_psrav_d:
13726 case Intrinsic::x86_avx2_psrav_d_256: {
13729 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13730 case Intrinsic::x86_avx2_psllv_d:
13731 case Intrinsic::x86_avx2_psllv_q:
13732 case Intrinsic::x86_avx2_psllv_d_256:
13733 case Intrinsic::x86_avx2_psllv_q_256:
13736 case Intrinsic::x86_avx2_psrlv_d:
13737 case Intrinsic::x86_avx2_psrlv_q:
13738 case Intrinsic::x86_avx2_psrlv_d_256:
13739 case Intrinsic::x86_avx2_psrlv_q_256:
13742 case Intrinsic::x86_avx2_psrav_d:
13743 case Intrinsic::x86_avx2_psrav_d_256:
13747 return DAG.getNode(Opcode, dl, Op.getValueType(),
13748 Op.getOperand(1), Op.getOperand(2));
13751 case Intrinsic::x86_sse2_packssdw_128:
13752 case Intrinsic::x86_sse2_packsswb_128:
13753 case Intrinsic::x86_avx2_packssdw:
13754 case Intrinsic::x86_avx2_packsswb:
13755 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13756 Op.getOperand(1), Op.getOperand(2));
13758 case Intrinsic::x86_sse2_packuswb_128:
13759 case Intrinsic::x86_sse41_packusdw:
13760 case Intrinsic::x86_avx2_packuswb:
13761 case Intrinsic::x86_avx2_packusdw:
13762 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13763 Op.getOperand(1), Op.getOperand(2));
13765 case Intrinsic::x86_ssse3_pshuf_b_128:
13766 case Intrinsic::x86_avx2_pshuf_b:
13767 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13768 Op.getOperand(1), Op.getOperand(2));
13770 case Intrinsic::x86_sse2_pshuf_d:
13771 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13772 Op.getOperand(1), Op.getOperand(2));
13774 case Intrinsic::x86_sse2_pshufl_w:
13775 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13776 Op.getOperand(1), Op.getOperand(2));
13778 case Intrinsic::x86_sse2_pshufh_w:
13779 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13780 Op.getOperand(1), Op.getOperand(2));
13782 case Intrinsic::x86_ssse3_psign_b_128:
13783 case Intrinsic::x86_ssse3_psign_w_128:
13784 case Intrinsic::x86_ssse3_psign_d_128:
13785 case Intrinsic::x86_avx2_psign_b:
13786 case Intrinsic::x86_avx2_psign_w:
13787 case Intrinsic::x86_avx2_psign_d:
13788 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13789 Op.getOperand(1), Op.getOperand(2));
13791 case Intrinsic::x86_sse41_insertps:
13792 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13793 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13795 case Intrinsic::x86_avx_vperm2f128_ps_256:
13796 case Intrinsic::x86_avx_vperm2f128_pd_256:
13797 case Intrinsic::x86_avx_vperm2f128_si_256:
13798 case Intrinsic::x86_avx2_vperm2i128:
13799 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13800 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13802 case Intrinsic::x86_avx2_permd:
13803 case Intrinsic::x86_avx2_permps:
13804 // Operands intentionally swapped. Mask is last operand to intrinsic,
13805 // but second operand for node/instruction.
13806 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13807 Op.getOperand(2), Op.getOperand(1));
13809 case Intrinsic::x86_sse_sqrt_ps:
13810 case Intrinsic::x86_sse2_sqrt_pd:
13811 case Intrinsic::x86_avx_sqrt_ps_256:
13812 case Intrinsic::x86_avx_sqrt_pd_256:
13813 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13815 // ptest and testp intrinsics. The intrinsic these come from are designed to
13816 // return an integer value, not just an instruction so lower it to the ptest
13817 // or testp pattern and a setcc for the result.
13818 case Intrinsic::x86_sse41_ptestz:
13819 case Intrinsic::x86_sse41_ptestc:
13820 case Intrinsic::x86_sse41_ptestnzc:
13821 case Intrinsic::x86_avx_ptestz_256:
13822 case Intrinsic::x86_avx_ptestc_256:
13823 case Intrinsic::x86_avx_ptestnzc_256:
13824 case Intrinsic::x86_avx_vtestz_ps:
13825 case Intrinsic::x86_avx_vtestc_ps:
13826 case Intrinsic::x86_avx_vtestnzc_ps:
13827 case Intrinsic::x86_avx_vtestz_pd:
13828 case Intrinsic::x86_avx_vtestc_pd:
13829 case Intrinsic::x86_avx_vtestnzc_pd:
13830 case Intrinsic::x86_avx_vtestz_ps_256:
13831 case Intrinsic::x86_avx_vtestc_ps_256:
13832 case Intrinsic::x86_avx_vtestnzc_ps_256:
13833 case Intrinsic::x86_avx_vtestz_pd_256:
13834 case Intrinsic::x86_avx_vtestc_pd_256:
13835 case Intrinsic::x86_avx_vtestnzc_pd_256: {
13836 bool IsTestPacked = false;
13839 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13840 case Intrinsic::x86_avx_vtestz_ps:
13841 case Intrinsic::x86_avx_vtestz_pd:
13842 case Intrinsic::x86_avx_vtestz_ps_256:
13843 case Intrinsic::x86_avx_vtestz_pd_256:
13844 IsTestPacked = true; // Fallthrough
13845 case Intrinsic::x86_sse41_ptestz:
13846 case Intrinsic::x86_avx_ptestz_256:
13848 X86CC = X86::COND_E;
13850 case Intrinsic::x86_avx_vtestc_ps:
13851 case Intrinsic::x86_avx_vtestc_pd:
13852 case Intrinsic::x86_avx_vtestc_ps_256:
13853 case Intrinsic::x86_avx_vtestc_pd_256:
13854 IsTestPacked = true; // Fallthrough
13855 case Intrinsic::x86_sse41_ptestc:
13856 case Intrinsic::x86_avx_ptestc_256:
13858 X86CC = X86::COND_B;
13860 case Intrinsic::x86_avx_vtestnzc_ps:
13861 case Intrinsic::x86_avx_vtestnzc_pd:
13862 case Intrinsic::x86_avx_vtestnzc_ps_256:
13863 case Intrinsic::x86_avx_vtestnzc_pd_256:
13864 IsTestPacked = true; // Fallthrough
13865 case Intrinsic::x86_sse41_ptestnzc:
13866 case Intrinsic::x86_avx_ptestnzc_256:
13868 X86CC = X86::COND_A;
13872 SDValue LHS = Op.getOperand(1);
13873 SDValue RHS = Op.getOperand(2);
13874 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13875 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13876 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13877 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13878 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13880 case Intrinsic::x86_avx512_kortestz_w:
13881 case Intrinsic::x86_avx512_kortestc_w: {
13882 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13883 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13884 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13885 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13886 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13887 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13888 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13891 // SSE/AVX shift intrinsics
13892 case Intrinsic::x86_sse2_psll_w:
13893 case Intrinsic::x86_sse2_psll_d:
13894 case Intrinsic::x86_sse2_psll_q:
13895 case Intrinsic::x86_avx2_psll_w:
13896 case Intrinsic::x86_avx2_psll_d:
13897 case Intrinsic::x86_avx2_psll_q:
13898 case Intrinsic::x86_sse2_psrl_w:
13899 case Intrinsic::x86_sse2_psrl_d:
13900 case Intrinsic::x86_sse2_psrl_q:
13901 case Intrinsic::x86_avx2_psrl_w:
13902 case Intrinsic::x86_avx2_psrl_d:
13903 case Intrinsic::x86_avx2_psrl_q:
13904 case Intrinsic::x86_sse2_psra_w:
13905 case Intrinsic::x86_sse2_psra_d:
13906 case Intrinsic::x86_avx2_psra_w:
13907 case Intrinsic::x86_avx2_psra_d: {
13910 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13911 case Intrinsic::x86_sse2_psll_w:
13912 case Intrinsic::x86_sse2_psll_d:
13913 case Intrinsic::x86_sse2_psll_q:
13914 case Intrinsic::x86_avx2_psll_w:
13915 case Intrinsic::x86_avx2_psll_d:
13916 case Intrinsic::x86_avx2_psll_q:
13917 Opcode = X86ISD::VSHL;
13919 case Intrinsic::x86_sse2_psrl_w:
13920 case Intrinsic::x86_sse2_psrl_d:
13921 case Intrinsic::x86_sse2_psrl_q:
13922 case Intrinsic::x86_avx2_psrl_w:
13923 case Intrinsic::x86_avx2_psrl_d:
13924 case Intrinsic::x86_avx2_psrl_q:
13925 Opcode = X86ISD::VSRL;
13927 case Intrinsic::x86_sse2_psra_w:
13928 case Intrinsic::x86_sse2_psra_d:
13929 case Intrinsic::x86_avx2_psra_w:
13930 case Intrinsic::x86_avx2_psra_d:
13931 Opcode = X86ISD::VSRA;
13934 return DAG.getNode(Opcode, dl, Op.getValueType(),
13935 Op.getOperand(1), Op.getOperand(2));
13938 // SSE/AVX immediate shift intrinsics
13939 case Intrinsic::x86_sse2_pslli_w:
13940 case Intrinsic::x86_sse2_pslli_d:
13941 case Intrinsic::x86_sse2_pslli_q:
13942 case Intrinsic::x86_avx2_pslli_w:
13943 case Intrinsic::x86_avx2_pslli_d:
13944 case Intrinsic::x86_avx2_pslli_q:
13945 case Intrinsic::x86_sse2_psrli_w:
13946 case Intrinsic::x86_sse2_psrli_d:
13947 case Intrinsic::x86_sse2_psrli_q:
13948 case Intrinsic::x86_avx2_psrli_w:
13949 case Intrinsic::x86_avx2_psrli_d:
13950 case Intrinsic::x86_avx2_psrli_q:
13951 case Intrinsic::x86_sse2_psrai_w:
13952 case Intrinsic::x86_sse2_psrai_d:
13953 case Intrinsic::x86_avx2_psrai_w:
13954 case Intrinsic::x86_avx2_psrai_d: {
13957 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13958 case Intrinsic::x86_sse2_pslli_w:
13959 case Intrinsic::x86_sse2_pslli_d:
13960 case Intrinsic::x86_sse2_pslli_q:
13961 case Intrinsic::x86_avx2_pslli_w:
13962 case Intrinsic::x86_avx2_pslli_d:
13963 case Intrinsic::x86_avx2_pslli_q:
13964 Opcode = X86ISD::VSHLI;
13966 case Intrinsic::x86_sse2_psrli_w:
13967 case Intrinsic::x86_sse2_psrli_d:
13968 case Intrinsic::x86_sse2_psrli_q:
13969 case Intrinsic::x86_avx2_psrli_w:
13970 case Intrinsic::x86_avx2_psrli_d:
13971 case Intrinsic::x86_avx2_psrli_q:
13972 Opcode = X86ISD::VSRLI;
13974 case Intrinsic::x86_sse2_psrai_w:
13975 case Intrinsic::x86_sse2_psrai_d:
13976 case Intrinsic::x86_avx2_psrai_w:
13977 case Intrinsic::x86_avx2_psrai_d:
13978 Opcode = X86ISD::VSRAI;
13981 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
13982 Op.getOperand(1), Op.getOperand(2), DAG);
13985 case Intrinsic::x86_sse42_pcmpistria128:
13986 case Intrinsic::x86_sse42_pcmpestria128:
13987 case Intrinsic::x86_sse42_pcmpistric128:
13988 case Intrinsic::x86_sse42_pcmpestric128:
13989 case Intrinsic::x86_sse42_pcmpistrio128:
13990 case Intrinsic::x86_sse42_pcmpestrio128:
13991 case Intrinsic::x86_sse42_pcmpistris128:
13992 case Intrinsic::x86_sse42_pcmpestris128:
13993 case Intrinsic::x86_sse42_pcmpistriz128:
13994 case Intrinsic::x86_sse42_pcmpestriz128: {
13998 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13999 case Intrinsic::x86_sse42_pcmpistria128:
14000 Opcode = X86ISD::PCMPISTRI;
14001 X86CC = X86::COND_A;
14003 case Intrinsic::x86_sse42_pcmpestria128:
14004 Opcode = X86ISD::PCMPESTRI;
14005 X86CC = X86::COND_A;
14007 case Intrinsic::x86_sse42_pcmpistric128:
14008 Opcode = X86ISD::PCMPISTRI;
14009 X86CC = X86::COND_B;
14011 case Intrinsic::x86_sse42_pcmpestric128:
14012 Opcode = X86ISD::PCMPESTRI;
14013 X86CC = X86::COND_B;
14015 case Intrinsic::x86_sse42_pcmpistrio128:
14016 Opcode = X86ISD::PCMPISTRI;
14017 X86CC = X86::COND_O;
14019 case Intrinsic::x86_sse42_pcmpestrio128:
14020 Opcode = X86ISD::PCMPESTRI;
14021 X86CC = X86::COND_O;
14023 case Intrinsic::x86_sse42_pcmpistris128:
14024 Opcode = X86ISD::PCMPISTRI;
14025 X86CC = X86::COND_S;
14027 case Intrinsic::x86_sse42_pcmpestris128:
14028 Opcode = X86ISD::PCMPESTRI;
14029 X86CC = X86::COND_S;
14031 case Intrinsic::x86_sse42_pcmpistriz128:
14032 Opcode = X86ISD::PCMPISTRI;
14033 X86CC = X86::COND_E;
14035 case Intrinsic::x86_sse42_pcmpestriz128:
14036 Opcode = X86ISD::PCMPESTRI;
14037 X86CC = X86::COND_E;
14040 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14041 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14042 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14043 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14044 DAG.getConstant(X86CC, MVT::i8),
14045 SDValue(PCMP.getNode(), 1));
14046 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14049 case Intrinsic::x86_sse42_pcmpistri128:
14050 case Intrinsic::x86_sse42_pcmpestri128: {
14052 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14053 Opcode = X86ISD::PCMPISTRI;
14055 Opcode = X86ISD::PCMPESTRI;
14057 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14058 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14059 return DAG.getNode(Opcode, dl, VTs, NewOps);
14061 case Intrinsic::x86_fma_vfmadd_ps:
14062 case Intrinsic::x86_fma_vfmadd_pd:
14063 case Intrinsic::x86_fma_vfmsub_ps:
14064 case Intrinsic::x86_fma_vfmsub_pd:
14065 case Intrinsic::x86_fma_vfnmadd_ps:
14066 case Intrinsic::x86_fma_vfnmadd_pd:
14067 case Intrinsic::x86_fma_vfnmsub_ps:
14068 case Intrinsic::x86_fma_vfnmsub_pd:
14069 case Intrinsic::x86_fma_vfmaddsub_ps:
14070 case Intrinsic::x86_fma_vfmaddsub_pd:
14071 case Intrinsic::x86_fma_vfmsubadd_ps:
14072 case Intrinsic::x86_fma_vfmsubadd_pd:
14073 case Intrinsic::x86_fma_vfmadd_ps_256:
14074 case Intrinsic::x86_fma_vfmadd_pd_256:
14075 case Intrinsic::x86_fma_vfmsub_ps_256:
14076 case Intrinsic::x86_fma_vfmsub_pd_256:
14077 case Intrinsic::x86_fma_vfnmadd_ps_256:
14078 case Intrinsic::x86_fma_vfnmadd_pd_256:
14079 case Intrinsic::x86_fma_vfnmsub_ps_256:
14080 case Intrinsic::x86_fma_vfnmsub_pd_256:
14081 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14082 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14083 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14084 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14085 case Intrinsic::x86_fma_vfmadd_ps_512:
14086 case Intrinsic::x86_fma_vfmadd_pd_512:
14087 case Intrinsic::x86_fma_vfmsub_ps_512:
14088 case Intrinsic::x86_fma_vfmsub_pd_512:
14089 case Intrinsic::x86_fma_vfnmadd_ps_512:
14090 case Intrinsic::x86_fma_vfnmadd_pd_512:
14091 case Intrinsic::x86_fma_vfnmsub_ps_512:
14092 case Intrinsic::x86_fma_vfnmsub_pd_512:
14093 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14094 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14095 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14096 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14099 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14100 case Intrinsic::x86_fma_vfmadd_ps:
14101 case Intrinsic::x86_fma_vfmadd_pd:
14102 case Intrinsic::x86_fma_vfmadd_ps_256:
14103 case Intrinsic::x86_fma_vfmadd_pd_256:
14104 case Intrinsic::x86_fma_vfmadd_ps_512:
14105 case Intrinsic::x86_fma_vfmadd_pd_512:
14106 Opc = X86ISD::FMADD;
14108 case Intrinsic::x86_fma_vfmsub_ps:
14109 case Intrinsic::x86_fma_vfmsub_pd:
14110 case Intrinsic::x86_fma_vfmsub_ps_256:
14111 case Intrinsic::x86_fma_vfmsub_pd_256:
14112 case Intrinsic::x86_fma_vfmsub_ps_512:
14113 case Intrinsic::x86_fma_vfmsub_pd_512:
14114 Opc = X86ISD::FMSUB;
14116 case Intrinsic::x86_fma_vfnmadd_ps:
14117 case Intrinsic::x86_fma_vfnmadd_pd:
14118 case Intrinsic::x86_fma_vfnmadd_ps_256:
14119 case Intrinsic::x86_fma_vfnmadd_pd_256:
14120 case Intrinsic::x86_fma_vfnmadd_ps_512:
14121 case Intrinsic::x86_fma_vfnmadd_pd_512:
14122 Opc = X86ISD::FNMADD;
14124 case Intrinsic::x86_fma_vfnmsub_ps:
14125 case Intrinsic::x86_fma_vfnmsub_pd:
14126 case Intrinsic::x86_fma_vfnmsub_ps_256:
14127 case Intrinsic::x86_fma_vfnmsub_pd_256:
14128 case Intrinsic::x86_fma_vfnmsub_ps_512:
14129 case Intrinsic::x86_fma_vfnmsub_pd_512:
14130 Opc = X86ISD::FNMSUB;
14132 case Intrinsic::x86_fma_vfmaddsub_ps:
14133 case Intrinsic::x86_fma_vfmaddsub_pd:
14134 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14135 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14136 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14137 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14138 Opc = X86ISD::FMADDSUB;
14140 case Intrinsic::x86_fma_vfmsubadd_ps:
14141 case Intrinsic::x86_fma_vfmsubadd_pd:
14142 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14143 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14144 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14145 case Intrinsic::x86_fma_vfmsubadd_pd_512:
14146 Opc = X86ISD::FMSUBADD;
14150 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14151 Op.getOperand(2), Op.getOperand(3));
14156 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14157 SDValue Src, SDValue Mask, SDValue Base,
14158 SDValue Index, SDValue ScaleOp, SDValue Chain,
14159 const X86Subtarget * Subtarget) {
14161 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14162 assert(C && "Invalid scale type");
14163 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14164 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14165 Index.getSimpleValueType().getVectorNumElements());
14167 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14169 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14171 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14172 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14173 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14174 SDValue Segment = DAG.getRegister(0, MVT::i32);
14175 if (Src.getOpcode() == ISD::UNDEF)
14176 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14177 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14178 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14179 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14180 return DAG.getMergeValues(RetOps, dl);
14183 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14184 SDValue Src, SDValue Mask, SDValue Base,
14185 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14187 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14188 assert(C && "Invalid scale type");
14189 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14190 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14191 SDValue Segment = DAG.getRegister(0, MVT::i32);
14192 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14193 Index.getSimpleValueType().getVectorNumElements());
14195 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14197 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14199 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14200 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14201 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14202 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14203 return SDValue(Res, 1);
14206 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14207 SDValue Mask, SDValue Base, SDValue Index,
14208 SDValue ScaleOp, SDValue Chain) {
14210 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14211 assert(C && "Invalid scale type");
14212 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14213 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14214 SDValue Segment = DAG.getRegister(0, MVT::i32);
14216 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14218 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14220 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14222 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14223 //SDVTList VTs = DAG.getVTList(MVT::Other);
14224 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14225 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14226 return SDValue(Res, 0);
14229 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14230 // read performance monitor counters (x86_rdpmc).
14231 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14232 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14233 SmallVectorImpl<SDValue> &Results) {
14234 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14235 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14238 // The ECX register is used to select the index of the performance counter
14240 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14242 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14244 // Reads the content of a 64-bit performance counter and returns it in the
14245 // registers EDX:EAX.
14246 if (Subtarget->is64Bit()) {
14247 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14248 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14251 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14252 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14255 Chain = HI.getValue(1);
14257 if (Subtarget->is64Bit()) {
14258 // The EAX register is loaded with the low-order 32 bits. The EDX register
14259 // is loaded with the supported high-order bits of the counter.
14260 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14261 DAG.getConstant(32, MVT::i8));
14262 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14263 Results.push_back(Chain);
14267 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14268 SDValue Ops[] = { LO, HI };
14269 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14270 Results.push_back(Pair);
14271 Results.push_back(Chain);
14274 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14275 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14276 // also used to custom lower READCYCLECOUNTER nodes.
14277 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14278 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14279 SmallVectorImpl<SDValue> &Results) {
14280 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14281 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14284 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14285 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14286 // and the EAX register is loaded with the low-order 32 bits.
14287 if (Subtarget->is64Bit()) {
14288 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14289 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14292 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14293 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14296 SDValue Chain = HI.getValue(1);
14298 if (Opcode == X86ISD::RDTSCP_DAG) {
14299 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14301 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14302 // the ECX register. Add 'ecx' explicitly to the chain.
14303 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14305 // Explicitly store the content of ECX at the location passed in input
14306 // to the 'rdtscp' intrinsic.
14307 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14308 MachinePointerInfo(), false, false, 0);
14311 if (Subtarget->is64Bit()) {
14312 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14313 // the EAX register is loaded with the low-order 32 bits.
14314 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14315 DAG.getConstant(32, MVT::i8));
14316 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14317 Results.push_back(Chain);
14321 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14322 SDValue Ops[] = { LO, HI };
14323 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14324 Results.push_back(Pair);
14325 Results.push_back(Chain);
14328 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14329 SelectionDAG &DAG) {
14330 SmallVector<SDValue, 2> Results;
14332 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14334 return DAG.getMergeValues(Results, DL);
14337 enum IntrinsicType {
14338 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14341 struct IntrinsicData {
14342 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14343 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14344 IntrinsicType Type;
14349 std::map < unsigned, IntrinsicData> IntrMap;
14350 static void InitIntinsicsMap() {
14351 static bool Initialized = false;
14354 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14355 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14356 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14357 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14358 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14359 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14360 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14361 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14362 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14363 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14364 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
14365 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14366 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
14367 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14368 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
14369 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14370 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
14371 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14373 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14374 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14375 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
14376 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14377 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
14378 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14379 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
14380 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14381 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
14382 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14383 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
14384 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14385 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
14386 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14387 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
14388 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14390 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
14391 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14392 X86::VGATHERPF1QPSm)));
14393 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
14394 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14395 X86::VGATHERPF1QPDm)));
14396 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
14397 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14398 X86::VGATHERPF1DPDm)));
14399 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
14400 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14401 X86::VGATHERPF1DPSm)));
14402 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
14403 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14404 X86::VSCATTERPF1QPSm)));
14405 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
14406 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14407 X86::VSCATTERPF1QPDm)));
14408 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
14409 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14410 X86::VSCATTERPF1DPDm)));
14411 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
14412 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14413 X86::VSCATTERPF1DPSm)));
14414 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14415 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14416 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14417 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14418 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14419 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14420 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14421 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14422 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14423 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14424 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14425 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14426 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14427 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
14428 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14429 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
14430 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14431 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
14432 IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14433 IntrinsicData(RDPMC, X86ISD::RDPMC_DAG, 0)));
14434 Initialized = true;
14437 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14438 SelectionDAG &DAG) {
14439 InitIntinsicsMap();
14440 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14441 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14442 if (itr == IntrMap.end())
14446 IntrinsicData Intr = itr->second;
14447 switch(Intr.Type) {
14450 // Emit the node with the right value type.
14451 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14452 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14454 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14455 // Otherwise return the value from Rand, which is always 0, casted to i32.
14456 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14457 DAG.getConstant(1, Op->getValueType(1)),
14458 DAG.getConstant(X86::COND_B, MVT::i32),
14459 SDValue(Result.getNode(), 1) };
14460 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14461 DAG.getVTList(Op->getValueType(1), MVT::Glue),
14464 // Return { result, isValid, chain }.
14465 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14466 SDValue(Result.getNode(), 2));
14469 //gather(v1, mask, index, base, scale);
14470 SDValue Chain = Op.getOperand(0);
14471 SDValue Src = Op.getOperand(2);
14472 SDValue Base = Op.getOperand(3);
14473 SDValue Index = Op.getOperand(4);
14474 SDValue Mask = Op.getOperand(5);
14475 SDValue Scale = Op.getOperand(6);
14476 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14480 //scatter(base, mask, index, v1, scale);
14481 SDValue Chain = Op.getOperand(0);
14482 SDValue Base = Op.getOperand(2);
14483 SDValue Mask = Op.getOperand(3);
14484 SDValue Index = Op.getOperand(4);
14485 SDValue Src = Op.getOperand(5);
14486 SDValue Scale = Op.getOperand(6);
14487 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14490 SDValue Hint = Op.getOperand(6);
14492 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14493 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14494 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14495 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14496 SDValue Chain = Op.getOperand(0);
14497 SDValue Mask = Op.getOperand(2);
14498 SDValue Index = Op.getOperand(3);
14499 SDValue Base = Op.getOperand(4);
14500 SDValue Scale = Op.getOperand(5);
14501 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14503 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14505 SmallVector<SDValue, 2> Results;
14506 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14507 return DAG.getMergeValues(Results, dl);
14509 // Read Performance Monitoring Counters.
14511 SmallVector<SDValue, 2> Results;
14512 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14513 return DAG.getMergeValues(Results, dl);
14515 // XTEST intrinsics.
14517 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14518 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14519 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14520 DAG.getConstant(X86::COND_NE, MVT::i8),
14522 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14523 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14524 Ret, SDValue(InTrans.getNode(), 1));
14527 llvm_unreachable("Unknown Intrinsic Type");
14530 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14531 SelectionDAG &DAG) const {
14532 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14533 MFI->setReturnAddressIsTaken(true);
14535 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14538 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14540 EVT PtrVT = getPointerTy();
14543 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14544 const X86RegisterInfo *RegInfo =
14545 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14546 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14547 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14548 DAG.getNode(ISD::ADD, dl, PtrVT,
14549 FrameAddr, Offset),
14550 MachinePointerInfo(), false, false, false, 0);
14553 // Just load the return address.
14554 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14555 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14556 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14559 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14560 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14561 MFI->setFrameAddressIsTaken(true);
14563 EVT VT = Op.getValueType();
14564 SDLoc dl(Op); // FIXME probably not meaningful
14565 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14566 const X86RegisterInfo *RegInfo =
14567 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14568 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14569 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14570 (FrameReg == X86::EBP && VT == MVT::i32)) &&
14571 "Invalid Frame Register!");
14572 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14574 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14575 MachinePointerInfo(),
14576 false, false, false, 0);
14580 // FIXME? Maybe this could be a TableGen attribute on some registers and
14581 // this table could be generated automatically from RegInfo.
14582 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14584 unsigned Reg = StringSwitch<unsigned>(RegName)
14585 .Case("esp", X86::ESP)
14586 .Case("rsp", X86::RSP)
14590 report_fatal_error("Invalid register name global variable");
14593 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14594 SelectionDAG &DAG) const {
14595 const X86RegisterInfo *RegInfo =
14596 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14597 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14600 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14601 SDValue Chain = Op.getOperand(0);
14602 SDValue Offset = Op.getOperand(1);
14603 SDValue Handler = Op.getOperand(2);
14606 EVT PtrVT = getPointerTy();
14607 const X86RegisterInfo *RegInfo =
14608 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14609 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14610 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14611 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14612 "Invalid Frame Register!");
14613 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14614 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14616 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14617 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14618 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14619 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14621 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14623 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14624 DAG.getRegister(StoreAddrReg, PtrVT));
14627 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14628 SelectionDAG &DAG) const {
14630 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14631 DAG.getVTList(MVT::i32, MVT::Other),
14632 Op.getOperand(0), Op.getOperand(1));
14635 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14636 SelectionDAG &DAG) const {
14638 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14639 Op.getOperand(0), Op.getOperand(1));
14642 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14643 return Op.getOperand(0);
14646 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14647 SelectionDAG &DAG) const {
14648 SDValue Root = Op.getOperand(0);
14649 SDValue Trmp = Op.getOperand(1); // trampoline
14650 SDValue FPtr = Op.getOperand(2); // nested function
14651 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14654 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14655 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14657 if (Subtarget->is64Bit()) {
14658 SDValue OutChains[6];
14660 // Large code-model.
14661 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
14662 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14664 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14665 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14667 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14669 // Load the pointer to the nested function into R11.
14670 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14671 SDValue Addr = Trmp;
14672 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14673 Addr, MachinePointerInfo(TrmpAddr),
14676 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14677 DAG.getConstant(2, MVT::i64));
14678 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14679 MachinePointerInfo(TrmpAddr, 2),
14682 // Load the 'nest' parameter value into R10.
14683 // R10 is specified in X86CallingConv.td
14684 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14685 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14686 DAG.getConstant(10, MVT::i64));
14687 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14688 Addr, MachinePointerInfo(TrmpAddr, 10),
14691 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14692 DAG.getConstant(12, MVT::i64));
14693 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14694 MachinePointerInfo(TrmpAddr, 12),
14697 // Jump to the nested function.
14698 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14699 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14700 DAG.getConstant(20, MVT::i64));
14701 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14702 Addr, MachinePointerInfo(TrmpAddr, 20),
14705 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14706 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14707 DAG.getConstant(22, MVT::i64));
14708 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14709 MachinePointerInfo(TrmpAddr, 22),
14712 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14714 const Function *Func =
14715 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14716 CallingConv::ID CC = Func->getCallingConv();
14721 llvm_unreachable("Unsupported calling convention");
14722 case CallingConv::C:
14723 case CallingConv::X86_StdCall: {
14724 // Pass 'nest' parameter in ECX.
14725 // Must be kept in sync with X86CallingConv.td
14726 NestReg = X86::ECX;
14728 // Check that ECX wasn't needed by an 'inreg' parameter.
14729 FunctionType *FTy = Func->getFunctionType();
14730 const AttributeSet &Attrs = Func->getAttributes();
14732 if (!Attrs.isEmpty() && !Func->isVarArg()) {
14733 unsigned InRegCount = 0;
14736 for (FunctionType::param_iterator I = FTy->param_begin(),
14737 E = FTy->param_end(); I != E; ++I, ++Idx)
14738 if (Attrs.hasAttribute(Idx, Attribute::InReg))
14739 // FIXME: should only count parameters that are lowered to integers.
14740 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14742 if (InRegCount > 2) {
14743 report_fatal_error("Nest register in use - reduce number of inreg"
14749 case CallingConv::X86_FastCall:
14750 case CallingConv::X86_ThisCall:
14751 case CallingConv::Fast:
14752 // Pass 'nest' parameter in EAX.
14753 // Must be kept in sync with X86CallingConv.td
14754 NestReg = X86::EAX;
14758 SDValue OutChains[4];
14759 SDValue Addr, Disp;
14761 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14762 DAG.getConstant(10, MVT::i32));
14763 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14765 // This is storing the opcode for MOV32ri.
14766 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14767 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14768 OutChains[0] = DAG.getStore(Root, dl,
14769 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14770 Trmp, MachinePointerInfo(TrmpAddr),
14773 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14774 DAG.getConstant(1, MVT::i32));
14775 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14776 MachinePointerInfo(TrmpAddr, 1),
14779 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14780 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14781 DAG.getConstant(5, MVT::i32));
14782 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14783 MachinePointerInfo(TrmpAddr, 5),
14786 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14787 DAG.getConstant(6, MVT::i32));
14788 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14789 MachinePointerInfo(TrmpAddr, 6),
14792 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14796 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14797 SelectionDAG &DAG) const {
14799 The rounding mode is in bits 11:10 of FPSR, and has the following
14801 00 Round to nearest
14806 FLT_ROUNDS, on the other hand, expects the following:
14813 To perform the conversion, we do:
14814 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14817 MachineFunction &MF = DAG.getMachineFunction();
14818 const TargetMachine &TM = MF.getTarget();
14819 const TargetFrameLowering &TFI = *TM.getFrameLowering();
14820 unsigned StackAlignment = TFI.getStackAlignment();
14821 MVT VT = Op.getSimpleValueType();
14824 // Save FP Control Word to stack slot
14825 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14826 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14828 MachineMemOperand *MMO =
14829 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14830 MachineMemOperand::MOStore, 2, 2);
14832 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14833 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14834 DAG.getVTList(MVT::Other),
14835 Ops, MVT::i16, MMO);
14837 // Load FP Control Word from stack slot
14838 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14839 MachinePointerInfo(), false, false, false, 0);
14841 // Transform as necessary
14843 DAG.getNode(ISD::SRL, DL, MVT::i16,
14844 DAG.getNode(ISD::AND, DL, MVT::i16,
14845 CWD, DAG.getConstant(0x800, MVT::i16)),
14846 DAG.getConstant(11, MVT::i8));
14848 DAG.getNode(ISD::SRL, DL, MVT::i16,
14849 DAG.getNode(ISD::AND, DL, MVT::i16,
14850 CWD, DAG.getConstant(0x400, MVT::i16)),
14851 DAG.getConstant(9, MVT::i8));
14854 DAG.getNode(ISD::AND, DL, MVT::i16,
14855 DAG.getNode(ISD::ADD, DL, MVT::i16,
14856 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14857 DAG.getConstant(1, MVT::i16)),
14858 DAG.getConstant(3, MVT::i16));
14860 return DAG.getNode((VT.getSizeInBits() < 16 ?
14861 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14864 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14865 MVT VT = Op.getSimpleValueType();
14867 unsigned NumBits = VT.getSizeInBits();
14870 Op = Op.getOperand(0);
14871 if (VT == MVT::i8) {
14872 // Zero extend to i32 since there is not an i8 bsr.
14874 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14877 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14878 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14879 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14881 // If src is zero (i.e. bsr sets ZF), returns NumBits.
14884 DAG.getConstant(NumBits+NumBits-1, OpVT),
14885 DAG.getConstant(X86::COND_E, MVT::i8),
14888 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14890 // Finally xor with NumBits-1.
14891 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14894 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14898 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14899 MVT VT = Op.getSimpleValueType();
14901 unsigned NumBits = VT.getSizeInBits();
14904 Op = Op.getOperand(0);
14905 if (VT == MVT::i8) {
14906 // Zero extend to i32 since there is not an i8 bsr.
14908 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14911 // Issue a bsr (scan bits in reverse).
14912 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14913 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14915 // And xor with NumBits-1.
14916 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14919 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14923 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14924 MVT VT = Op.getSimpleValueType();
14925 unsigned NumBits = VT.getSizeInBits();
14927 Op = Op.getOperand(0);
14929 // Issue a bsf (scan bits forward) which also sets EFLAGS.
14930 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14931 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14933 // If src is zero (i.e. bsf sets ZF), returns NumBits.
14936 DAG.getConstant(NumBits, VT),
14937 DAG.getConstant(X86::COND_E, MVT::i8),
14940 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14943 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14944 // ones, and then concatenate the result back.
14945 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14946 MVT VT = Op.getSimpleValueType();
14948 assert(VT.is256BitVector() && VT.isInteger() &&
14949 "Unsupported value type for operation");
14951 unsigned NumElems = VT.getVectorNumElements();
14954 // Extract the LHS vectors
14955 SDValue LHS = Op.getOperand(0);
14956 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14957 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14959 // Extract the RHS vectors
14960 SDValue RHS = Op.getOperand(1);
14961 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14962 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14964 MVT EltVT = VT.getVectorElementType();
14965 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14967 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14968 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
14969 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
14972 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
14973 assert(Op.getSimpleValueType().is256BitVector() &&
14974 Op.getSimpleValueType().isInteger() &&
14975 "Only handle AVX 256-bit vector integer operation");
14976 return Lower256IntArith(Op, DAG);
14979 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
14980 assert(Op.getSimpleValueType().is256BitVector() &&
14981 Op.getSimpleValueType().isInteger() &&
14982 "Only handle AVX 256-bit vector integer operation");
14983 return Lower256IntArith(Op, DAG);
14986 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
14987 SelectionDAG &DAG) {
14989 MVT VT = Op.getSimpleValueType();
14991 // Decompose 256-bit ops into smaller 128-bit ops.
14992 if (VT.is256BitVector() && !Subtarget->hasInt256())
14993 return Lower256IntArith(Op, DAG);
14995 SDValue A = Op.getOperand(0);
14996 SDValue B = Op.getOperand(1);
14998 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
14999 if (VT == MVT::v4i32) {
15000 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15001 "Should not custom lower when pmuldq is available!");
15003 // Extract the odd parts.
15004 static const int UnpackMask[] = { 1, -1, 3, -1 };
15005 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15006 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15008 // Multiply the even parts.
15009 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15010 // Now multiply odd parts.
15011 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15013 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15014 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15016 // Merge the two vectors back together with a shuffle. This expands into 2
15018 static const int ShufMask[] = { 0, 4, 2, 6 };
15019 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15022 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15023 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15025 // Ahi = psrlqi(a, 32);
15026 // Bhi = psrlqi(b, 32);
15028 // AloBlo = pmuludq(a, b);
15029 // AloBhi = pmuludq(a, Bhi);
15030 // AhiBlo = pmuludq(Ahi, b);
15032 // AloBhi = psllqi(AloBhi, 32);
15033 // AhiBlo = psllqi(AhiBlo, 32);
15034 // return AloBlo + AloBhi + AhiBlo;
15036 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15037 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15039 // Bit cast to 32-bit vectors for MULUDQ
15040 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15041 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15042 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15043 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15044 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15045 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15047 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15048 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15049 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15051 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15052 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15054 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15055 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15058 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15059 assert(Subtarget->isTargetWin64() && "Unexpected target");
15060 EVT VT = Op.getValueType();
15061 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15062 "Unexpected return type for lowering");
15066 switch (Op->getOpcode()) {
15067 default: llvm_unreachable("Unexpected request for libcall!");
15068 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15069 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15070 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15071 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15072 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15073 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15077 SDValue InChain = DAG.getEntryNode();
15079 TargetLowering::ArgListTy Args;
15080 TargetLowering::ArgListEntry Entry;
15081 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15082 EVT ArgVT = Op->getOperand(i).getValueType();
15083 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15084 "Unexpected argument type for lowering");
15085 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15086 Entry.Node = StackPtr;
15087 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15089 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15090 Entry.Ty = PointerType::get(ArgTy,0);
15091 Entry.isSExt = false;
15092 Entry.isZExt = false;
15093 Args.push_back(Entry);
15096 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15099 TargetLowering::CallLoweringInfo CLI(DAG);
15100 CLI.setDebugLoc(dl).setChain(InChain)
15101 .setCallee(getLibcallCallingConv(LC),
15102 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15103 Callee, std::move(Args), 0)
15104 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15106 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15107 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15110 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15111 SelectionDAG &DAG) {
15112 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15113 EVT VT = Op0.getValueType();
15116 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15117 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15119 // Get the high parts.
15120 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
15121 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15122 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15124 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15126 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15127 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15129 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15130 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15131 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15132 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15133 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
15135 // Shuffle it back into the right order.
15136 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
15137 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15138 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
15139 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15141 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15142 // unsigned multiply.
15143 if (IsSigned && !Subtarget->hasSSE41()) {
15145 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15146 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15147 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15148 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15149 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15151 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15152 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15155 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
15158 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15159 const X86Subtarget *Subtarget) {
15160 MVT VT = Op.getSimpleValueType();
15162 SDValue R = Op.getOperand(0);
15163 SDValue Amt = Op.getOperand(1);
15165 // Optimize shl/srl/sra with constant shift amount.
15166 if (isSplatVector(Amt.getNode())) {
15167 SDValue SclrAmt = Amt->getOperand(0);
15168 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
15169 uint64_t ShiftAmt = C->getZExtValue();
15171 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15172 (Subtarget->hasInt256() &&
15173 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15174 (Subtarget->hasAVX512() &&
15175 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15176 if (Op.getOpcode() == ISD::SHL)
15177 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15179 if (Op.getOpcode() == ISD::SRL)
15180 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15182 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15183 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15187 if (VT == MVT::v16i8) {
15188 if (Op.getOpcode() == ISD::SHL) {
15189 // Make a large shift.
15190 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15191 MVT::v8i16, R, ShiftAmt,
15193 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15194 // Zero out the rightmost bits.
15195 SmallVector<SDValue, 16> V(16,
15196 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15198 return DAG.getNode(ISD::AND, dl, VT, SHL,
15199 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15201 if (Op.getOpcode() == ISD::SRL) {
15202 // Make a large shift.
15203 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15204 MVT::v8i16, R, ShiftAmt,
15206 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15207 // Zero out the leftmost bits.
15208 SmallVector<SDValue, 16> V(16,
15209 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15211 return DAG.getNode(ISD::AND, dl, VT, SRL,
15212 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15214 if (Op.getOpcode() == ISD::SRA) {
15215 if (ShiftAmt == 7) {
15216 // R s>> 7 === R s< 0
15217 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15218 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15221 // R s>> a === ((R u>> a) ^ m) - m
15222 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15223 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15225 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15226 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15227 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15230 llvm_unreachable("Unknown shift opcode.");
15233 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15234 if (Op.getOpcode() == ISD::SHL) {
15235 // Make a large shift.
15236 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15237 MVT::v16i16, R, ShiftAmt,
15239 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15240 // Zero out the rightmost bits.
15241 SmallVector<SDValue, 32> V(32,
15242 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15244 return DAG.getNode(ISD::AND, dl, VT, SHL,
15245 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15247 if (Op.getOpcode() == ISD::SRL) {
15248 // Make a large shift.
15249 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15250 MVT::v16i16, R, ShiftAmt,
15252 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15253 // Zero out the leftmost bits.
15254 SmallVector<SDValue, 32> V(32,
15255 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15257 return DAG.getNode(ISD::AND, dl, VT, SRL,
15258 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15260 if (Op.getOpcode() == ISD::SRA) {
15261 if (ShiftAmt == 7) {
15262 // R s>> 7 === R s< 0
15263 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15264 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15267 // R s>> a === ((R u>> a) ^ m) - m
15268 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15269 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15271 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15272 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15273 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15276 llvm_unreachable("Unknown shift opcode.");
15281 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15282 if (!Subtarget->is64Bit() &&
15283 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15284 Amt.getOpcode() == ISD::BITCAST &&
15285 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15286 Amt = Amt.getOperand(0);
15287 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15288 VT.getVectorNumElements();
15289 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15290 uint64_t ShiftAmt = 0;
15291 for (unsigned i = 0; i != Ratio; ++i) {
15292 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15296 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15298 // Check remaining shift amounts.
15299 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15300 uint64_t ShAmt = 0;
15301 for (unsigned j = 0; j != Ratio; ++j) {
15302 ConstantSDNode *C =
15303 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15307 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15309 if (ShAmt != ShiftAmt)
15312 switch (Op.getOpcode()) {
15314 llvm_unreachable("Unknown shift opcode!");
15316 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15319 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15322 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15330 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15331 const X86Subtarget* Subtarget) {
15332 MVT VT = Op.getSimpleValueType();
15334 SDValue R = Op.getOperand(0);
15335 SDValue Amt = Op.getOperand(1);
15337 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15338 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15339 (Subtarget->hasInt256() &&
15340 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15341 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15342 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15344 EVT EltVT = VT.getVectorElementType();
15346 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15347 unsigned NumElts = VT.getVectorNumElements();
15349 for (i = 0; i != NumElts; ++i) {
15350 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15354 for (j = i; j != NumElts; ++j) {
15355 SDValue Arg = Amt.getOperand(j);
15356 if (Arg.getOpcode() == ISD::UNDEF) continue;
15357 if (Arg != Amt.getOperand(i))
15360 if (i != NumElts && j == NumElts)
15361 BaseShAmt = Amt.getOperand(i);
15363 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15364 Amt = Amt.getOperand(0);
15365 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15366 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15367 SDValue InVec = Amt.getOperand(0);
15368 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15369 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15371 for (; i != NumElts; ++i) {
15372 SDValue Arg = InVec.getOperand(i);
15373 if (Arg.getOpcode() == ISD::UNDEF) continue;
15377 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15378 if (ConstantSDNode *C =
15379 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15380 unsigned SplatIdx =
15381 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15382 if (C->getZExtValue() == SplatIdx)
15383 BaseShAmt = InVec.getOperand(1);
15386 if (!BaseShAmt.getNode())
15387 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15388 DAG.getIntPtrConstant(0));
15392 if (BaseShAmt.getNode()) {
15393 if (EltVT.bitsGT(MVT::i32))
15394 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15395 else if (EltVT.bitsLT(MVT::i32))
15396 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15398 switch (Op.getOpcode()) {
15400 llvm_unreachable("Unknown shift opcode!");
15402 switch (VT.SimpleTy) {
15403 default: return SDValue();
15412 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15415 switch (VT.SimpleTy) {
15416 default: return SDValue();
15423 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15426 switch (VT.SimpleTy) {
15427 default: return SDValue();
15436 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15442 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15443 if (!Subtarget->is64Bit() &&
15444 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15445 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15446 Amt.getOpcode() == ISD::BITCAST &&
15447 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15448 Amt = Amt.getOperand(0);
15449 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15450 VT.getVectorNumElements();
15451 std::vector<SDValue> Vals(Ratio);
15452 for (unsigned i = 0; i != Ratio; ++i)
15453 Vals[i] = Amt.getOperand(i);
15454 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15455 for (unsigned j = 0; j != Ratio; ++j)
15456 if (Vals[j] != Amt.getOperand(i + j))
15459 switch (Op.getOpcode()) {
15461 llvm_unreachable("Unknown shift opcode!");
15463 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15465 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15467 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15474 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15475 SelectionDAG &DAG) {
15477 MVT VT = Op.getSimpleValueType();
15479 SDValue R = Op.getOperand(0);
15480 SDValue Amt = Op.getOperand(1);
15483 if (!Subtarget->hasSSE2())
15486 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15490 V = LowerScalarVariableShift(Op, DAG, Subtarget);
15494 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15496 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15497 if (Subtarget->hasInt256()) {
15498 if (Op.getOpcode() == ISD::SRL &&
15499 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15500 VT == MVT::v4i64 || VT == MVT::v8i32))
15502 if (Op.getOpcode() == ISD::SHL &&
15503 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15504 VT == MVT::v4i64 || VT == MVT::v8i32))
15506 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15510 // If possible, lower this packed shift into a vector multiply instead of
15511 // expanding it into a sequence of scalar shifts.
15512 // Do this only if the vector shift count is a constant build_vector.
15513 if (Op.getOpcode() == ISD::SHL &&
15514 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15515 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15516 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15517 SmallVector<SDValue, 8> Elts;
15518 EVT SVT = VT.getScalarType();
15519 unsigned SVTBits = SVT.getSizeInBits();
15520 const APInt &One = APInt(SVTBits, 1);
15521 unsigned NumElems = VT.getVectorNumElements();
15523 for (unsigned i=0; i !=NumElems; ++i) {
15524 SDValue Op = Amt->getOperand(i);
15525 if (Op->getOpcode() == ISD::UNDEF) {
15526 Elts.push_back(Op);
15530 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15531 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15532 uint64_t ShAmt = C.getZExtValue();
15533 if (ShAmt >= SVTBits) {
15534 Elts.push_back(DAG.getUNDEF(SVT));
15537 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15539 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15540 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15543 // Lower SHL with variable shift amount.
15544 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15545 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15547 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15548 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15549 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15550 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15553 // If possible, lower this shift as a sequence of two shifts by
15554 // constant plus a MOVSS/MOVSD instead of scalarizing it.
15556 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15558 // Could be rewritten as:
15559 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15561 // The advantage is that the two shifts from the example would be
15562 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15563 // the vector shift into four scalar shifts plus four pairs of vector
15565 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15566 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15567 unsigned TargetOpcode = X86ISD::MOVSS;
15568 bool CanBeSimplified;
15569 // The splat value for the first packed shift (the 'X' from the example).
15570 SDValue Amt1 = Amt->getOperand(0);
15571 // The splat value for the second packed shift (the 'Y' from the example).
15572 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15573 Amt->getOperand(2);
15575 // See if it is possible to replace this node with a sequence of
15576 // two shifts followed by a MOVSS/MOVSD
15577 if (VT == MVT::v4i32) {
15578 // Check if it is legal to use a MOVSS.
15579 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15580 Amt2 == Amt->getOperand(3);
15581 if (!CanBeSimplified) {
15582 // Otherwise, check if we can still simplify this node using a MOVSD.
15583 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15584 Amt->getOperand(2) == Amt->getOperand(3);
15585 TargetOpcode = X86ISD::MOVSD;
15586 Amt2 = Amt->getOperand(2);
15589 // Do similar checks for the case where the machine value type
15591 CanBeSimplified = Amt1 == Amt->getOperand(1);
15592 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15593 CanBeSimplified = Amt2 == Amt->getOperand(i);
15595 if (!CanBeSimplified) {
15596 TargetOpcode = X86ISD::MOVSD;
15597 CanBeSimplified = true;
15598 Amt2 = Amt->getOperand(4);
15599 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15600 CanBeSimplified = Amt1 == Amt->getOperand(i);
15601 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15602 CanBeSimplified = Amt2 == Amt->getOperand(j);
15606 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15607 isa<ConstantSDNode>(Amt2)) {
15608 // Replace this node with two shifts followed by a MOVSS/MOVSD.
15609 EVT CastVT = MVT::v4i32;
15611 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15612 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15614 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15615 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15616 if (TargetOpcode == X86ISD::MOVSD)
15617 CastVT = MVT::v2i64;
15618 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15619 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15620 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15622 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15626 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15627 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15630 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15631 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15633 // Turn 'a' into a mask suitable for VSELECT
15634 SDValue VSelM = DAG.getConstant(0x80, VT);
15635 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15636 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15638 SDValue CM1 = DAG.getConstant(0x0f, VT);
15639 SDValue CM2 = DAG.getConstant(0x3f, VT);
15641 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15642 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15643 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15644 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15645 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15648 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15649 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15650 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15652 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15653 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15654 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15655 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15656 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15659 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15660 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15661 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15663 // return VSELECT(r, r+r, a);
15664 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15665 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15669 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15670 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15671 // solution better.
15672 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15673 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15675 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15676 R = DAG.getNode(ExtOpc, dl, NewVT, R);
15677 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15678 return DAG.getNode(ISD::TRUNCATE, dl, VT,
15679 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15682 // Decompose 256-bit shifts into smaller 128-bit shifts.
15683 if (VT.is256BitVector()) {
15684 unsigned NumElems = VT.getVectorNumElements();
15685 MVT EltVT = VT.getVectorElementType();
15686 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15688 // Extract the two vectors
15689 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15690 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15692 // Recreate the shift amount vectors
15693 SDValue Amt1, Amt2;
15694 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15695 // Constant shift amount
15696 SmallVector<SDValue, 4> Amt1Csts;
15697 SmallVector<SDValue, 4> Amt2Csts;
15698 for (unsigned i = 0; i != NumElems/2; ++i)
15699 Amt1Csts.push_back(Amt->getOperand(i));
15700 for (unsigned i = NumElems/2; i != NumElems; ++i)
15701 Amt2Csts.push_back(Amt->getOperand(i));
15703 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15704 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15706 // Variable shift amount
15707 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15708 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15711 // Issue new vector shifts for the smaller types
15712 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15713 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15715 // Concatenate the result back
15716 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15722 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15723 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15724 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15725 // looks for this combo and may remove the "setcc" instruction if the "setcc"
15726 // has only one use.
15727 SDNode *N = Op.getNode();
15728 SDValue LHS = N->getOperand(0);
15729 SDValue RHS = N->getOperand(1);
15730 unsigned BaseOp = 0;
15733 switch (Op.getOpcode()) {
15734 default: llvm_unreachable("Unknown ovf instruction!");
15736 // A subtract of one will be selected as a INC. Note that INC doesn't
15737 // set CF, so we can't do this for UADDO.
15738 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15740 BaseOp = X86ISD::INC;
15741 Cond = X86::COND_O;
15744 BaseOp = X86ISD::ADD;
15745 Cond = X86::COND_O;
15748 BaseOp = X86ISD::ADD;
15749 Cond = X86::COND_B;
15752 // A subtract of one will be selected as a DEC. Note that DEC doesn't
15753 // set CF, so we can't do this for USUBO.
15754 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15756 BaseOp = X86ISD::DEC;
15757 Cond = X86::COND_O;
15760 BaseOp = X86ISD::SUB;
15761 Cond = X86::COND_O;
15764 BaseOp = X86ISD::SUB;
15765 Cond = X86::COND_B;
15768 BaseOp = X86ISD::SMUL;
15769 Cond = X86::COND_O;
15771 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15772 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15774 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15777 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15778 DAG.getConstant(X86::COND_O, MVT::i32),
15779 SDValue(Sum.getNode(), 2));
15781 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15785 // Also sets EFLAGS.
15786 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15787 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15790 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15791 DAG.getConstant(Cond, MVT::i32),
15792 SDValue(Sum.getNode(), 1));
15794 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15797 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15798 SelectionDAG &DAG) const {
15800 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15801 MVT VT = Op.getSimpleValueType();
15803 if (!Subtarget->hasSSE2() || !VT.isVector())
15806 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15807 ExtraVT.getScalarType().getSizeInBits();
15809 switch (VT.SimpleTy) {
15810 default: return SDValue();
15813 if (!Subtarget->hasFp256())
15815 if (!Subtarget->hasInt256()) {
15816 // needs to be split
15817 unsigned NumElems = VT.getVectorNumElements();
15819 // Extract the LHS vectors
15820 SDValue LHS = Op.getOperand(0);
15821 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15822 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15824 MVT EltVT = VT.getVectorElementType();
15825 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15827 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15828 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15829 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15831 SDValue Extra = DAG.getValueType(ExtraVT);
15833 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15834 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15836 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15841 SDValue Op0 = Op.getOperand(0);
15842 SDValue Op00 = Op0.getOperand(0);
15844 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15845 if (Op0.getOpcode() == ISD::BITCAST &&
15846 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15847 // (sext (vzext x)) -> (vsext x)
15848 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15849 if (Tmp1.getNode()) {
15850 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15851 // This folding is only valid when the in-reg type is a vector of i8,
15853 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15854 ExtraEltVT == MVT::i32) {
15855 SDValue Tmp1Op0 = Tmp1.getOperand(0);
15856 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15857 "This optimization is invalid without a VZEXT.");
15858 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15864 // If the above didn't work, then just use Shift-Left + Shift-Right.
15865 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15867 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15873 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15874 SelectionDAG &DAG) {
15876 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15877 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15878 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15879 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15881 // The only fence that needs an instruction is a sequentially-consistent
15882 // cross-thread fence.
15883 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15884 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15885 // no-sse2). There isn't any reason to disable it if the target processor
15887 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15888 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15890 SDValue Chain = Op.getOperand(0);
15891 SDValue Zero = DAG.getConstant(0, MVT::i32);
15893 DAG.getRegister(X86::ESP, MVT::i32), // Base
15894 DAG.getTargetConstant(1, MVT::i8), // Scale
15895 DAG.getRegister(0, MVT::i32), // Index
15896 DAG.getTargetConstant(0, MVT::i32), // Disp
15897 DAG.getRegister(0, MVT::i32), // Segment.
15901 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15902 return SDValue(Res, 0);
15905 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15906 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15909 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15910 SelectionDAG &DAG) {
15911 MVT T = Op.getSimpleValueType();
15915 switch(T.SimpleTy) {
15916 default: llvm_unreachable("Invalid value type!");
15917 case MVT::i8: Reg = X86::AL; size = 1; break;
15918 case MVT::i16: Reg = X86::AX; size = 2; break;
15919 case MVT::i32: Reg = X86::EAX; size = 4; break;
15921 assert(Subtarget->is64Bit() && "Node not type legal!");
15922 Reg = X86::RAX; size = 8;
15925 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
15926 Op.getOperand(2), SDValue());
15927 SDValue Ops[] = { cpIn.getValue(0),
15930 DAG.getTargetConstant(size, MVT::i8),
15931 cpIn.getValue(1) };
15932 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15933 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
15934 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
15938 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
15939 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
15940 MVT::i32, cpOut.getValue(2));
15941 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
15942 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15944 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
15945 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
15946 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
15950 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
15951 SelectionDAG &DAG) {
15952 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
15953 MVT DstVT = Op.getSimpleValueType();
15955 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
15956 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15957 if (DstVT != MVT::f64)
15958 // This conversion needs to be expanded.
15961 SDValue InVec = Op->getOperand(0);
15963 unsigned NumElts = SrcVT.getVectorNumElements();
15964 EVT SVT = SrcVT.getVectorElementType();
15966 // Widen the vector in input in the case of MVT::v2i32.
15967 // Example: from MVT::v2i32 to MVT::v4i32.
15968 SmallVector<SDValue, 16> Elts;
15969 for (unsigned i = 0, e = NumElts; i != e; ++i)
15970 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
15971 DAG.getIntPtrConstant(i)));
15973 // Explicitly mark the extra elements as Undef.
15974 SDValue Undef = DAG.getUNDEF(SVT);
15975 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
15976 Elts.push_back(Undef);
15978 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15979 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
15980 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
15981 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
15982 DAG.getIntPtrConstant(0));
15985 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
15986 Subtarget->hasMMX() && "Unexpected custom BITCAST");
15987 assert((DstVT == MVT::i64 ||
15988 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
15989 "Unexpected custom BITCAST");
15990 // i64 <=> MMX conversions are Legal.
15991 if (SrcVT==MVT::i64 && DstVT.isVector())
15993 if (DstVT==MVT::i64 && SrcVT.isVector())
15995 // MMX <=> MMX conversions are Legal.
15996 if (SrcVT.isVector() && DstVT.isVector())
15998 // All other conversions need to be expanded.
16002 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16003 SDNode *Node = Op.getNode();
16005 EVT T = Node->getValueType(0);
16006 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16007 DAG.getConstant(0, T), Node->getOperand(2));
16008 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16009 cast<AtomicSDNode>(Node)->getMemoryVT(),
16010 Node->getOperand(0),
16011 Node->getOperand(1), negOp,
16012 cast<AtomicSDNode>(Node)->getMemOperand(),
16013 cast<AtomicSDNode>(Node)->getOrdering(),
16014 cast<AtomicSDNode>(Node)->getSynchScope());
16017 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16018 SDNode *Node = Op.getNode();
16020 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16022 // Convert seq_cst store -> xchg
16023 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16024 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16025 // (The only way to get a 16-byte store is cmpxchg16b)
16026 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16027 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16028 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16029 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16030 cast<AtomicSDNode>(Node)->getMemoryVT(),
16031 Node->getOperand(0),
16032 Node->getOperand(1), Node->getOperand(2),
16033 cast<AtomicSDNode>(Node)->getMemOperand(),
16034 cast<AtomicSDNode>(Node)->getOrdering(),
16035 cast<AtomicSDNode>(Node)->getSynchScope());
16036 return Swap.getValue(1);
16038 // Other atomic stores have a simple pattern.
16042 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16043 EVT VT = Op.getNode()->getSimpleValueType(0);
16045 // Let legalize expand this if it isn't a legal type yet.
16046 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16049 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16052 bool ExtraOp = false;
16053 switch (Op.getOpcode()) {
16054 default: llvm_unreachable("Invalid code");
16055 case ISD::ADDC: Opc = X86ISD::ADD; break;
16056 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16057 case ISD::SUBC: Opc = X86ISD::SUB; break;
16058 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16062 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16064 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16065 Op.getOperand(1), Op.getOperand(2));
16068 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16069 SelectionDAG &DAG) {
16070 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16072 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16073 // which returns the values as { float, float } (in XMM0) or
16074 // { double, double } (which is returned in XMM0, XMM1).
16076 SDValue Arg = Op.getOperand(0);
16077 EVT ArgVT = Arg.getValueType();
16078 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16080 TargetLowering::ArgListTy Args;
16081 TargetLowering::ArgListEntry Entry;
16085 Entry.isSExt = false;
16086 Entry.isZExt = false;
16087 Args.push_back(Entry);
16089 bool isF64 = ArgVT == MVT::f64;
16090 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16091 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16092 // the results are returned via SRet in memory.
16093 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16094 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16095 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16097 Type *RetTy = isF64
16098 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16099 : (Type*)VectorType::get(ArgTy, 4);
16101 TargetLowering::CallLoweringInfo CLI(DAG);
16102 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16103 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16105 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16108 // Returned in xmm0 and xmm1.
16109 return CallResult.first;
16111 // Returned in bits 0:31 and 32:64 xmm0.
16112 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16113 CallResult.first, DAG.getIntPtrConstant(0));
16114 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16115 CallResult.first, DAG.getIntPtrConstant(1));
16116 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16117 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16120 /// LowerOperation - Provide custom lowering hooks for some operations.
16122 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16123 switch (Op.getOpcode()) {
16124 default: llvm_unreachable("Should not custom lower this!");
16125 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16126 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16127 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16128 return LowerCMP_SWAP(Op, Subtarget, DAG);
16129 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16130 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16131 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16132 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16133 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16134 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16135 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16136 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16137 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16138 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16139 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16140 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16141 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16142 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16143 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16144 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16145 case ISD::SHL_PARTS:
16146 case ISD::SRA_PARTS:
16147 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16148 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16149 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16150 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16151 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16152 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16153 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16154 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16155 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16156 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16157 case ISD::FABS: return LowerFABS(Op, DAG);
16158 case ISD::FNEG: return LowerFNEG(Op, DAG);
16159 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16160 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16161 case ISD::SETCC: return LowerSETCC(Op, DAG);
16162 case ISD::SELECT: return LowerSELECT(Op, DAG);
16163 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16164 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16165 case ISD::VASTART: return LowerVASTART(Op, DAG);
16166 case ISD::VAARG: return LowerVAARG(Op, DAG);
16167 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16168 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16169 case ISD::INTRINSIC_VOID:
16170 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16171 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16172 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16173 case ISD::FRAME_TO_ARGS_OFFSET:
16174 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16175 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16176 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16177 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16178 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16179 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16180 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16181 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16182 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16183 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16184 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16185 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16186 case ISD::UMUL_LOHI:
16187 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16190 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16196 case ISD::UMULO: return LowerXALUO(Op, DAG);
16197 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16198 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16202 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16203 case ISD::ADD: return LowerADD(Op, DAG);
16204 case ISD::SUB: return LowerSUB(Op, DAG);
16205 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16209 static void ReplaceATOMIC_LOAD(SDNode *Node,
16210 SmallVectorImpl<SDValue> &Results,
16211 SelectionDAG &DAG) {
16213 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16215 // Convert wide load -> cmpxchg8b/cmpxchg16b
16216 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16217 // (The only way to get a 16-byte load is cmpxchg16b)
16218 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16219 SDValue Zero = DAG.getConstant(0, VT);
16220 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16222 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16223 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16224 cast<AtomicSDNode>(Node)->getMemOperand(),
16225 cast<AtomicSDNode>(Node)->getOrdering(),
16226 cast<AtomicSDNode>(Node)->getOrdering(),
16227 cast<AtomicSDNode>(Node)->getSynchScope());
16228 Results.push_back(Swap.getValue(0));
16229 Results.push_back(Swap.getValue(2));
16232 /// ReplaceNodeResults - Replace a node with an illegal result type
16233 /// with a new node built out of custom code.
16234 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16235 SmallVectorImpl<SDValue>&Results,
16236 SelectionDAG &DAG) const {
16238 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16239 switch (N->getOpcode()) {
16241 llvm_unreachable("Do not know how to custom type legalize this operation!");
16242 case ISD::SIGN_EXTEND_INREG:
16247 // We don't want to expand or promote these.
16254 case ISD::UDIVREM: {
16255 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16256 Results.push_back(V);
16259 case ISD::FP_TO_SINT:
16260 case ISD::FP_TO_UINT: {
16261 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16263 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16266 std::pair<SDValue,SDValue> Vals =
16267 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16268 SDValue FIST = Vals.first, StackSlot = Vals.second;
16269 if (FIST.getNode()) {
16270 EVT VT = N->getValueType(0);
16271 // Return a load from the stack slot.
16272 if (StackSlot.getNode())
16273 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16274 MachinePointerInfo(),
16275 false, false, false, 0));
16277 Results.push_back(FIST);
16281 case ISD::UINT_TO_FP: {
16282 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16283 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16284 N->getValueType(0) != MVT::v2f32)
16286 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16288 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16290 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16291 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16292 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16293 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16294 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16295 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16298 case ISD::FP_ROUND: {
16299 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16301 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16302 Results.push_back(V);
16305 case ISD::INTRINSIC_W_CHAIN: {
16306 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16308 default : llvm_unreachable("Do not know how to custom type "
16309 "legalize this intrinsic operation!");
16310 case Intrinsic::x86_rdtsc:
16311 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16313 case Intrinsic::x86_rdtscp:
16314 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16316 case Intrinsic::x86_rdpmc:
16317 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16320 case ISD::READCYCLECOUNTER: {
16321 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16324 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16325 EVT T = N->getValueType(0);
16326 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16327 bool Regs64bit = T == MVT::i128;
16328 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16329 SDValue cpInL, cpInH;
16330 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16331 DAG.getConstant(0, HalfT));
16332 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16333 DAG.getConstant(1, HalfT));
16334 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16335 Regs64bit ? X86::RAX : X86::EAX,
16337 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16338 Regs64bit ? X86::RDX : X86::EDX,
16339 cpInH, cpInL.getValue(1));
16340 SDValue swapInL, swapInH;
16341 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16342 DAG.getConstant(0, HalfT));
16343 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16344 DAG.getConstant(1, HalfT));
16345 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16346 Regs64bit ? X86::RBX : X86::EBX,
16347 swapInL, cpInH.getValue(1));
16348 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16349 Regs64bit ? X86::RCX : X86::ECX,
16350 swapInH, swapInL.getValue(1));
16351 SDValue Ops[] = { swapInH.getValue(0),
16353 swapInH.getValue(1) };
16354 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16355 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16356 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16357 X86ISD::LCMPXCHG8_DAG;
16358 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16359 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16360 Regs64bit ? X86::RAX : X86::EAX,
16361 HalfT, Result.getValue(1));
16362 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16363 Regs64bit ? X86::RDX : X86::EDX,
16364 HalfT, cpOutL.getValue(2));
16365 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16367 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16368 MVT::i32, cpOutH.getValue(2));
16370 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16371 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16372 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16374 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16375 Results.push_back(Success);
16376 Results.push_back(EFLAGS.getValue(1));
16379 case ISD::ATOMIC_SWAP:
16380 case ISD::ATOMIC_LOAD_ADD:
16381 case ISD::ATOMIC_LOAD_SUB:
16382 case ISD::ATOMIC_LOAD_AND:
16383 case ISD::ATOMIC_LOAD_OR:
16384 case ISD::ATOMIC_LOAD_XOR:
16385 case ISD::ATOMIC_LOAD_NAND:
16386 case ISD::ATOMIC_LOAD_MIN:
16387 case ISD::ATOMIC_LOAD_MAX:
16388 case ISD::ATOMIC_LOAD_UMIN:
16389 case ISD::ATOMIC_LOAD_UMAX:
16390 // Delegate to generic TypeLegalization. Situations we can really handle
16391 // should have already been dealt with by X86AtomicExpand.cpp.
16393 case ISD::ATOMIC_LOAD: {
16394 ReplaceATOMIC_LOAD(N, Results, DAG);
16397 case ISD::BITCAST: {
16398 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16399 EVT DstVT = N->getValueType(0);
16400 EVT SrcVT = N->getOperand(0)->getValueType(0);
16402 if (SrcVT != MVT::f64 ||
16403 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16406 unsigned NumElts = DstVT.getVectorNumElements();
16407 EVT SVT = DstVT.getVectorElementType();
16408 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16409 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16410 MVT::v2f64, N->getOperand(0));
16411 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16413 if (ExperimentalVectorWideningLegalization) {
16414 // If we are legalizing vectors by widening, we already have the desired
16415 // legal vector type, just return it.
16416 Results.push_back(ToVecInt);
16420 SmallVector<SDValue, 8> Elts;
16421 for (unsigned i = 0, e = NumElts; i != e; ++i)
16422 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16423 ToVecInt, DAG.getIntPtrConstant(i)));
16425 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16430 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16432 default: return nullptr;
16433 case X86ISD::BSF: return "X86ISD::BSF";
16434 case X86ISD::BSR: return "X86ISD::BSR";
16435 case X86ISD::SHLD: return "X86ISD::SHLD";
16436 case X86ISD::SHRD: return "X86ISD::SHRD";
16437 case X86ISD::FAND: return "X86ISD::FAND";
16438 case X86ISD::FANDN: return "X86ISD::FANDN";
16439 case X86ISD::FOR: return "X86ISD::FOR";
16440 case X86ISD::FXOR: return "X86ISD::FXOR";
16441 case X86ISD::FSRL: return "X86ISD::FSRL";
16442 case X86ISD::FILD: return "X86ISD::FILD";
16443 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
16444 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16445 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16446 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16447 case X86ISD::FLD: return "X86ISD::FLD";
16448 case X86ISD::FST: return "X86ISD::FST";
16449 case X86ISD::CALL: return "X86ISD::CALL";
16450 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
16451 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
16452 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
16453 case X86ISD::BT: return "X86ISD::BT";
16454 case X86ISD::CMP: return "X86ISD::CMP";
16455 case X86ISD::COMI: return "X86ISD::COMI";
16456 case X86ISD::UCOMI: return "X86ISD::UCOMI";
16457 case X86ISD::CMPM: return "X86ISD::CMPM";
16458 case X86ISD::CMPMU: return "X86ISD::CMPMU";
16459 case X86ISD::SETCC: return "X86ISD::SETCC";
16460 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
16461 case X86ISD::FSETCC: return "X86ISD::FSETCC";
16462 case X86ISD::CMOV: return "X86ISD::CMOV";
16463 case X86ISD::BRCOND: return "X86ISD::BRCOND";
16464 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
16465 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
16466 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
16467 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
16468 case X86ISD::Wrapper: return "X86ISD::Wrapper";
16469 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
16470 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
16471 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
16472 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
16473 case X86ISD::PINSRB: return "X86ISD::PINSRB";
16474 case X86ISD::PINSRW: return "X86ISD::PINSRW";
16475 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
16476 case X86ISD::ANDNP: return "X86ISD::ANDNP";
16477 case X86ISD::PSIGN: return "X86ISD::PSIGN";
16478 case X86ISD::BLENDV: return "X86ISD::BLENDV";
16479 case X86ISD::BLENDI: return "X86ISD::BLENDI";
16480 case X86ISD::SUBUS: return "X86ISD::SUBUS";
16481 case X86ISD::HADD: return "X86ISD::HADD";
16482 case X86ISD::HSUB: return "X86ISD::HSUB";
16483 case X86ISD::FHADD: return "X86ISD::FHADD";
16484 case X86ISD::FHSUB: return "X86ISD::FHSUB";
16485 case X86ISD::UMAX: return "X86ISD::UMAX";
16486 case X86ISD::UMIN: return "X86ISD::UMIN";
16487 case X86ISD::SMAX: return "X86ISD::SMAX";
16488 case X86ISD::SMIN: return "X86ISD::SMIN";
16489 case X86ISD::FMAX: return "X86ISD::FMAX";
16490 case X86ISD::FMIN: return "X86ISD::FMIN";
16491 case X86ISD::FMAXC: return "X86ISD::FMAXC";
16492 case X86ISD::FMINC: return "X86ISD::FMINC";
16493 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
16494 case X86ISD::FRCP: return "X86ISD::FRCP";
16495 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
16496 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
16497 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
16498 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
16499 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
16500 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
16501 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
16502 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
16503 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
16504 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
16505 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
16506 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
16507 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
16508 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
16509 case X86ISD::VZEXT: return "X86ISD::VZEXT";
16510 case X86ISD::VSEXT: return "X86ISD::VSEXT";
16511 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
16512 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
16513 case X86ISD::VINSERT: return "X86ISD::VINSERT";
16514 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
16515 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
16516 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
16517 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
16518 case X86ISD::VSHL: return "X86ISD::VSHL";
16519 case X86ISD::VSRL: return "X86ISD::VSRL";
16520 case X86ISD::VSRA: return "X86ISD::VSRA";
16521 case X86ISD::VSHLI: return "X86ISD::VSHLI";
16522 case X86ISD::VSRLI: return "X86ISD::VSRLI";
16523 case X86ISD::VSRAI: return "X86ISD::VSRAI";
16524 case X86ISD::CMPP: return "X86ISD::CMPP";
16525 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
16526 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
16527 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
16528 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
16529 case X86ISD::ADD: return "X86ISD::ADD";
16530 case X86ISD::SUB: return "X86ISD::SUB";
16531 case X86ISD::ADC: return "X86ISD::ADC";
16532 case X86ISD::SBB: return "X86ISD::SBB";
16533 case X86ISD::SMUL: return "X86ISD::SMUL";
16534 case X86ISD::UMUL: return "X86ISD::UMUL";
16535 case X86ISD::INC: return "X86ISD::INC";
16536 case X86ISD::DEC: return "X86ISD::DEC";
16537 case X86ISD::OR: return "X86ISD::OR";
16538 case X86ISD::XOR: return "X86ISD::XOR";
16539 case X86ISD::AND: return "X86ISD::AND";
16540 case X86ISD::BEXTR: return "X86ISD::BEXTR";
16541 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
16542 case X86ISD::PTEST: return "X86ISD::PTEST";
16543 case X86ISD::TESTP: return "X86ISD::TESTP";
16544 case X86ISD::TESTM: return "X86ISD::TESTM";
16545 case X86ISD::TESTNM: return "X86ISD::TESTNM";
16546 case X86ISD::KORTEST: return "X86ISD::KORTEST";
16547 case X86ISD::PACKSS: return "X86ISD::PACKSS";
16548 case X86ISD::PACKUS: return "X86ISD::PACKUS";
16549 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
16550 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
16551 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
16552 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
16553 case X86ISD::SHUFP: return "X86ISD::SHUFP";
16554 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
16555 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
16556 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
16557 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
16558 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
16559 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
16560 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
16561 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
16562 case X86ISD::MOVSD: return "X86ISD::MOVSD";
16563 case X86ISD::MOVSS: return "X86ISD::MOVSS";
16564 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
16565 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
16566 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
16567 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
16568 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
16569 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
16570 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
16571 case X86ISD::VPERMV: return "X86ISD::VPERMV";
16572 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
16573 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
16574 case X86ISD::VPERMI: return "X86ISD::VPERMI";
16575 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
16576 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
16577 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16578 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
16579 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
16580 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
16581 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
16582 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
16583 case X86ISD::SAHF: return "X86ISD::SAHF";
16584 case X86ISD::RDRAND: return "X86ISD::RDRAND";
16585 case X86ISD::RDSEED: return "X86ISD::RDSEED";
16586 case X86ISD::FMADD: return "X86ISD::FMADD";
16587 case X86ISD::FMSUB: return "X86ISD::FMSUB";
16588 case X86ISD::FNMADD: return "X86ISD::FNMADD";
16589 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
16590 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
16591 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
16592 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
16593 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
16594 case X86ISD::XTEST: return "X86ISD::XTEST";
16598 // isLegalAddressingMode - Return true if the addressing mode represented
16599 // by AM is legal for this target, for a load/store of the specified type.
16600 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16602 // X86 supports extremely general addressing modes.
16603 CodeModel::Model M = getTargetMachine().getCodeModel();
16604 Reloc::Model R = getTargetMachine().getRelocationModel();
16606 // X86 allows a sign-extended 32-bit immediate field as a displacement.
16607 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16612 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16614 // If a reference to this global requires an extra load, we can't fold it.
16615 if (isGlobalStubReference(GVFlags))
16618 // If BaseGV requires a register for the PIC base, we cannot also have a
16619 // BaseReg specified.
16620 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16623 // If lower 4G is not available, then we must use rip-relative addressing.
16624 if ((M != CodeModel::Small || R != Reloc::Static) &&
16625 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16629 switch (AM.Scale) {
16635 // These scales always work.
16640 // These scales are formed with basereg+scalereg. Only accept if there is
16645 default: // Other stuff never works.
16652 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16653 unsigned Bits = Ty->getScalarSizeInBits();
16655 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16656 // particularly cheaper than those without.
16660 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16661 // variable shifts just as cheap as scalar ones.
16662 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16665 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16666 // fully general vector.
16670 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16671 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16673 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16674 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16675 return NumBits1 > NumBits2;
16678 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16679 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16682 if (!isTypeLegal(EVT::getEVT(Ty1)))
16685 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16687 // Assuming the caller doesn't have a zeroext or signext return parameter,
16688 // truncation all the way down to i1 is valid.
16692 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16693 return isInt<32>(Imm);
16696 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16697 // Can also use sub to handle negated immediates.
16698 return isInt<32>(Imm);
16701 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16702 if (!VT1.isInteger() || !VT2.isInteger())
16704 unsigned NumBits1 = VT1.getSizeInBits();
16705 unsigned NumBits2 = VT2.getSizeInBits();
16706 return NumBits1 > NumBits2;
16709 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16710 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16711 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16714 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16715 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16716 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16719 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16720 EVT VT1 = Val.getValueType();
16721 if (isZExtFree(VT1, VT2))
16724 if (Val.getOpcode() != ISD::LOAD)
16727 if (!VT1.isSimple() || !VT1.isInteger() ||
16728 !VT2.isSimple() || !VT2.isInteger())
16731 switch (VT1.getSimpleVT().SimpleTy) {
16736 // X86 has 8, 16, and 32-bit zero-extending loads.
16744 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16745 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16748 VT = VT.getScalarType();
16750 if (!VT.isSimple())
16753 switch (VT.getSimpleVT().SimpleTy) {
16764 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16765 // i16 instructions are longer (0x66 prefix) and potentially slower.
16766 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16769 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16770 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16771 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16772 /// are assumed to be legal.
16774 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16776 if (!VT.isSimple())
16779 MVT SVT = VT.getSimpleVT();
16781 // Very little shuffling can be done for 64-bit vectors right now.
16782 if (VT.getSizeInBits() == 64)
16785 // If this is a single-input shuffle with no 128 bit lane crossings we can
16786 // lower it into pshufb.
16787 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16788 (SVT.is256BitVector() && Subtarget->hasInt256())) {
16789 bool isLegal = true;
16790 for (unsigned I = 0, E = M.size(); I != E; ++I) {
16791 if (M[I] >= (int)SVT.getVectorNumElements() ||
16792 ShuffleCrosses128bitLane(SVT, I, M[I])) {
16801 // FIXME: blends, shifts.
16802 return (SVT.getVectorNumElements() == 2 ||
16803 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16804 isMOVLMask(M, SVT) ||
16805 isSHUFPMask(M, SVT) ||
16806 isPSHUFDMask(M, SVT) ||
16807 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16808 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16809 isPALIGNRMask(M, SVT, Subtarget) ||
16810 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16811 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16812 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16813 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16814 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16818 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16820 if (!VT.isSimple())
16823 MVT SVT = VT.getSimpleVT();
16824 unsigned NumElts = SVT.getVectorNumElements();
16825 // FIXME: This collection of masks seems suspect.
16828 if (NumElts == 4 && SVT.is128BitVector()) {
16829 return (isMOVLMask(Mask, SVT) ||
16830 isCommutedMOVLMask(Mask, SVT, true) ||
16831 isSHUFPMask(Mask, SVT) ||
16832 isSHUFPMask(Mask, SVT, /* Commuted */ true));
16837 //===----------------------------------------------------------------------===//
16838 // X86 Scheduler Hooks
16839 //===----------------------------------------------------------------------===//
16841 /// Utility function to emit xbegin specifying the start of an RTM region.
16842 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16843 const TargetInstrInfo *TII) {
16844 DebugLoc DL = MI->getDebugLoc();
16846 const BasicBlock *BB = MBB->getBasicBlock();
16847 MachineFunction::iterator I = MBB;
16850 // For the v = xbegin(), we generate
16861 MachineBasicBlock *thisMBB = MBB;
16862 MachineFunction *MF = MBB->getParent();
16863 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16864 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16865 MF->insert(I, mainMBB);
16866 MF->insert(I, sinkMBB);
16868 // Transfer the remainder of BB and its successor edges to sinkMBB.
16869 sinkMBB->splice(sinkMBB->begin(), MBB,
16870 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16871 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16875 // # fallthrough to mainMBB
16876 // # abortion to sinkMBB
16877 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16878 thisMBB->addSuccessor(mainMBB);
16879 thisMBB->addSuccessor(sinkMBB);
16883 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16884 mainMBB->addSuccessor(sinkMBB);
16887 // EAX is live into the sinkMBB
16888 sinkMBB->addLiveIn(X86::EAX);
16889 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16890 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16893 MI->eraseFromParent();
16897 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16898 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16899 // in the .td file.
16900 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16901 const TargetInstrInfo *TII) {
16903 switch (MI->getOpcode()) {
16904 default: llvm_unreachable("illegal opcode!");
16905 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
16906 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16907 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
16908 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16909 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
16910 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16911 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
16912 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16915 DebugLoc dl = MI->getDebugLoc();
16916 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16918 unsigned NumArgs = MI->getNumOperands();
16919 for (unsigned i = 1; i < NumArgs; ++i) {
16920 MachineOperand &Op = MI->getOperand(i);
16921 if (!(Op.isReg() && Op.isImplicit()))
16922 MIB.addOperand(Op);
16924 if (MI->hasOneMemOperand())
16925 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16927 BuildMI(*BB, MI, dl,
16928 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16929 .addReg(X86::XMM0);
16931 MI->eraseFromParent();
16935 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16936 // defs in an instruction pattern
16937 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16938 const TargetInstrInfo *TII) {
16940 switch (MI->getOpcode()) {
16941 default: llvm_unreachable("illegal opcode!");
16942 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16943 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16944 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16945 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16946 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16947 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16948 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16949 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16952 DebugLoc dl = MI->getDebugLoc();
16953 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16955 unsigned NumArgs = MI->getNumOperands(); // remove the results
16956 for (unsigned i = 1; i < NumArgs; ++i) {
16957 MachineOperand &Op = MI->getOperand(i);
16958 if (!(Op.isReg() && Op.isImplicit()))
16959 MIB.addOperand(Op);
16961 if (MI->hasOneMemOperand())
16962 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16964 BuildMI(*BB, MI, dl,
16965 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16968 MI->eraseFromParent();
16972 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16973 const TargetInstrInfo *TII,
16974 const X86Subtarget* Subtarget) {
16975 DebugLoc dl = MI->getDebugLoc();
16977 // Address into RAX/EAX, other two args into ECX, EDX.
16978 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16979 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16980 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16981 for (int i = 0; i < X86::AddrNumOperands; ++i)
16982 MIB.addOperand(MI->getOperand(i));
16984 unsigned ValOps = X86::AddrNumOperands;
16985 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16986 .addReg(MI->getOperand(ValOps).getReg());
16987 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16988 .addReg(MI->getOperand(ValOps+1).getReg());
16990 // The instruction doesn't actually take any operands though.
16991 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16993 MI->eraseFromParent(); // The pseudo is gone now.
16997 MachineBasicBlock *
16998 X86TargetLowering::EmitVAARG64WithCustomInserter(
17000 MachineBasicBlock *MBB) const {
17001 // Emit va_arg instruction on X86-64.
17003 // Operands to this pseudo-instruction:
17004 // 0 ) Output : destination address (reg)
17005 // 1-5) Input : va_list address (addr, i64mem)
17006 // 6 ) ArgSize : Size (in bytes) of vararg type
17007 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17008 // 8 ) Align : Alignment of type
17009 // 9 ) EFLAGS (implicit-def)
17011 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17012 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17014 unsigned DestReg = MI->getOperand(0).getReg();
17015 MachineOperand &Base = MI->getOperand(1);
17016 MachineOperand &Scale = MI->getOperand(2);
17017 MachineOperand &Index = MI->getOperand(3);
17018 MachineOperand &Disp = MI->getOperand(4);
17019 MachineOperand &Segment = MI->getOperand(5);
17020 unsigned ArgSize = MI->getOperand(6).getImm();
17021 unsigned ArgMode = MI->getOperand(7).getImm();
17022 unsigned Align = MI->getOperand(8).getImm();
17024 // Memory Reference
17025 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17026 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17027 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17029 // Machine Information
17030 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17031 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17032 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17033 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17034 DebugLoc DL = MI->getDebugLoc();
17036 // struct va_list {
17039 // i64 overflow_area (address)
17040 // i64 reg_save_area (address)
17042 // sizeof(va_list) = 24
17043 // alignment(va_list) = 8
17045 unsigned TotalNumIntRegs = 6;
17046 unsigned TotalNumXMMRegs = 8;
17047 bool UseGPOffset = (ArgMode == 1);
17048 bool UseFPOffset = (ArgMode == 2);
17049 unsigned MaxOffset = TotalNumIntRegs * 8 +
17050 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17052 /* Align ArgSize to a multiple of 8 */
17053 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17054 bool NeedsAlign = (Align > 8);
17056 MachineBasicBlock *thisMBB = MBB;
17057 MachineBasicBlock *overflowMBB;
17058 MachineBasicBlock *offsetMBB;
17059 MachineBasicBlock *endMBB;
17061 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17062 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17063 unsigned OffsetReg = 0;
17065 if (!UseGPOffset && !UseFPOffset) {
17066 // If we only pull from the overflow region, we don't create a branch.
17067 // We don't need to alter control flow.
17068 OffsetDestReg = 0; // unused
17069 OverflowDestReg = DestReg;
17071 offsetMBB = nullptr;
17072 overflowMBB = thisMBB;
17075 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17076 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17077 // If not, pull from overflow_area. (branch to overflowMBB)
17082 // offsetMBB overflowMBB
17087 // Registers for the PHI in endMBB
17088 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17089 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17091 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17092 MachineFunction *MF = MBB->getParent();
17093 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17094 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17095 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17097 MachineFunction::iterator MBBIter = MBB;
17100 // Insert the new basic blocks
17101 MF->insert(MBBIter, offsetMBB);
17102 MF->insert(MBBIter, overflowMBB);
17103 MF->insert(MBBIter, endMBB);
17105 // Transfer the remainder of MBB and its successor edges to endMBB.
17106 endMBB->splice(endMBB->begin(), thisMBB,
17107 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17108 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17110 // Make offsetMBB and overflowMBB successors of thisMBB
17111 thisMBB->addSuccessor(offsetMBB);
17112 thisMBB->addSuccessor(overflowMBB);
17114 // endMBB is a successor of both offsetMBB and overflowMBB
17115 offsetMBB->addSuccessor(endMBB);
17116 overflowMBB->addSuccessor(endMBB);
17118 // Load the offset value into a register
17119 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17120 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17124 .addDisp(Disp, UseFPOffset ? 4 : 0)
17125 .addOperand(Segment)
17126 .setMemRefs(MMOBegin, MMOEnd);
17128 // Check if there is enough room left to pull this argument.
17129 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17131 .addImm(MaxOffset + 8 - ArgSizeA8);
17133 // Branch to "overflowMBB" if offset >= max
17134 // Fall through to "offsetMBB" otherwise
17135 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17136 .addMBB(overflowMBB);
17139 // In offsetMBB, emit code to use the reg_save_area.
17141 assert(OffsetReg != 0);
17143 // Read the reg_save_area address.
17144 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17145 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17150 .addOperand(Segment)
17151 .setMemRefs(MMOBegin, MMOEnd);
17153 // Zero-extend the offset
17154 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17155 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17158 .addImm(X86::sub_32bit);
17160 // Add the offset to the reg_save_area to get the final address.
17161 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17162 .addReg(OffsetReg64)
17163 .addReg(RegSaveReg);
17165 // Compute the offset for the next argument
17166 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17167 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17169 .addImm(UseFPOffset ? 16 : 8);
17171 // Store it back into the va_list.
17172 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17176 .addDisp(Disp, UseFPOffset ? 4 : 0)
17177 .addOperand(Segment)
17178 .addReg(NextOffsetReg)
17179 .setMemRefs(MMOBegin, MMOEnd);
17182 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17187 // Emit code to use overflow area
17190 // Load the overflow_area address into a register.
17191 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17192 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17197 .addOperand(Segment)
17198 .setMemRefs(MMOBegin, MMOEnd);
17200 // If we need to align it, do so. Otherwise, just copy the address
17201 // to OverflowDestReg.
17203 // Align the overflow address
17204 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17205 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17207 // aligned_addr = (addr + (align-1)) & ~(align-1)
17208 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17209 .addReg(OverflowAddrReg)
17212 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17214 .addImm(~(uint64_t)(Align-1));
17216 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17217 .addReg(OverflowAddrReg);
17220 // Compute the next overflow address after this argument.
17221 // (the overflow address should be kept 8-byte aligned)
17222 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17223 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17224 .addReg(OverflowDestReg)
17225 .addImm(ArgSizeA8);
17227 // Store the new overflow address.
17228 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17233 .addOperand(Segment)
17234 .addReg(NextAddrReg)
17235 .setMemRefs(MMOBegin, MMOEnd);
17237 // If we branched, emit the PHI to the front of endMBB.
17239 BuildMI(*endMBB, endMBB->begin(), DL,
17240 TII->get(X86::PHI), DestReg)
17241 .addReg(OffsetDestReg).addMBB(offsetMBB)
17242 .addReg(OverflowDestReg).addMBB(overflowMBB);
17245 // Erase the pseudo instruction
17246 MI->eraseFromParent();
17251 MachineBasicBlock *
17252 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17254 MachineBasicBlock *MBB) const {
17255 // Emit code to save XMM registers to the stack. The ABI says that the
17256 // number of registers to save is given in %al, so it's theoretically
17257 // possible to do an indirect jump trick to avoid saving all of them,
17258 // however this code takes a simpler approach and just executes all
17259 // of the stores if %al is non-zero. It's less code, and it's probably
17260 // easier on the hardware branch predictor, and stores aren't all that
17261 // expensive anyway.
17263 // Create the new basic blocks. One block contains all the XMM stores,
17264 // and one block is the final destination regardless of whether any
17265 // stores were performed.
17266 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17267 MachineFunction *F = MBB->getParent();
17268 MachineFunction::iterator MBBIter = MBB;
17270 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17271 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17272 F->insert(MBBIter, XMMSaveMBB);
17273 F->insert(MBBIter, EndMBB);
17275 // Transfer the remainder of MBB and its successor edges to EndMBB.
17276 EndMBB->splice(EndMBB->begin(), MBB,
17277 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17278 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17280 // The original block will now fall through to the XMM save block.
17281 MBB->addSuccessor(XMMSaveMBB);
17282 // The XMMSaveMBB will fall through to the end block.
17283 XMMSaveMBB->addSuccessor(EndMBB);
17285 // Now add the instructions.
17286 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17287 DebugLoc DL = MI->getDebugLoc();
17289 unsigned CountReg = MI->getOperand(0).getReg();
17290 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17291 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17293 if (!Subtarget->isTargetWin64()) {
17294 // If %al is 0, branch around the XMM save block.
17295 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17296 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17297 MBB->addSuccessor(EndMBB);
17300 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17301 // that was just emitted, but clearly shouldn't be "saved".
17302 assert((MI->getNumOperands() <= 3 ||
17303 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17304 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17305 && "Expected last argument to be EFLAGS");
17306 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17307 // In the XMM save block, save all the XMM argument registers.
17308 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17309 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17310 MachineMemOperand *MMO =
17311 F->getMachineMemOperand(
17312 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17313 MachineMemOperand::MOStore,
17314 /*Size=*/16, /*Align=*/16);
17315 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17316 .addFrameIndex(RegSaveFrameIndex)
17317 .addImm(/*Scale=*/1)
17318 .addReg(/*IndexReg=*/0)
17319 .addImm(/*Disp=*/Offset)
17320 .addReg(/*Segment=*/0)
17321 .addReg(MI->getOperand(i).getReg())
17322 .addMemOperand(MMO);
17325 MI->eraseFromParent(); // The pseudo instruction is gone now.
17330 // The EFLAGS operand of SelectItr might be missing a kill marker
17331 // because there were multiple uses of EFLAGS, and ISel didn't know
17332 // which to mark. Figure out whether SelectItr should have had a
17333 // kill marker, and set it if it should. Returns the correct kill
17335 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17336 MachineBasicBlock* BB,
17337 const TargetRegisterInfo* TRI) {
17338 // Scan forward through BB for a use/def of EFLAGS.
17339 MachineBasicBlock::iterator miI(std::next(SelectItr));
17340 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17341 const MachineInstr& mi = *miI;
17342 if (mi.readsRegister(X86::EFLAGS))
17344 if (mi.definesRegister(X86::EFLAGS))
17345 break; // Should have kill-flag - update below.
17348 // If we hit the end of the block, check whether EFLAGS is live into a
17350 if (miI == BB->end()) {
17351 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17352 sEnd = BB->succ_end();
17353 sItr != sEnd; ++sItr) {
17354 MachineBasicBlock* succ = *sItr;
17355 if (succ->isLiveIn(X86::EFLAGS))
17360 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17361 // out. SelectMI should have a kill flag on EFLAGS.
17362 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17366 MachineBasicBlock *
17367 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17368 MachineBasicBlock *BB) const {
17369 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17370 DebugLoc DL = MI->getDebugLoc();
17372 // To "insert" a SELECT_CC instruction, we actually have to insert the
17373 // diamond control-flow pattern. The incoming instruction knows the
17374 // destination vreg to set, the condition code register to branch on, the
17375 // true/false values to select between, and a branch opcode to use.
17376 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17377 MachineFunction::iterator It = BB;
17383 // cmpTY ccX, r1, r2
17385 // fallthrough --> copy0MBB
17386 MachineBasicBlock *thisMBB = BB;
17387 MachineFunction *F = BB->getParent();
17388 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17389 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17390 F->insert(It, copy0MBB);
17391 F->insert(It, sinkMBB);
17393 // If the EFLAGS register isn't dead in the terminator, then claim that it's
17394 // live into the sink and copy blocks.
17395 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17396 if (!MI->killsRegister(X86::EFLAGS) &&
17397 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17398 copy0MBB->addLiveIn(X86::EFLAGS);
17399 sinkMBB->addLiveIn(X86::EFLAGS);
17402 // Transfer the remainder of BB and its successor edges to sinkMBB.
17403 sinkMBB->splice(sinkMBB->begin(), BB,
17404 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17405 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17407 // Add the true and fallthrough blocks as its successors.
17408 BB->addSuccessor(copy0MBB);
17409 BB->addSuccessor(sinkMBB);
17411 // Create the conditional branch instruction.
17413 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17414 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17417 // %FalseValue = ...
17418 // # fallthrough to sinkMBB
17419 copy0MBB->addSuccessor(sinkMBB);
17422 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17424 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17425 TII->get(X86::PHI), MI->getOperand(0).getReg())
17426 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17427 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17429 MI->eraseFromParent(); // The pseudo instruction is gone now.
17433 MachineBasicBlock *
17434 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17435 bool Is64Bit) const {
17436 MachineFunction *MF = BB->getParent();
17437 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17438 DebugLoc DL = MI->getDebugLoc();
17439 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17441 assert(MF->shouldSplitStack());
17443 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17444 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17447 // ... [Till the alloca]
17448 // If stacklet is not large enough, jump to mallocMBB
17451 // Allocate by subtracting from RSP
17452 // Jump to continueMBB
17455 // Allocate by call to runtime
17459 // [rest of original BB]
17462 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17463 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17464 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17466 MachineRegisterInfo &MRI = MF->getRegInfo();
17467 const TargetRegisterClass *AddrRegClass =
17468 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17470 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17471 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17472 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17473 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17474 sizeVReg = MI->getOperand(1).getReg(),
17475 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17477 MachineFunction::iterator MBBIter = BB;
17480 MF->insert(MBBIter, bumpMBB);
17481 MF->insert(MBBIter, mallocMBB);
17482 MF->insert(MBBIter, continueMBB);
17484 continueMBB->splice(continueMBB->begin(), BB,
17485 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17486 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17488 // Add code to the main basic block to check if the stack limit has been hit,
17489 // and if so, jump to mallocMBB otherwise to bumpMBB.
17490 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17491 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17492 .addReg(tmpSPVReg).addReg(sizeVReg);
17493 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17494 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17495 .addReg(SPLimitVReg);
17496 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17498 // bumpMBB simply decreases the stack pointer, since we know the current
17499 // stacklet has enough space.
17500 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17501 .addReg(SPLimitVReg);
17502 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17503 .addReg(SPLimitVReg);
17504 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17506 // Calls into a routine in libgcc to allocate more space from the heap.
17507 const uint32_t *RegMask =
17508 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17510 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17512 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17513 .addExternalSymbol("__morestack_allocate_stack_space")
17514 .addRegMask(RegMask)
17515 .addReg(X86::RDI, RegState::Implicit)
17516 .addReg(X86::RAX, RegState::ImplicitDefine);
17518 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17520 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17521 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17522 .addExternalSymbol("__morestack_allocate_stack_space")
17523 .addRegMask(RegMask)
17524 .addReg(X86::EAX, RegState::ImplicitDefine);
17528 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17531 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17532 .addReg(Is64Bit ? X86::RAX : X86::EAX);
17533 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17535 // Set up the CFG correctly.
17536 BB->addSuccessor(bumpMBB);
17537 BB->addSuccessor(mallocMBB);
17538 mallocMBB->addSuccessor(continueMBB);
17539 bumpMBB->addSuccessor(continueMBB);
17541 // Take care of the PHI nodes.
17542 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17543 MI->getOperand(0).getReg())
17544 .addReg(mallocPtrVReg).addMBB(mallocMBB)
17545 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17547 // Delete the original pseudo instruction.
17548 MI->eraseFromParent();
17551 return continueMBB;
17554 MachineBasicBlock *
17555 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17556 MachineBasicBlock *BB) const {
17557 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17558 DebugLoc DL = MI->getDebugLoc();
17560 assert(!Subtarget->isTargetMacho());
17562 // The lowering is pretty easy: we're just emitting the call to _alloca. The
17563 // non-trivial part is impdef of ESP.
17565 if (Subtarget->isTargetWin64()) {
17566 if (Subtarget->isTargetCygMing()) {
17567 // ___chkstk(Mingw64):
17568 // Clobbers R10, R11, RAX and EFLAGS.
17570 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17571 .addExternalSymbol("___chkstk")
17572 .addReg(X86::RAX, RegState::Implicit)
17573 .addReg(X86::RSP, RegState::Implicit)
17574 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17575 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17576 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17578 // __chkstk(MSVCRT): does not update stack pointer.
17579 // Clobbers R10, R11 and EFLAGS.
17580 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17581 .addExternalSymbol("__chkstk")
17582 .addReg(X86::RAX, RegState::Implicit)
17583 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17584 // RAX has the offset to be subtracted from RSP.
17585 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17590 const char *StackProbeSymbol =
17591 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17593 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17594 .addExternalSymbol(StackProbeSymbol)
17595 .addReg(X86::EAX, RegState::Implicit)
17596 .addReg(X86::ESP, RegState::Implicit)
17597 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17598 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17599 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17602 MI->eraseFromParent(); // The pseudo instruction is gone now.
17606 MachineBasicBlock *
17607 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17608 MachineBasicBlock *BB) const {
17609 // This is pretty easy. We're taking the value that we received from
17610 // our load from the relocation, sticking it in either RDI (x86-64)
17611 // or EAX and doing an indirect call. The return value will then
17612 // be in the normal return register.
17613 MachineFunction *F = BB->getParent();
17614 const X86InstrInfo *TII
17615 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17616 DebugLoc DL = MI->getDebugLoc();
17618 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17619 assert(MI->getOperand(3).isGlobal() && "This should be a global");
17621 // Get a register mask for the lowered call.
17622 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17623 // proper register mask.
17624 const uint32_t *RegMask =
17625 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17626 if (Subtarget->is64Bit()) {
17627 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17628 TII->get(X86::MOV64rm), X86::RDI)
17630 .addImm(0).addReg(0)
17631 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17632 MI->getOperand(3).getTargetFlags())
17634 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17635 addDirectMem(MIB, X86::RDI);
17636 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17637 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17638 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17639 TII->get(X86::MOV32rm), X86::EAX)
17641 .addImm(0).addReg(0)
17642 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17643 MI->getOperand(3).getTargetFlags())
17645 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17646 addDirectMem(MIB, X86::EAX);
17647 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17649 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17650 TII->get(X86::MOV32rm), X86::EAX)
17651 .addReg(TII->getGlobalBaseReg(F))
17652 .addImm(0).addReg(0)
17653 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17654 MI->getOperand(3).getTargetFlags())
17656 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17657 addDirectMem(MIB, X86::EAX);
17658 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17661 MI->eraseFromParent(); // The pseudo instruction is gone now.
17665 MachineBasicBlock *
17666 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17667 MachineBasicBlock *MBB) const {
17668 DebugLoc DL = MI->getDebugLoc();
17669 MachineFunction *MF = MBB->getParent();
17670 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17671 MachineRegisterInfo &MRI = MF->getRegInfo();
17673 const BasicBlock *BB = MBB->getBasicBlock();
17674 MachineFunction::iterator I = MBB;
17677 // Memory Reference
17678 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17679 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17682 unsigned MemOpndSlot = 0;
17684 unsigned CurOp = 0;
17686 DstReg = MI->getOperand(CurOp++).getReg();
17687 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17688 assert(RC->hasType(MVT::i32) && "Invalid destination!");
17689 unsigned mainDstReg = MRI.createVirtualRegister(RC);
17690 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17692 MemOpndSlot = CurOp;
17694 MVT PVT = getPointerTy();
17695 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17696 "Invalid Pointer Size!");
17698 // For v = setjmp(buf), we generate
17701 // buf[LabelOffset] = restoreMBB
17702 // SjLjSetup restoreMBB
17708 // v = phi(main, restore)
17713 MachineBasicBlock *thisMBB = MBB;
17714 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17715 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17716 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17717 MF->insert(I, mainMBB);
17718 MF->insert(I, sinkMBB);
17719 MF->push_back(restoreMBB);
17721 MachineInstrBuilder MIB;
17723 // Transfer the remainder of BB and its successor edges to sinkMBB.
17724 sinkMBB->splice(sinkMBB->begin(), MBB,
17725 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17726 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17729 unsigned PtrStoreOpc = 0;
17730 unsigned LabelReg = 0;
17731 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17732 Reloc::Model RM = MF->getTarget().getRelocationModel();
17733 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17734 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17736 // Prepare IP either in reg or imm.
17737 if (!UseImmLabel) {
17738 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17739 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17740 LabelReg = MRI.createVirtualRegister(PtrRC);
17741 if (Subtarget->is64Bit()) {
17742 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17746 .addMBB(restoreMBB)
17749 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17750 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17751 .addReg(XII->getGlobalBaseReg(MF))
17754 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17758 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17760 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17761 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17762 if (i == X86::AddrDisp)
17763 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17765 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17768 MIB.addReg(LabelReg);
17770 MIB.addMBB(restoreMBB);
17771 MIB.setMemRefs(MMOBegin, MMOEnd);
17773 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17774 .addMBB(restoreMBB);
17776 const X86RegisterInfo *RegInfo =
17777 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17778 MIB.addRegMask(RegInfo->getNoPreservedMask());
17779 thisMBB->addSuccessor(mainMBB);
17780 thisMBB->addSuccessor(restoreMBB);
17784 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17785 mainMBB->addSuccessor(sinkMBB);
17788 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17789 TII->get(X86::PHI), DstReg)
17790 .addReg(mainDstReg).addMBB(mainMBB)
17791 .addReg(restoreDstReg).addMBB(restoreMBB);
17794 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17795 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17796 restoreMBB->addSuccessor(sinkMBB);
17798 MI->eraseFromParent();
17802 MachineBasicBlock *
17803 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17804 MachineBasicBlock *MBB) const {
17805 DebugLoc DL = MI->getDebugLoc();
17806 MachineFunction *MF = MBB->getParent();
17807 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17808 MachineRegisterInfo &MRI = MF->getRegInfo();
17810 // Memory Reference
17811 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17812 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17814 MVT PVT = getPointerTy();
17815 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17816 "Invalid Pointer Size!");
17818 const TargetRegisterClass *RC =
17819 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17820 unsigned Tmp = MRI.createVirtualRegister(RC);
17821 // Since FP is only updated here but NOT referenced, it's treated as GPR.
17822 const X86RegisterInfo *RegInfo =
17823 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17824 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17825 unsigned SP = RegInfo->getStackRegister();
17827 MachineInstrBuilder MIB;
17829 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17830 const int64_t SPOffset = 2 * PVT.getStoreSize();
17832 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17833 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17836 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17837 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17838 MIB.addOperand(MI->getOperand(i));
17839 MIB.setMemRefs(MMOBegin, MMOEnd);
17841 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17842 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17843 if (i == X86::AddrDisp)
17844 MIB.addDisp(MI->getOperand(i), LabelOffset);
17846 MIB.addOperand(MI->getOperand(i));
17848 MIB.setMemRefs(MMOBegin, MMOEnd);
17850 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17851 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17852 if (i == X86::AddrDisp)
17853 MIB.addDisp(MI->getOperand(i), SPOffset);
17855 MIB.addOperand(MI->getOperand(i));
17857 MIB.setMemRefs(MMOBegin, MMOEnd);
17859 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17861 MI->eraseFromParent();
17865 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17866 // accumulator loops. Writing back to the accumulator allows the coalescer
17867 // to remove extra copies in the loop.
17868 MachineBasicBlock *
17869 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17870 MachineBasicBlock *MBB) const {
17871 MachineOperand &AddendOp = MI->getOperand(3);
17873 // Bail out early if the addend isn't a register - we can't switch these.
17874 if (!AddendOp.isReg())
17877 MachineFunction &MF = *MBB->getParent();
17878 MachineRegisterInfo &MRI = MF.getRegInfo();
17880 // Check whether the addend is defined by a PHI:
17881 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17882 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17883 if (!AddendDef.isPHI())
17886 // Look for the following pattern:
17888 // %addend = phi [%entry, 0], [%loop, %result]
17890 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17894 // %addend = phi [%entry, 0], [%loop, %result]
17896 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17898 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17899 assert(AddendDef.getOperand(i).isReg());
17900 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17901 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17902 if (&PHISrcInst == MI) {
17903 // Found a matching instruction.
17904 unsigned NewFMAOpc = 0;
17905 switch (MI->getOpcode()) {
17906 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17907 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17908 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17909 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17910 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17911 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17912 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17913 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17914 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17915 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17916 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17917 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17918 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17919 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17920 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17921 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17922 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17923 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17924 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17925 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17926 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17927 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17928 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17929 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17930 default: llvm_unreachable("Unrecognized FMA variant.");
17933 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17934 MachineInstrBuilder MIB =
17935 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17936 .addOperand(MI->getOperand(0))
17937 .addOperand(MI->getOperand(3))
17938 .addOperand(MI->getOperand(2))
17939 .addOperand(MI->getOperand(1));
17940 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17941 MI->eraseFromParent();
17948 MachineBasicBlock *
17949 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17950 MachineBasicBlock *BB) const {
17951 switch (MI->getOpcode()) {
17952 default: llvm_unreachable("Unexpected instr type to insert");
17953 case X86::TAILJMPd64:
17954 case X86::TAILJMPr64:
17955 case X86::TAILJMPm64:
17956 llvm_unreachable("TAILJMP64 would not be touched here.");
17957 case X86::TCRETURNdi64:
17958 case X86::TCRETURNri64:
17959 case X86::TCRETURNmi64:
17961 case X86::WIN_ALLOCA:
17962 return EmitLoweredWinAlloca(MI, BB);
17963 case X86::SEG_ALLOCA_32:
17964 return EmitLoweredSegAlloca(MI, BB, false);
17965 case X86::SEG_ALLOCA_64:
17966 return EmitLoweredSegAlloca(MI, BB, true);
17967 case X86::TLSCall_32:
17968 case X86::TLSCall_64:
17969 return EmitLoweredTLSCall(MI, BB);
17970 case X86::CMOV_GR8:
17971 case X86::CMOV_FR32:
17972 case X86::CMOV_FR64:
17973 case X86::CMOV_V4F32:
17974 case X86::CMOV_V2F64:
17975 case X86::CMOV_V2I64:
17976 case X86::CMOV_V8F32:
17977 case X86::CMOV_V4F64:
17978 case X86::CMOV_V4I64:
17979 case X86::CMOV_V16F32:
17980 case X86::CMOV_V8F64:
17981 case X86::CMOV_V8I64:
17982 case X86::CMOV_GR16:
17983 case X86::CMOV_GR32:
17984 case X86::CMOV_RFP32:
17985 case X86::CMOV_RFP64:
17986 case X86::CMOV_RFP80:
17987 return EmitLoweredSelect(MI, BB);
17989 case X86::FP32_TO_INT16_IN_MEM:
17990 case X86::FP32_TO_INT32_IN_MEM:
17991 case X86::FP32_TO_INT64_IN_MEM:
17992 case X86::FP64_TO_INT16_IN_MEM:
17993 case X86::FP64_TO_INT32_IN_MEM:
17994 case X86::FP64_TO_INT64_IN_MEM:
17995 case X86::FP80_TO_INT16_IN_MEM:
17996 case X86::FP80_TO_INT32_IN_MEM:
17997 case X86::FP80_TO_INT64_IN_MEM: {
17998 MachineFunction *F = BB->getParent();
17999 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18000 DebugLoc DL = MI->getDebugLoc();
18002 // Change the floating point control register to use "round towards zero"
18003 // mode when truncating to an integer value.
18004 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18005 addFrameReference(BuildMI(*BB, MI, DL,
18006 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18008 // Load the old value of the high byte of the control word...
18010 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18011 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18014 // Set the high part to be round to zero...
18015 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18018 // Reload the modified control word now...
18019 addFrameReference(BuildMI(*BB, MI, DL,
18020 TII->get(X86::FLDCW16m)), CWFrameIdx);
18022 // Restore the memory image of control word to original value
18023 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18026 // Get the X86 opcode to use.
18028 switch (MI->getOpcode()) {
18029 default: llvm_unreachable("illegal opcode!");
18030 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18031 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18032 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18033 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18034 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18035 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18036 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18037 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18038 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18042 MachineOperand &Op = MI->getOperand(0);
18044 AM.BaseType = X86AddressMode::RegBase;
18045 AM.Base.Reg = Op.getReg();
18047 AM.BaseType = X86AddressMode::FrameIndexBase;
18048 AM.Base.FrameIndex = Op.getIndex();
18050 Op = MI->getOperand(1);
18052 AM.Scale = Op.getImm();
18053 Op = MI->getOperand(2);
18055 AM.IndexReg = Op.getImm();
18056 Op = MI->getOperand(3);
18057 if (Op.isGlobal()) {
18058 AM.GV = Op.getGlobal();
18060 AM.Disp = Op.getImm();
18062 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18063 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18065 // Reload the original control word now.
18066 addFrameReference(BuildMI(*BB, MI, DL,
18067 TII->get(X86::FLDCW16m)), CWFrameIdx);
18069 MI->eraseFromParent(); // The pseudo instruction is gone now.
18072 // String/text processing lowering.
18073 case X86::PCMPISTRM128REG:
18074 case X86::VPCMPISTRM128REG:
18075 case X86::PCMPISTRM128MEM:
18076 case X86::VPCMPISTRM128MEM:
18077 case X86::PCMPESTRM128REG:
18078 case X86::VPCMPESTRM128REG:
18079 case X86::PCMPESTRM128MEM:
18080 case X86::VPCMPESTRM128MEM:
18081 assert(Subtarget->hasSSE42() &&
18082 "Target must have SSE4.2 or AVX features enabled");
18083 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18085 // String/text processing lowering.
18086 case X86::PCMPISTRIREG:
18087 case X86::VPCMPISTRIREG:
18088 case X86::PCMPISTRIMEM:
18089 case X86::VPCMPISTRIMEM:
18090 case X86::PCMPESTRIREG:
18091 case X86::VPCMPESTRIREG:
18092 case X86::PCMPESTRIMEM:
18093 case X86::VPCMPESTRIMEM:
18094 assert(Subtarget->hasSSE42() &&
18095 "Target must have SSE4.2 or AVX features enabled");
18096 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18098 // Thread synchronization.
18100 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18104 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18106 case X86::VASTART_SAVE_XMM_REGS:
18107 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18109 case X86::VAARG_64:
18110 return EmitVAARG64WithCustomInserter(MI, BB);
18112 case X86::EH_SjLj_SetJmp32:
18113 case X86::EH_SjLj_SetJmp64:
18114 return emitEHSjLjSetJmp(MI, BB);
18116 case X86::EH_SjLj_LongJmp32:
18117 case X86::EH_SjLj_LongJmp64:
18118 return emitEHSjLjLongJmp(MI, BB);
18120 case TargetOpcode::STACKMAP:
18121 case TargetOpcode::PATCHPOINT:
18122 return emitPatchPoint(MI, BB);
18124 case X86::VFMADDPDr213r:
18125 case X86::VFMADDPSr213r:
18126 case X86::VFMADDSDr213r:
18127 case X86::VFMADDSSr213r:
18128 case X86::VFMSUBPDr213r:
18129 case X86::VFMSUBPSr213r:
18130 case X86::VFMSUBSDr213r:
18131 case X86::VFMSUBSSr213r:
18132 case X86::VFNMADDPDr213r:
18133 case X86::VFNMADDPSr213r:
18134 case X86::VFNMADDSDr213r:
18135 case X86::VFNMADDSSr213r:
18136 case X86::VFNMSUBPDr213r:
18137 case X86::VFNMSUBPSr213r:
18138 case X86::VFNMSUBSDr213r:
18139 case X86::VFNMSUBSSr213r:
18140 case X86::VFMADDPDr213rY:
18141 case X86::VFMADDPSr213rY:
18142 case X86::VFMSUBPDr213rY:
18143 case X86::VFMSUBPSr213rY:
18144 case X86::VFNMADDPDr213rY:
18145 case X86::VFNMADDPSr213rY:
18146 case X86::VFNMSUBPDr213rY:
18147 case X86::VFNMSUBPSr213rY:
18148 return emitFMA3Instr(MI, BB);
18152 //===----------------------------------------------------------------------===//
18153 // X86 Optimization Hooks
18154 //===----------------------------------------------------------------------===//
18156 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18159 const SelectionDAG &DAG,
18160 unsigned Depth) const {
18161 unsigned BitWidth = KnownZero.getBitWidth();
18162 unsigned Opc = Op.getOpcode();
18163 assert((Opc >= ISD::BUILTIN_OP_END ||
18164 Opc == ISD::INTRINSIC_WO_CHAIN ||
18165 Opc == ISD::INTRINSIC_W_CHAIN ||
18166 Opc == ISD::INTRINSIC_VOID) &&
18167 "Should use MaskedValueIsZero if you don't know whether Op"
18168 " is a target node!");
18170 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18184 // These nodes' second result is a boolean.
18185 if (Op.getResNo() == 0)
18188 case X86ISD::SETCC:
18189 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18191 case ISD::INTRINSIC_WO_CHAIN: {
18192 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18193 unsigned NumLoBits = 0;
18196 case Intrinsic::x86_sse_movmsk_ps:
18197 case Intrinsic::x86_avx_movmsk_ps_256:
18198 case Intrinsic::x86_sse2_movmsk_pd:
18199 case Intrinsic::x86_avx_movmsk_pd_256:
18200 case Intrinsic::x86_mmx_pmovmskb:
18201 case Intrinsic::x86_sse2_pmovmskb_128:
18202 case Intrinsic::x86_avx2_pmovmskb: {
18203 // High bits of movmskp{s|d}, pmovmskb are known zero.
18205 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18206 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18207 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18208 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18209 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18210 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18211 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18212 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18214 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18223 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18225 const SelectionDAG &,
18226 unsigned Depth) const {
18227 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18228 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18229 return Op.getValueType().getScalarType().getSizeInBits();
18235 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18236 /// node is a GlobalAddress + offset.
18237 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18238 const GlobalValue* &GA,
18239 int64_t &Offset) const {
18240 if (N->getOpcode() == X86ISD::Wrapper) {
18241 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18242 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18243 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18247 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18250 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18251 /// same as extracting the high 128-bit part of 256-bit vector and then
18252 /// inserting the result into the low part of a new 256-bit vector
18253 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18254 EVT VT = SVOp->getValueType(0);
18255 unsigned NumElems = VT.getVectorNumElements();
18257 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18258 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18259 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18260 SVOp->getMaskElt(j) >= 0)
18266 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18267 /// same as extracting the low 128-bit part of 256-bit vector and then
18268 /// inserting the result into the high part of a new 256-bit vector
18269 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18270 EVT VT = SVOp->getValueType(0);
18271 unsigned NumElems = VT.getVectorNumElements();
18273 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18274 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18275 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18276 SVOp->getMaskElt(j) >= 0)
18282 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18283 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18284 TargetLowering::DAGCombinerInfo &DCI,
18285 const X86Subtarget* Subtarget) {
18287 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18288 SDValue V1 = SVOp->getOperand(0);
18289 SDValue V2 = SVOp->getOperand(1);
18290 EVT VT = SVOp->getValueType(0);
18291 unsigned NumElems = VT.getVectorNumElements();
18293 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18294 V2.getOpcode() == ISD::CONCAT_VECTORS) {
18298 // V UNDEF BUILD_VECTOR UNDEF
18300 // CONCAT_VECTOR CONCAT_VECTOR
18303 // RESULT: V + zero extended
18305 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18306 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18307 V1.getOperand(1).getOpcode() != ISD::UNDEF)
18310 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18313 // To match the shuffle mask, the first half of the mask should
18314 // be exactly the first vector, and all the rest a splat with the
18315 // first element of the second one.
18316 for (unsigned i = 0; i != NumElems/2; ++i)
18317 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18318 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18321 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18322 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18323 if (Ld->hasNUsesOfValue(1, 0)) {
18324 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18325 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18327 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18329 Ld->getPointerInfo(),
18330 Ld->getAlignment(),
18331 false/*isVolatile*/, true/*ReadMem*/,
18332 false/*WriteMem*/);
18334 // Make sure the newly-created LOAD is in the same position as Ld in
18335 // terms of dependency. We create a TokenFactor for Ld and ResNode,
18336 // and update uses of Ld's output chain to use the TokenFactor.
18337 if (Ld->hasAnyUseOfValue(1)) {
18338 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18339 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18340 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18341 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18342 SDValue(ResNode.getNode(), 1));
18345 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18349 // Emit a zeroed vector and insert the desired subvector on its
18351 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18352 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18353 return DCI.CombineTo(N, InsV);
18356 //===--------------------------------------------------------------------===//
18357 // Combine some shuffles into subvector extracts and inserts:
18360 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18361 if (isShuffleHigh128VectorInsertLow(SVOp)) {
18362 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18363 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18364 return DCI.CombineTo(N, InsV);
18367 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18368 if (isShuffleLow128VectorInsertHigh(SVOp)) {
18369 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18370 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18371 return DCI.CombineTo(N, InsV);
18377 /// \brief Get the PSHUF-style mask from PSHUF node.
18379 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18380 /// PSHUF-style masks that can be reused with such instructions.
18381 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18382 SmallVector<int, 4> Mask;
18384 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18388 switch (N.getOpcode()) {
18389 case X86ISD::PSHUFD:
18391 case X86ISD::PSHUFLW:
18394 case X86ISD::PSHUFHW:
18395 Mask.erase(Mask.begin(), Mask.begin() + 4);
18396 for (int &M : Mask)
18400 llvm_unreachable("No valid shuffle instruction found!");
18404 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18406 /// We walk up the chain and look for a combinable shuffle, skipping over
18407 /// shuffles that we could hoist this shuffle's transformation past without
18408 /// altering anything.
18409 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18411 TargetLowering::DAGCombinerInfo &DCI) {
18412 assert(N.getOpcode() == X86ISD::PSHUFD &&
18413 "Called with something other than an x86 128-bit half shuffle!");
18416 // Walk up a single-use chain looking for a combinable shuffle.
18417 SDValue V = N.getOperand(0);
18418 for (; V.hasOneUse(); V = V.getOperand(0)) {
18419 switch (V.getOpcode()) {
18421 return false; // Nothing combined!
18424 // Skip bitcasts as we always know the type for the target specific
18428 case X86ISD::PSHUFD:
18429 // Found another dword shuffle.
18432 case X86ISD::PSHUFLW:
18433 // Check that the low words (being shuffled) are the identity in the
18434 // dword shuffle, and the high words are self-contained.
18435 if (Mask[0] != 0 || Mask[1] != 1 ||
18436 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18441 case X86ISD::PSHUFHW:
18442 // Check that the high words (being shuffled) are the identity in the
18443 // dword shuffle, and the low words are self-contained.
18444 if (Mask[2] != 2 || Mask[3] != 3 ||
18445 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18450 // Break out of the loop if we break out of the switch.
18454 if (!V.hasOneUse())
18455 // We fell out of the loop without finding a viable combining instruction.
18458 // Record the old value to use in RAUW-ing.
18461 // Merge this node's mask and our incoming mask.
18462 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18463 for (int &M : Mask)
18465 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V.getOperand(0),
18466 getV4X86ShuffleImm8ForMask(Mask, DAG));
18468 // It is possible that one of the combinable shuffles was completely absorbed
18469 // by the other, just replace it and revisit all users in that case.
18470 if (Old.getNode() == V.getNode()) {
18471 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18475 // Replace N with its operand as we're going to combine that shuffle away.
18476 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18478 // Replace the combinable shuffle with the combined one, updating all users
18479 // so that we re-evaluate the chain here.
18480 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18484 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18486 /// We walk up the chain, skipping shuffles of the other half and looking
18487 /// through shuffles which switch halves trying to find a shuffle of the same
18488 /// pair of dwords.
18489 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18491 TargetLowering::DAGCombinerInfo &DCI) {
18493 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18494 "Called with something other than an x86 128-bit half shuffle!");
18496 unsigned CombineOpcode = N.getOpcode();
18498 // Walk up a single-use chain looking for a combinable shuffle.
18499 SDValue V = N.getOperand(0);
18500 for (; V.hasOneUse(); V = V.getOperand(0)) {
18501 switch (V.getOpcode()) {
18503 return false; // Nothing combined!
18506 // Skip bitcasts as we always know the type for the target specific
18510 case X86ISD::PSHUFLW:
18511 case X86ISD::PSHUFHW:
18512 if (V.getOpcode() == CombineOpcode)
18515 // Other-half shuffles are no-ops.
18518 case X86ISD::PSHUFD: {
18519 // We can only handle pshufd if the half we are combining either stays in
18520 // its half, or switches to the other half. Bail if one of these isn't
18522 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18523 int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18524 if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18525 (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18528 // Map the mask through the pshufd and keep walking up the chain.
18529 for (int i = 0; i < 4; ++i)
18530 Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18532 // Switch halves if the pshufd does.
18534 VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18538 // Break out of the loop if we break out of the switch.
18542 if (!V.hasOneUse())
18543 // We fell out of the loop without finding a viable combining instruction.
18546 // Record the old value to use in RAUW-ing.
18549 // Merge this node's mask and our incoming mask (adjusted to account for all
18550 // the pshufd instructions encountered).
18551 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18552 for (int &M : Mask)
18554 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18555 getV4X86ShuffleImm8ForMask(Mask, DAG));
18557 // Replace N with its operand as we're going to combine that shuffle away.
18558 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18560 // Replace the combinable shuffle with the combined one, updating all users
18561 // so that we re-evaluate the chain here.
18562 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18566 /// \brief Try to combine x86 target specific shuffles.
18567 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18568 TargetLowering::DAGCombinerInfo &DCI,
18569 const X86Subtarget *Subtarget) {
18571 MVT VT = N.getSimpleValueType();
18572 SmallVector<int, 4> Mask;
18574 switch (N.getOpcode()) {
18575 case X86ISD::PSHUFD:
18576 case X86ISD::PSHUFLW:
18577 case X86ISD::PSHUFHW:
18578 Mask = getPSHUFShuffleMask(N);
18579 assert(Mask.size() == 4);
18585 // Nuke no-op shuffles that show up after combining.
18586 if (isNoopShuffleMask(Mask))
18587 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18589 // Look for simplifications involving one or two shuffle instructions.
18590 SDValue V = N.getOperand(0);
18591 switch (N.getOpcode()) {
18594 case X86ISD::PSHUFLW:
18595 case X86ISD::PSHUFHW:
18596 assert(VT == MVT::v8i16);
18599 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18600 return SDValue(); // We combined away this shuffle, so we're done.
18602 // See if this reduces to a PSHUFD which is no more expensive and can
18603 // combine with more operations.
18604 if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18605 areAdjacentMasksSequential(Mask)) {
18606 int DMask[] = {-1, -1, -1, -1};
18607 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18608 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18609 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18610 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18611 DCI.AddToWorklist(V.getNode());
18612 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18613 getV4X86ShuffleImm8ForMask(DMask, DAG));
18614 DCI.AddToWorklist(V.getNode());
18615 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18620 case X86ISD::PSHUFD:
18621 if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
18622 return SDValue(); // We combined away this shuffle.
18630 /// PerformShuffleCombine - Performs several different shuffle combines.
18631 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
18632 TargetLowering::DAGCombinerInfo &DCI,
18633 const X86Subtarget *Subtarget) {
18635 SDValue N0 = N->getOperand(0);
18636 SDValue N1 = N->getOperand(1);
18637 EVT VT = N->getValueType(0);
18639 // Canonicalize shuffles that perform 'addsub' on packed float vectors
18640 // according to the rule:
18641 // (shuffle (FADD A, B), (FSUB A, B), Mask) ->
18642 // (shuffle (FSUB A, -B), (FADD A, -B), Mask)
18644 // Where 'Mask' is:
18645 // <0,5,2,7> -- for v4f32 and v4f64 shuffles;
18646 // <0,3> -- for v2f64 shuffles;
18647 // <0,9,2,11,4,13,6,15> -- for v8f32 shuffles.
18649 // This helps pattern-matching more SSE3/AVX ADDSUB instructions
18650 // during ISel stage.
18651 if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
18652 ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18653 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18654 N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
18655 // Operands to the FADD and FSUB must be the same.
18656 ((N0->getOperand(0) == N1->getOperand(0) &&
18657 N0->getOperand(1) == N1->getOperand(1)) ||
18658 // FADD is commutable. See if by commuting the operands of the FADD
18659 // we would still be able to match the operands of the FSUB dag node.
18660 (N0->getOperand(1) == N1->getOperand(0) &&
18661 N0->getOperand(0) == N1->getOperand(1))) &&
18662 N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
18663 N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
18665 ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
18666 unsigned NumElts = VT.getVectorNumElements();
18667 ArrayRef<int> Mask = SV->getMask();
18668 bool CanFold = true;
18670 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
18671 CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
18674 SDValue Op0 = N1->getOperand(0);
18675 SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
18676 SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
18677 SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
18678 return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
18682 // Don't create instructions with illegal types after legalize types has run.
18683 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18684 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18687 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18688 if (Subtarget->hasFp256() && VT.is256BitVector() &&
18689 N->getOpcode() == ISD::VECTOR_SHUFFLE)
18690 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18692 // During Type Legalization, when promoting illegal vector types,
18693 // the backend might introduce new shuffle dag nodes and bitcasts.
18695 // This code performs the following transformation:
18696 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18697 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18699 // We do this only if both the bitcast and the BINOP dag nodes have
18700 // one use. Also, perform this transformation only if the new binary
18701 // operation is legal. This is to avoid introducing dag nodes that
18702 // potentially need to be further expanded (or custom lowered) into a
18703 // less optimal sequence of dag nodes.
18704 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18705 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18706 N0.getOpcode() == ISD::BITCAST) {
18707 SDValue BC0 = N0.getOperand(0);
18708 EVT SVT = BC0.getValueType();
18709 unsigned Opcode = BC0.getOpcode();
18710 unsigned NumElts = VT.getVectorNumElements();
18712 if (BC0.hasOneUse() && SVT.isVector() &&
18713 SVT.getVectorNumElements() * 2 == NumElts &&
18714 TLI.isOperationLegal(Opcode, VT)) {
18715 bool CanFold = false;
18727 unsigned SVTNumElts = SVT.getVectorNumElements();
18728 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18729 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18730 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18731 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18732 CanFold = SVOp->getMaskElt(i) < 0;
18735 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18736 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18737 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18738 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18743 // Only handle 128 wide vector from here on.
18744 if (!VT.is128BitVector())
18747 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18748 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18749 // consecutive, non-overlapping, and in the right order.
18750 SmallVector<SDValue, 16> Elts;
18751 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18752 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18754 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18758 if (isTargetShuffle(N->getOpcode())) {
18760 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
18761 if (Shuffle.getNode())
18768 /// PerformTruncateCombine - Converts truncate operation to
18769 /// a sequence of vector shuffle operations.
18770 /// It is possible when we truncate 256-bit vector to 128-bit vector
18771 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18772 TargetLowering::DAGCombinerInfo &DCI,
18773 const X86Subtarget *Subtarget) {
18777 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18778 /// specific shuffle of a load can be folded into a single element load.
18779 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18780 /// shuffles have been customed lowered so we need to handle those here.
18781 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18782 TargetLowering::DAGCombinerInfo &DCI) {
18783 if (DCI.isBeforeLegalizeOps())
18786 SDValue InVec = N->getOperand(0);
18787 SDValue EltNo = N->getOperand(1);
18789 if (!isa<ConstantSDNode>(EltNo))
18792 EVT VT = InVec.getValueType();
18794 bool HasShuffleIntoBitcast = false;
18795 if (InVec.getOpcode() == ISD::BITCAST) {
18796 // Don't duplicate a load with other uses.
18797 if (!InVec.hasOneUse())
18799 EVT BCVT = InVec.getOperand(0).getValueType();
18800 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18802 InVec = InVec.getOperand(0);
18803 HasShuffleIntoBitcast = true;
18806 if (!isTargetShuffle(InVec.getOpcode()))
18809 // Don't duplicate a load with other uses.
18810 if (!InVec.hasOneUse())
18813 SmallVector<int, 16> ShuffleMask;
18815 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18819 // Select the input vector, guarding against out of range extract vector.
18820 unsigned NumElems = VT.getVectorNumElements();
18821 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18822 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18823 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18824 : InVec.getOperand(1);
18826 // If inputs to shuffle are the same for both ops, then allow 2 uses
18827 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18829 if (LdNode.getOpcode() == ISD::BITCAST) {
18830 // Don't duplicate a load with other uses.
18831 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18834 AllowedUses = 1; // only allow 1 load use if we have a bitcast
18835 LdNode = LdNode.getOperand(0);
18838 if (!ISD::isNormalLoad(LdNode.getNode()))
18841 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18843 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18846 if (HasShuffleIntoBitcast) {
18847 // If there's a bitcast before the shuffle, check if the load type and
18848 // alignment is valid.
18849 unsigned Align = LN0->getAlignment();
18850 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18851 unsigned NewAlign = TLI.getDataLayout()->
18852 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18854 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18858 // All checks match so transform back to vector_shuffle so that DAG combiner
18859 // can finish the job
18862 // Create shuffle node taking into account the case that its a unary shuffle
18863 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18864 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18865 InVec.getOperand(0), Shuffle,
18867 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18868 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18872 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18873 /// generation and convert it from being a bunch of shuffles and extracts
18874 /// to a simple store and scalar loads to extract the elements.
18875 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18876 TargetLowering::DAGCombinerInfo &DCI) {
18877 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18878 if (NewOp.getNode())
18881 SDValue InputVector = N->getOperand(0);
18883 // Detect whether we are trying to convert from mmx to i32 and the bitcast
18884 // from mmx to v2i32 has a single usage.
18885 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18886 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18887 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18888 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18889 N->getValueType(0),
18890 InputVector.getNode()->getOperand(0));
18892 // Only operate on vectors of 4 elements, where the alternative shuffling
18893 // gets to be more expensive.
18894 if (InputVector.getValueType() != MVT::v4i32)
18897 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
18898 // single use which is a sign-extend or zero-extend, and all elements are
18900 SmallVector<SDNode *, 4> Uses;
18901 unsigned ExtractedElements = 0;
18902 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
18903 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
18904 if (UI.getUse().getResNo() != InputVector.getResNo())
18907 SDNode *Extract = *UI;
18908 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18911 if (Extract->getValueType(0) != MVT::i32)
18913 if (!Extract->hasOneUse())
18915 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18916 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18918 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18921 // Record which element was extracted.
18922 ExtractedElements |=
18923 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18925 Uses.push_back(Extract);
18928 // If not all the elements were used, this may not be worthwhile.
18929 if (ExtractedElements != 15)
18932 // Ok, we've now decided to do the transformation.
18933 SDLoc dl(InputVector);
18935 // Store the value to a temporary stack slot.
18936 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18937 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18938 MachinePointerInfo(), false, false, 0);
18940 // Replace each use (extract) with a load of the appropriate element.
18941 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18942 UE = Uses.end(); UI != UE; ++UI) {
18943 SDNode *Extract = *UI;
18945 // cOMpute the element's address.
18946 SDValue Idx = Extract->getOperand(1);
18948 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18949 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18950 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18951 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18953 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18954 StackPtr, OffsetVal);
18956 // Load the scalar.
18957 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
18958 ScalarAddr, MachinePointerInfo(),
18959 false, false, false, 0);
18961 // Replace the exact with the load.
18962 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
18965 // The replacement was made in place; don't return anything.
18969 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
18970 static std::pair<unsigned, bool>
18971 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
18972 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
18973 if (!VT.isVector())
18974 return std::make_pair(0, false);
18976 bool NeedSplit = false;
18977 switch (VT.getSimpleVT().SimpleTy) {
18978 default: return std::make_pair(0, false);
18982 if (!Subtarget->hasAVX2())
18984 if (!Subtarget->hasAVX())
18985 return std::make_pair(0, false);
18990 if (!Subtarget->hasSSE2())
18991 return std::make_pair(0, false);
18994 // SSE2 has only a small subset of the operations.
18995 bool hasUnsigned = Subtarget->hasSSE41() ||
18996 (Subtarget->hasSSE2() && VT == MVT::v16i8);
18997 bool hasSigned = Subtarget->hasSSE41() ||
18998 (Subtarget->hasSSE2() && VT == MVT::v8i16);
19000 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19003 // Check for x CC y ? x : y.
19004 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19005 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19010 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19013 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19016 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19019 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19021 // Check for x CC y ? y : x -- a min/max with reversed arms.
19022 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19023 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19028 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19031 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19034 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19037 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19041 return std::make_pair(Opc, NeedSplit);
19045 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19046 const X86Subtarget *Subtarget) {
19048 SDValue Cond = N->getOperand(0);
19049 SDValue LHS = N->getOperand(1);
19050 SDValue RHS = N->getOperand(2);
19052 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19053 SDValue CondSrc = Cond->getOperand(0);
19054 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19055 Cond = CondSrc->getOperand(0);
19058 MVT VT = N->getSimpleValueType(0);
19059 MVT EltVT = VT.getVectorElementType();
19060 unsigned NumElems = VT.getVectorNumElements();
19061 // There is no blend with immediate in AVX-512.
19062 if (VT.is512BitVector())
19065 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19067 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19070 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19073 unsigned MaskValue = 0;
19074 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19077 SmallVector<int, 8> ShuffleMask(NumElems, -1);
19078 for (unsigned i = 0; i < NumElems; ++i) {
19079 // Be sure we emit undef where we can.
19080 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19081 ShuffleMask[i] = -1;
19083 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19086 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19089 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19091 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19092 TargetLowering::DAGCombinerInfo &DCI,
19093 const X86Subtarget *Subtarget) {
19095 SDValue Cond = N->getOperand(0);
19096 // Get the LHS/RHS of the select.
19097 SDValue LHS = N->getOperand(1);
19098 SDValue RHS = N->getOperand(2);
19099 EVT VT = LHS.getValueType();
19100 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19102 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19103 // instructions match the semantics of the common C idiom x<y?x:y but not
19104 // x<=y?x:y, because of how they handle negative zero (which can be
19105 // ignored in unsafe-math mode).
19106 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19107 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19108 (Subtarget->hasSSE2() ||
19109 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19110 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19112 unsigned Opcode = 0;
19113 // Check for x CC y ? x : y.
19114 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19115 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19119 // Converting this to a min would handle NaNs incorrectly, and swapping
19120 // the operands would cause it to handle comparisons between positive
19121 // and negative zero incorrectly.
19122 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19123 if (!DAG.getTarget().Options.UnsafeFPMath &&
19124 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19126 std::swap(LHS, RHS);
19128 Opcode = X86ISD::FMIN;
19131 // Converting this to a min would handle comparisons between positive
19132 // and negative zero incorrectly.
19133 if (!DAG.getTarget().Options.UnsafeFPMath &&
19134 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19136 Opcode = X86ISD::FMIN;
19139 // Converting this to a min would handle both negative zeros and NaNs
19140 // incorrectly, but we can swap the operands to fix both.
19141 std::swap(LHS, RHS);
19145 Opcode = X86ISD::FMIN;
19149 // Converting this to a max would handle comparisons between positive
19150 // and negative zero incorrectly.
19151 if (!DAG.getTarget().Options.UnsafeFPMath &&
19152 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19154 Opcode = X86ISD::FMAX;
19157 // Converting this to a max would handle NaNs incorrectly, and swapping
19158 // the operands would cause it to handle comparisons between positive
19159 // and negative zero incorrectly.
19160 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19161 if (!DAG.getTarget().Options.UnsafeFPMath &&
19162 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19164 std::swap(LHS, RHS);
19166 Opcode = X86ISD::FMAX;
19169 // Converting this to a max would handle both negative zeros and NaNs
19170 // incorrectly, but we can swap the operands to fix both.
19171 std::swap(LHS, RHS);
19175 Opcode = X86ISD::FMAX;
19178 // Check for x CC y ? y : x -- a min/max with reversed arms.
19179 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19180 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19184 // Converting this to a min would handle comparisons between positive
19185 // and negative zero incorrectly, and swapping the operands would
19186 // cause it to handle NaNs incorrectly.
19187 if (!DAG.getTarget().Options.UnsafeFPMath &&
19188 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19189 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19191 std::swap(LHS, RHS);
19193 Opcode = X86ISD::FMIN;
19196 // Converting this to a min would handle NaNs incorrectly.
19197 if (!DAG.getTarget().Options.UnsafeFPMath &&
19198 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19200 Opcode = X86ISD::FMIN;
19203 // Converting this to a min would handle both negative zeros and NaNs
19204 // incorrectly, but we can swap the operands to fix both.
19205 std::swap(LHS, RHS);
19209 Opcode = X86ISD::FMIN;
19213 // Converting this to a max would handle NaNs incorrectly.
19214 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19216 Opcode = X86ISD::FMAX;
19219 // Converting this to a max would handle comparisons between positive
19220 // and negative zero incorrectly, and swapping the operands would
19221 // cause it to handle NaNs incorrectly.
19222 if (!DAG.getTarget().Options.UnsafeFPMath &&
19223 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19224 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19226 std::swap(LHS, RHS);
19228 Opcode = X86ISD::FMAX;
19231 // Converting this to a max would handle both negative zeros and NaNs
19232 // incorrectly, but we can swap the operands to fix both.
19233 std::swap(LHS, RHS);
19237 Opcode = X86ISD::FMAX;
19243 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19246 EVT CondVT = Cond.getValueType();
19247 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19248 CondVT.getVectorElementType() == MVT::i1) {
19249 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19250 // lowering on AVX-512. In this case we convert it to
19251 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19252 // The same situation for all 128 and 256-bit vectors of i8 and i16
19253 EVT OpVT = LHS.getValueType();
19254 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19255 (OpVT.getVectorElementType() == MVT::i8 ||
19256 OpVT.getVectorElementType() == MVT::i16)) {
19257 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19258 DCI.AddToWorklist(Cond.getNode());
19259 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19262 // If this is a select between two integer constants, try to do some
19264 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19265 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19266 // Don't do this for crazy integer types.
19267 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19268 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19269 // so that TrueC (the true value) is larger than FalseC.
19270 bool NeedsCondInvert = false;
19272 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19273 // Efficiently invertible.
19274 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
19275 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
19276 isa<ConstantSDNode>(Cond.getOperand(1))))) {
19277 NeedsCondInvert = true;
19278 std::swap(TrueC, FalseC);
19281 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
19282 if (FalseC->getAPIntValue() == 0 &&
19283 TrueC->getAPIntValue().isPowerOf2()) {
19284 if (NeedsCondInvert) // Invert the condition if needed.
19285 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19286 DAG.getConstant(1, Cond.getValueType()));
19288 // Zero extend the condition if needed.
19289 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19291 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19292 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19293 DAG.getConstant(ShAmt, MVT::i8));
19296 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19297 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19298 if (NeedsCondInvert) // Invert the condition if needed.
19299 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19300 DAG.getConstant(1, Cond.getValueType()));
19302 // Zero extend the condition if needed.
19303 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19304 FalseC->getValueType(0), Cond);
19305 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19306 SDValue(FalseC, 0));
19309 // Optimize cases that will turn into an LEA instruction. This requires
19310 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19311 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19312 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19313 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19315 bool isFastMultiplier = false;
19317 switch ((unsigned char)Diff) {
19319 case 1: // result = add base, cond
19320 case 2: // result = lea base( , cond*2)
19321 case 3: // result = lea base(cond, cond*2)
19322 case 4: // result = lea base( , cond*4)
19323 case 5: // result = lea base(cond, cond*4)
19324 case 8: // result = lea base( , cond*8)
19325 case 9: // result = lea base(cond, cond*8)
19326 isFastMultiplier = true;
19331 if (isFastMultiplier) {
19332 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19333 if (NeedsCondInvert) // Invert the condition if needed.
19334 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19335 DAG.getConstant(1, Cond.getValueType()));
19337 // Zero extend the condition if needed.
19338 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19340 // Scale the condition by the difference.
19342 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19343 DAG.getConstant(Diff, Cond.getValueType()));
19345 // Add the base if non-zero.
19346 if (FalseC->getAPIntValue() != 0)
19347 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19348 SDValue(FalseC, 0));
19355 // Canonicalize max and min:
19356 // (x > y) ? x : y -> (x >= y) ? x : y
19357 // (x < y) ? x : y -> (x <= y) ? x : y
19358 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19359 // the need for an extra compare
19360 // against zero. e.g.
19361 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19363 // testl %edi, %edi
19365 // cmovgl %edi, %eax
19369 // cmovsl %eax, %edi
19370 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19371 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19372 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19373 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19378 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19379 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19380 Cond.getOperand(0), Cond.getOperand(1), NewCC);
19381 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19386 // Early exit check
19387 if (!TLI.isTypeLegal(VT))
19390 // Match VSELECTs into subs with unsigned saturation.
19391 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19392 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19393 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19394 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19395 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19397 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19398 // left side invert the predicate to simplify logic below.
19400 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19402 CC = ISD::getSetCCInverse(CC, true);
19403 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19407 if (Other.getNode() && Other->getNumOperands() == 2 &&
19408 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19409 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19410 SDValue CondRHS = Cond->getOperand(1);
19412 // Look for a general sub with unsigned saturation first.
19413 // x >= y ? x-y : 0 --> subus x, y
19414 // x > y ? x-y : 0 --> subus x, y
19415 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19416 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19417 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19419 // If the RHS is a constant we have to reverse the const canonicalization.
19420 // x > C-1 ? x+-C : 0 --> subus x, C
19421 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19422 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
19423 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
19424 if (CondRHS.getConstantOperandVal(0) == -A-1)
19425 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
19426 DAG.getConstant(-A, VT));
19429 // Another special case: If C was a sign bit, the sub has been
19430 // canonicalized into a xor.
19431 // FIXME: Would it be better to use computeKnownBits to determine whether
19432 // it's safe to decanonicalize the xor?
19433 // x s< 0 ? x^C : 0 --> subus x, C
19434 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19435 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19436 isSplatVector(OpRHS.getNode())) {
19437 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
19439 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19444 // Try to match a min/max vector operation.
19445 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19446 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19447 unsigned Opc = ret.first;
19448 bool NeedSplit = ret.second;
19450 if (Opc && NeedSplit) {
19451 unsigned NumElems = VT.getVectorNumElements();
19452 // Extract the LHS vectors
19453 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19454 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19456 // Extract the RHS vectors
19457 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19458 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19460 // Create min/max for each subvector
19461 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19462 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19464 // Merge the result
19465 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19467 return DAG.getNode(Opc, DL, VT, LHS, RHS);
19470 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19471 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19472 // Check if SETCC has already been promoted
19473 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19474 // Check that condition value type matches vselect operand type
19477 assert(Cond.getValueType().isVector() &&
19478 "vector select expects a vector selector!");
19480 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19481 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19483 if (!TValIsAllOnes && !FValIsAllZeros) {
19484 // Try invert the condition if true value is not all 1s and false value
19486 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19487 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19489 if (TValIsAllZeros || FValIsAllOnes) {
19490 SDValue CC = Cond.getOperand(2);
19491 ISD::CondCode NewCC =
19492 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19493 Cond.getOperand(0).getValueType().isInteger());
19494 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19495 std::swap(LHS, RHS);
19496 TValIsAllOnes = FValIsAllOnes;
19497 FValIsAllZeros = TValIsAllZeros;
19501 if (TValIsAllOnes || FValIsAllZeros) {
19504 if (TValIsAllOnes && FValIsAllZeros)
19506 else if (TValIsAllOnes)
19507 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19508 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19509 else if (FValIsAllZeros)
19510 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19511 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19513 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19517 // Try to fold this VSELECT into a MOVSS/MOVSD
19518 if (N->getOpcode() == ISD::VSELECT &&
19519 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19520 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19521 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19522 bool CanFold = false;
19523 unsigned NumElems = Cond.getNumOperands();
19527 if (isZero(Cond.getOperand(0))) {
19530 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19531 // fold (vselect <0,-1> -> (movsd A, B)
19532 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19533 CanFold = isAllOnes(Cond.getOperand(i));
19534 } else if (isAllOnes(Cond.getOperand(0))) {
19538 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19539 // fold (vselect <-1,0> -> (movsd B, A)
19540 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19541 CanFold = isZero(Cond.getOperand(i));
19545 if (VT == MVT::v4i32 || VT == MVT::v4f32)
19546 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19547 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19550 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19551 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19552 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19553 // (v2i64 (bitcast B)))))
19555 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19556 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19557 // (v2f64 (bitcast B)))))
19559 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19560 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19561 // (v2i64 (bitcast A)))))
19563 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19564 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19565 // (v2f64 (bitcast A)))))
19567 CanFold = (isZero(Cond.getOperand(0)) &&
19568 isZero(Cond.getOperand(1)) &&
19569 isAllOnes(Cond.getOperand(2)) &&
19570 isAllOnes(Cond.getOperand(3)));
19572 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19573 isAllOnes(Cond.getOperand(1)) &&
19574 isZero(Cond.getOperand(2)) &&
19575 isZero(Cond.getOperand(3))) {
19577 std::swap(LHS, RHS);
19581 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19582 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19583 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19584 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19586 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19592 // If we know that this node is legal then we know that it is going to be
19593 // matched by one of the SSE/AVX BLEND instructions. These instructions only
19594 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19595 // to simplify previous instructions.
19596 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19597 !DCI.isBeforeLegalize() &&
19598 // We explicitly check against v8i16 and v16i16 because, although
19599 // they're marked as Custom, they might only be legal when Cond is a
19600 // build_vector of constants. This will be taken care in a later
19602 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19603 VT != MVT::v8i16)) {
19604 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19606 // Don't optimize vector selects that map to mask-registers.
19610 // Check all uses of that condition operand to check whether it will be
19611 // consumed by non-BLEND instructions, which may depend on all bits are set
19613 for (SDNode::use_iterator I = Cond->use_begin(),
19614 E = Cond->use_end(); I != E; ++I)
19615 if (I->getOpcode() != ISD::VSELECT)
19616 // TODO: Add other opcodes eventually lowered into BLEND.
19619 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19620 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19622 APInt KnownZero, KnownOne;
19623 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19624 DCI.isBeforeLegalizeOps());
19625 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19626 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19627 DCI.CommitTargetLoweringOpt(TLO);
19630 // We should generate an X86ISD::BLENDI from a vselect if its argument
19631 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
19632 // constants. This specific pattern gets generated when we split a
19633 // selector for a 512 bit vector in a machine without AVX512 (but with
19634 // 256-bit vectors), during legalization:
19636 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
19638 // Iff we find this pattern and the build_vectors are built from
19639 // constants, we translate the vselect into a shuffle_vector that we
19640 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
19641 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
19642 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
19643 if (Shuffle.getNode())
19650 // Check whether a boolean test is testing a boolean value generated by
19651 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
19654 // Simplify the following patterns:
19655 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
19656 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
19657 // to (Op EFLAGS Cond)
19659 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
19660 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
19661 // to (Op EFLAGS !Cond)
19663 // where Op could be BRCOND or CMOV.
19665 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
19666 // Quit if not CMP and SUB with its value result used.
19667 if (Cmp.getOpcode() != X86ISD::CMP &&
19668 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
19671 // Quit if not used as a boolean value.
19672 if (CC != X86::COND_E && CC != X86::COND_NE)
19675 // Check CMP operands. One of them should be 0 or 1 and the other should be
19676 // an SetCC or extended from it.
19677 SDValue Op1 = Cmp.getOperand(0);
19678 SDValue Op2 = Cmp.getOperand(1);
19681 const ConstantSDNode* C = nullptr;
19682 bool needOppositeCond = (CC == X86::COND_E);
19683 bool checkAgainstTrue = false; // Is it a comparison against 1?
19685 if ((C = dyn_cast<ConstantSDNode>(Op1)))
19687 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19689 else // Quit if all operands are not constants.
19692 if (C->getZExtValue() == 1) {
19693 needOppositeCond = !needOppositeCond;
19694 checkAgainstTrue = true;
19695 } else if (C->getZExtValue() != 0)
19696 // Quit if the constant is neither 0 or 1.
19699 bool truncatedToBoolWithAnd = false;
19700 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19701 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19702 SetCC.getOpcode() == ISD::TRUNCATE ||
19703 SetCC.getOpcode() == ISD::AND) {
19704 if (SetCC.getOpcode() == ISD::AND) {
19706 ConstantSDNode *CS;
19707 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19708 CS->getZExtValue() == 1)
19710 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19711 CS->getZExtValue() == 1)
19715 SetCC = SetCC.getOperand(OpIdx);
19716 truncatedToBoolWithAnd = true;
19718 SetCC = SetCC.getOperand(0);
19721 switch (SetCC.getOpcode()) {
19722 case X86ISD::SETCC_CARRY:
19723 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19724 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19725 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19726 // truncated to i1 using 'and'.
19727 if (checkAgainstTrue && !truncatedToBoolWithAnd)
19729 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19730 "Invalid use of SETCC_CARRY!");
19732 case X86ISD::SETCC:
19733 // Set the condition code or opposite one if necessary.
19734 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19735 if (needOppositeCond)
19736 CC = X86::GetOppositeBranchCondition(CC);
19737 return SetCC.getOperand(1);
19738 case X86ISD::CMOV: {
19739 // Check whether false/true value has canonical one, i.e. 0 or 1.
19740 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19741 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19742 // Quit if true value is not a constant.
19745 // Quit if false value is not a constant.
19747 SDValue Op = SetCC.getOperand(0);
19748 // Skip 'zext' or 'trunc' node.
19749 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19750 Op.getOpcode() == ISD::TRUNCATE)
19751 Op = Op.getOperand(0);
19752 // A special case for rdrand/rdseed, where 0 is set if false cond is
19754 if ((Op.getOpcode() != X86ISD::RDRAND &&
19755 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19758 // Quit if false value is not the constant 0 or 1.
19759 bool FValIsFalse = true;
19760 if (FVal && FVal->getZExtValue() != 0) {
19761 if (FVal->getZExtValue() != 1)
19763 // If FVal is 1, opposite cond is needed.
19764 needOppositeCond = !needOppositeCond;
19765 FValIsFalse = false;
19767 // Quit if TVal is not the constant opposite of FVal.
19768 if (FValIsFalse && TVal->getZExtValue() != 1)
19770 if (!FValIsFalse && TVal->getZExtValue() != 0)
19772 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19773 if (needOppositeCond)
19774 CC = X86::GetOppositeBranchCondition(CC);
19775 return SetCC.getOperand(3);
19782 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19783 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19784 TargetLowering::DAGCombinerInfo &DCI,
19785 const X86Subtarget *Subtarget) {
19788 // If the flag operand isn't dead, don't touch this CMOV.
19789 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19792 SDValue FalseOp = N->getOperand(0);
19793 SDValue TrueOp = N->getOperand(1);
19794 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19795 SDValue Cond = N->getOperand(3);
19797 if (CC == X86::COND_E || CC == X86::COND_NE) {
19798 switch (Cond.getOpcode()) {
19802 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19803 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19804 return (CC == X86::COND_E) ? FalseOp : TrueOp;
19810 Flags = checkBoolTestSetCCCombine(Cond, CC);
19811 if (Flags.getNode() &&
19812 // Extra check as FCMOV only supports a subset of X86 cond.
19813 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19814 SDValue Ops[] = { FalseOp, TrueOp,
19815 DAG.getConstant(CC, MVT::i8), Flags };
19816 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19819 // If this is a select between two integer constants, try to do some
19820 // optimizations. Note that the operands are ordered the opposite of SELECT
19822 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19823 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19824 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19825 // larger than FalseC (the false value).
19826 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19827 CC = X86::GetOppositeBranchCondition(CC);
19828 std::swap(TrueC, FalseC);
19829 std::swap(TrueOp, FalseOp);
19832 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
19833 // This is efficient for any integer data type (including i8/i16) and
19835 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19836 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19837 DAG.getConstant(CC, MVT::i8), Cond);
19839 // Zero extend the condition if needed.
19840 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19842 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19843 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19844 DAG.getConstant(ShAmt, MVT::i8));
19845 if (N->getNumValues() == 2) // Dead flag value?
19846 return DCI.CombineTo(N, Cond, SDValue());
19850 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
19851 // for any integer data type, including i8/i16.
19852 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19853 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19854 DAG.getConstant(CC, MVT::i8), Cond);
19856 // Zero extend the condition if needed.
19857 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19858 FalseC->getValueType(0), Cond);
19859 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19860 SDValue(FalseC, 0));
19862 if (N->getNumValues() == 2) // Dead flag value?
19863 return DCI.CombineTo(N, Cond, SDValue());
19867 // Optimize cases that will turn into an LEA instruction. This requires
19868 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19869 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19870 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19871 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19873 bool isFastMultiplier = false;
19875 switch ((unsigned char)Diff) {
19877 case 1: // result = add base, cond
19878 case 2: // result = lea base( , cond*2)
19879 case 3: // result = lea base(cond, cond*2)
19880 case 4: // result = lea base( , cond*4)
19881 case 5: // result = lea base(cond, cond*4)
19882 case 8: // result = lea base( , cond*8)
19883 case 9: // result = lea base(cond, cond*8)
19884 isFastMultiplier = true;
19889 if (isFastMultiplier) {
19890 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19891 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19892 DAG.getConstant(CC, MVT::i8), Cond);
19893 // Zero extend the condition if needed.
19894 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19896 // Scale the condition by the difference.
19898 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19899 DAG.getConstant(Diff, Cond.getValueType()));
19901 // Add the base if non-zero.
19902 if (FalseC->getAPIntValue() != 0)
19903 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19904 SDValue(FalseC, 0));
19905 if (N->getNumValues() == 2) // Dead flag value?
19906 return DCI.CombineTo(N, Cond, SDValue());
19913 // Handle these cases:
19914 // (select (x != c), e, c) -> select (x != c), e, x),
19915 // (select (x == c), c, e) -> select (x == c), x, e)
19916 // where the c is an integer constant, and the "select" is the combination
19917 // of CMOV and CMP.
19919 // The rationale for this change is that the conditional-move from a constant
19920 // needs two instructions, however, conditional-move from a register needs
19921 // only one instruction.
19923 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19924 // some instruction-combining opportunities. This opt needs to be
19925 // postponed as late as possible.
19927 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19928 // the DCI.xxxx conditions are provided to postpone the optimization as
19929 // late as possible.
19931 ConstantSDNode *CmpAgainst = nullptr;
19932 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19933 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19934 !isa<ConstantSDNode>(Cond.getOperand(0))) {
19936 if (CC == X86::COND_NE &&
19937 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19938 CC = X86::GetOppositeBranchCondition(CC);
19939 std::swap(TrueOp, FalseOp);
19942 if (CC == X86::COND_E &&
19943 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19944 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19945 DAG.getConstant(CC, MVT::i8), Cond };
19946 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19954 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
19955 const X86Subtarget *Subtarget) {
19956 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
19958 default: return SDValue();
19959 // SSE/AVX/AVX2 blend intrinsics.
19960 case Intrinsic::x86_avx2_pblendvb:
19961 case Intrinsic::x86_avx2_pblendw:
19962 case Intrinsic::x86_avx2_pblendd_128:
19963 case Intrinsic::x86_avx2_pblendd_256:
19964 // Don't try to simplify this intrinsic if we don't have AVX2.
19965 if (!Subtarget->hasAVX2())
19968 case Intrinsic::x86_avx_blend_pd_256:
19969 case Intrinsic::x86_avx_blend_ps_256:
19970 case Intrinsic::x86_avx_blendv_pd_256:
19971 case Intrinsic::x86_avx_blendv_ps_256:
19972 // Don't try to simplify this intrinsic if we don't have AVX.
19973 if (!Subtarget->hasAVX())
19976 case Intrinsic::x86_sse41_pblendw:
19977 case Intrinsic::x86_sse41_blendpd:
19978 case Intrinsic::x86_sse41_blendps:
19979 case Intrinsic::x86_sse41_blendvps:
19980 case Intrinsic::x86_sse41_blendvpd:
19981 case Intrinsic::x86_sse41_pblendvb: {
19982 SDValue Op0 = N->getOperand(1);
19983 SDValue Op1 = N->getOperand(2);
19984 SDValue Mask = N->getOperand(3);
19986 // Don't try to simplify this intrinsic if we don't have SSE4.1.
19987 if (!Subtarget->hasSSE41())
19990 // fold (blend A, A, Mask) -> A
19993 // fold (blend A, B, allZeros) -> A
19994 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
19996 // fold (blend A, B, allOnes) -> B
19997 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20000 // Simplify the case where the mask is a constant i32 value.
20001 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20002 if (C->isNullValue())
20004 if (C->isAllOnesValue())
20011 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20012 case Intrinsic::x86_sse2_psrai_w:
20013 case Intrinsic::x86_sse2_psrai_d:
20014 case Intrinsic::x86_avx2_psrai_w:
20015 case Intrinsic::x86_avx2_psrai_d:
20016 case Intrinsic::x86_sse2_psra_w:
20017 case Intrinsic::x86_sse2_psra_d:
20018 case Intrinsic::x86_avx2_psra_w:
20019 case Intrinsic::x86_avx2_psra_d: {
20020 SDValue Op0 = N->getOperand(1);
20021 SDValue Op1 = N->getOperand(2);
20022 EVT VT = Op0.getValueType();
20023 assert(VT.isVector() && "Expected a vector type!");
20025 if (isa<BuildVectorSDNode>(Op1))
20026 Op1 = Op1.getOperand(0);
20028 if (!isa<ConstantSDNode>(Op1))
20031 EVT SVT = VT.getVectorElementType();
20032 unsigned SVTBits = SVT.getSizeInBits();
20034 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20035 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20036 uint64_t ShAmt = C.getZExtValue();
20038 // Don't try to convert this shift into a ISD::SRA if the shift
20039 // count is bigger than or equal to the element size.
20040 if (ShAmt >= SVTBits)
20043 // Trivial case: if the shift count is zero, then fold this
20044 // into the first operand.
20048 // Replace this packed shift intrinsic with a target independent
20050 SDValue Splat = DAG.getConstant(C, VT);
20051 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20056 /// PerformMulCombine - Optimize a single multiply with constant into two
20057 /// in order to implement it with two cheaper instructions, e.g.
20058 /// LEA + SHL, LEA + LEA.
20059 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20060 TargetLowering::DAGCombinerInfo &DCI) {
20061 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20064 EVT VT = N->getValueType(0);
20065 if (VT != MVT::i64)
20068 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20071 uint64_t MulAmt = C->getZExtValue();
20072 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20075 uint64_t MulAmt1 = 0;
20076 uint64_t MulAmt2 = 0;
20077 if ((MulAmt % 9) == 0) {
20079 MulAmt2 = MulAmt / 9;
20080 } else if ((MulAmt % 5) == 0) {
20082 MulAmt2 = MulAmt / 5;
20083 } else if ((MulAmt % 3) == 0) {
20085 MulAmt2 = MulAmt / 3;
20088 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20091 if (isPowerOf2_64(MulAmt2) &&
20092 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20093 // If second multiplifer is pow2, issue it first. We want the multiply by
20094 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20096 std::swap(MulAmt1, MulAmt2);
20099 if (isPowerOf2_64(MulAmt1))
20100 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20101 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20103 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20104 DAG.getConstant(MulAmt1, VT));
20106 if (isPowerOf2_64(MulAmt2))
20107 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20108 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20110 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20111 DAG.getConstant(MulAmt2, VT));
20113 // Do not add new nodes to DAG combiner worklist.
20114 DCI.CombineTo(N, NewMul, false);
20119 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20120 SDValue N0 = N->getOperand(0);
20121 SDValue N1 = N->getOperand(1);
20122 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20123 EVT VT = N0.getValueType();
20125 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20126 // since the result of setcc_c is all zero's or all ones.
20127 if (VT.isInteger() && !VT.isVector() &&
20128 N1C && N0.getOpcode() == ISD::AND &&
20129 N0.getOperand(1).getOpcode() == ISD::Constant) {
20130 SDValue N00 = N0.getOperand(0);
20131 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20132 ((N00.getOpcode() == ISD::ANY_EXTEND ||
20133 N00.getOpcode() == ISD::ZERO_EXTEND) &&
20134 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20135 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20136 APInt ShAmt = N1C->getAPIntValue();
20137 Mask = Mask.shl(ShAmt);
20139 return DAG.getNode(ISD::AND, SDLoc(N), VT,
20140 N00, DAG.getConstant(Mask, VT));
20144 // Hardware support for vector shifts is sparse which makes us scalarize the
20145 // vector operations in many cases. Also, on sandybridge ADD is faster than
20147 // (shl V, 1) -> add V,V
20148 if (isSplatVector(N1.getNode())) {
20149 assert(N0.getValueType().isVector() && "Invalid vector shift type");
20150 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
20151 // We shift all of the values by one. In many cases we do not have
20152 // hardware support for this operation. This is better expressed as an ADD
20154 if (N1C && (1 == N1C->getZExtValue())) {
20155 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20162 /// \brief Returns a vector of 0s if the node in input is a vector logical
20163 /// shift by a constant amount which is known to be bigger than or equal
20164 /// to the vector element size in bits.
20165 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20166 const X86Subtarget *Subtarget) {
20167 EVT VT = N->getValueType(0);
20169 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20170 (!Subtarget->hasInt256() ||
20171 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20174 SDValue Amt = N->getOperand(1);
20176 if (isSplatVector(Amt.getNode())) {
20177 SDValue SclrAmt = Amt->getOperand(0);
20178 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
20179 APInt ShiftAmt = C->getAPIntValue();
20180 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20182 // SSE2/AVX2 logical shifts always return a vector of 0s
20183 // if the shift amount is bigger than or equal to
20184 // the element size. The constant shift amount will be
20185 // encoded as a 8-bit immediate.
20186 if (ShiftAmt.trunc(8).uge(MaxAmount))
20187 return getZeroVector(VT, Subtarget, DAG, DL);
20194 /// PerformShiftCombine - Combine shifts.
20195 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20196 TargetLowering::DAGCombinerInfo &DCI,
20197 const X86Subtarget *Subtarget) {
20198 if (N->getOpcode() == ISD::SHL) {
20199 SDValue V = PerformSHLCombine(N, DAG);
20200 if (V.getNode()) return V;
20203 if (N->getOpcode() != ISD::SRA) {
20204 // Try to fold this logical shift into a zero vector.
20205 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20206 if (V.getNode()) return V;
20212 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
20213 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20214 // and friends. Likewise for OR -> CMPNEQSS.
20215 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20216 TargetLowering::DAGCombinerInfo &DCI,
20217 const X86Subtarget *Subtarget) {
20220 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20221 // we're requiring SSE2 for both.
20222 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20223 SDValue N0 = N->getOperand(0);
20224 SDValue N1 = N->getOperand(1);
20225 SDValue CMP0 = N0->getOperand(1);
20226 SDValue CMP1 = N1->getOperand(1);
20229 // The SETCCs should both refer to the same CMP.
20230 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20233 SDValue CMP00 = CMP0->getOperand(0);
20234 SDValue CMP01 = CMP0->getOperand(1);
20235 EVT VT = CMP00.getValueType();
20237 if (VT == MVT::f32 || VT == MVT::f64) {
20238 bool ExpectingFlags = false;
20239 // Check for any users that want flags:
20240 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20241 !ExpectingFlags && UI != UE; ++UI)
20242 switch (UI->getOpcode()) {
20247 ExpectingFlags = true;
20249 case ISD::CopyToReg:
20250 case ISD::SIGN_EXTEND:
20251 case ISD::ZERO_EXTEND:
20252 case ISD::ANY_EXTEND:
20256 if (!ExpectingFlags) {
20257 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20258 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20260 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20261 X86::CondCode tmp = cc0;
20266 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
20267 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20268 // FIXME: need symbolic constants for these magic numbers.
20269 // See X86ATTInstPrinter.cpp:printSSECC().
20270 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20271 if (Subtarget->hasAVX512()) {
20272 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20273 CMP01, DAG.getConstant(x86cc, MVT::i8));
20274 if (N->getValueType(0) != MVT::i1)
20275 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20279 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20280 CMP00.getValueType(), CMP00, CMP01,
20281 DAG.getConstant(x86cc, MVT::i8));
20283 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20284 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20286 if (is64BitFP && !Subtarget->is64Bit()) {
20287 // On a 32-bit target, we cannot bitcast the 64-bit float to a
20288 // 64-bit integer, since that's not a legal type. Since
20289 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20290 // bits, but can do this little dance to extract the lowest 32 bits
20291 // and work with those going forward.
20292 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20294 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20296 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20297 Vector32, DAG.getIntPtrConstant(0));
20301 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20302 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20303 DAG.getConstant(1, IntVT));
20304 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20305 return OneBitOfTruth;
20313 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20314 /// so it can be folded inside ANDNP.
20315 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20316 EVT VT = N->getValueType(0);
20318 // Match direct AllOnes for 128 and 256-bit vectors
20319 if (ISD::isBuildVectorAllOnes(N))
20322 // Look through a bit convert.
20323 if (N->getOpcode() == ISD::BITCAST)
20324 N = N->getOperand(0).getNode();
20326 // Sometimes the operand may come from a insert_subvector building a 256-bit
20328 if (VT.is256BitVector() &&
20329 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20330 SDValue V1 = N->getOperand(0);
20331 SDValue V2 = N->getOperand(1);
20333 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20334 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20335 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20336 ISD::isBuildVectorAllOnes(V2.getNode()))
20343 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20344 // register. In most cases we actually compare or select YMM-sized registers
20345 // and mixing the two types creates horrible code. This method optimizes
20346 // some of the transition sequences.
20347 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20348 TargetLowering::DAGCombinerInfo &DCI,
20349 const X86Subtarget *Subtarget) {
20350 EVT VT = N->getValueType(0);
20351 if (!VT.is256BitVector())
20354 assert((N->getOpcode() == ISD::ANY_EXTEND ||
20355 N->getOpcode() == ISD::ZERO_EXTEND ||
20356 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20358 SDValue Narrow = N->getOperand(0);
20359 EVT NarrowVT = Narrow->getValueType(0);
20360 if (!NarrowVT.is128BitVector())
20363 if (Narrow->getOpcode() != ISD::XOR &&
20364 Narrow->getOpcode() != ISD::AND &&
20365 Narrow->getOpcode() != ISD::OR)
20368 SDValue N0 = Narrow->getOperand(0);
20369 SDValue N1 = Narrow->getOperand(1);
20372 // The Left side has to be a trunc.
20373 if (N0.getOpcode() != ISD::TRUNCATE)
20376 // The type of the truncated inputs.
20377 EVT WideVT = N0->getOperand(0)->getValueType(0);
20381 // The right side has to be a 'trunc' or a constant vector.
20382 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20383 bool RHSConst = (isSplatVector(N1.getNode()) &&
20384 isa<ConstantSDNode>(N1->getOperand(0)));
20385 if (!RHSTrunc && !RHSConst)
20388 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20390 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20393 // Set N0 and N1 to hold the inputs to the new wide operation.
20394 N0 = N0->getOperand(0);
20396 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20397 N1->getOperand(0));
20398 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20399 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20400 } else if (RHSTrunc) {
20401 N1 = N1->getOperand(0);
20404 // Generate the wide operation.
20405 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20406 unsigned Opcode = N->getOpcode();
20408 case ISD::ANY_EXTEND:
20410 case ISD::ZERO_EXTEND: {
20411 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20412 APInt Mask = APInt::getAllOnesValue(InBits);
20413 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20414 return DAG.getNode(ISD::AND, DL, VT,
20415 Op, DAG.getConstant(Mask, VT));
20417 case ISD::SIGN_EXTEND:
20418 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20419 Op, DAG.getValueType(NarrowVT));
20421 llvm_unreachable("Unexpected opcode");
20425 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20426 TargetLowering::DAGCombinerInfo &DCI,
20427 const X86Subtarget *Subtarget) {
20428 EVT VT = N->getValueType(0);
20429 if (DCI.isBeforeLegalizeOps())
20432 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20436 // Create BEXTR instructions
20437 // BEXTR is ((X >> imm) & (2**size-1))
20438 if (VT == MVT::i32 || VT == MVT::i64) {
20439 SDValue N0 = N->getOperand(0);
20440 SDValue N1 = N->getOperand(1);
20443 // Check for BEXTR.
20444 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20445 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20446 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20447 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20448 if (MaskNode && ShiftNode) {
20449 uint64_t Mask = MaskNode->getZExtValue();
20450 uint64_t Shift = ShiftNode->getZExtValue();
20451 if (isMask_64(Mask)) {
20452 uint64_t MaskSize = CountPopulation_64(Mask);
20453 if (Shift + MaskSize <= VT.getSizeInBits())
20454 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20455 DAG.getConstant(Shift | (MaskSize << 8), VT));
20463 // Want to form ANDNP nodes:
20464 // 1) In the hopes of then easily combining them with OR and AND nodes
20465 // to form PBLEND/PSIGN.
20466 // 2) To match ANDN packed intrinsics
20467 if (VT != MVT::v2i64 && VT != MVT::v4i64)
20470 SDValue N0 = N->getOperand(0);
20471 SDValue N1 = N->getOperand(1);
20474 // Check LHS for vnot
20475 if (N0.getOpcode() == ISD::XOR &&
20476 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20477 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20478 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20480 // Check RHS for vnot
20481 if (N1.getOpcode() == ISD::XOR &&
20482 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20483 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20484 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20489 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20490 TargetLowering::DAGCombinerInfo &DCI,
20491 const X86Subtarget *Subtarget) {
20492 if (DCI.isBeforeLegalizeOps())
20495 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20499 SDValue N0 = N->getOperand(0);
20500 SDValue N1 = N->getOperand(1);
20501 EVT VT = N->getValueType(0);
20503 // look for psign/blend
20504 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20505 if (!Subtarget->hasSSSE3() ||
20506 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20509 // Canonicalize pandn to RHS
20510 if (N0.getOpcode() == X86ISD::ANDNP)
20512 // or (and (m, y), (pandn m, x))
20513 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20514 SDValue Mask = N1.getOperand(0);
20515 SDValue X = N1.getOperand(1);
20517 if (N0.getOperand(0) == Mask)
20518 Y = N0.getOperand(1);
20519 if (N0.getOperand(1) == Mask)
20520 Y = N0.getOperand(0);
20522 // Check to see if the mask appeared in both the AND and ANDNP and
20526 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20527 // Look through mask bitcast.
20528 if (Mask.getOpcode() == ISD::BITCAST)
20529 Mask = Mask.getOperand(0);
20530 if (X.getOpcode() == ISD::BITCAST)
20531 X = X.getOperand(0);
20532 if (Y.getOpcode() == ISD::BITCAST)
20533 Y = Y.getOperand(0);
20535 EVT MaskVT = Mask.getValueType();
20537 // Validate that the Mask operand is a vector sra node.
20538 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20539 // there is no psrai.b
20540 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20541 unsigned SraAmt = ~0;
20542 if (Mask.getOpcode() == ISD::SRA) {
20543 SDValue Amt = Mask.getOperand(1);
20544 if (isSplatVector(Amt.getNode())) {
20545 SDValue SclrAmt = Amt->getOperand(0);
20546 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
20547 SraAmt = C->getZExtValue();
20549 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20550 SDValue SraC = Mask.getOperand(1);
20551 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
20553 if ((SraAmt + 1) != EltBits)
20558 // Now we know we at least have a plendvb with the mask val. See if
20559 // we can form a psignb/w/d.
20560 // psign = x.type == y.type == mask.type && y = sub(0, x);
20561 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20562 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20563 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20564 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20565 "Unsupported VT for PSIGN");
20566 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20567 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20569 // PBLENDVB only available on SSE 4.1
20570 if (!Subtarget->hasSSE41())
20573 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20575 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20576 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20577 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20578 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20579 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20583 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20586 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20587 MachineFunction &MF = DAG.getMachineFunction();
20588 bool OptForSize = MF.getFunction()->getAttributes().
20589 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20591 // SHLD/SHRD instructions have lower register pressure, but on some
20592 // platforms they have higher latency than the equivalent
20593 // series of shifts/or that would otherwise be generated.
20594 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20595 // have higher latencies and we are not optimizing for size.
20596 if (!OptForSize && Subtarget->isSHLDSlow())
20599 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20601 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20603 if (!N0.hasOneUse() || !N1.hasOneUse())
20606 SDValue ShAmt0 = N0.getOperand(1);
20607 if (ShAmt0.getValueType() != MVT::i8)
20609 SDValue ShAmt1 = N1.getOperand(1);
20610 if (ShAmt1.getValueType() != MVT::i8)
20612 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20613 ShAmt0 = ShAmt0.getOperand(0);
20614 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20615 ShAmt1 = ShAmt1.getOperand(0);
20618 unsigned Opc = X86ISD::SHLD;
20619 SDValue Op0 = N0.getOperand(0);
20620 SDValue Op1 = N1.getOperand(0);
20621 if (ShAmt0.getOpcode() == ISD::SUB) {
20622 Opc = X86ISD::SHRD;
20623 std::swap(Op0, Op1);
20624 std::swap(ShAmt0, ShAmt1);
20627 unsigned Bits = VT.getSizeInBits();
20628 if (ShAmt1.getOpcode() == ISD::SUB) {
20629 SDValue Sum = ShAmt1.getOperand(0);
20630 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20631 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20632 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
20633 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
20634 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
20635 return DAG.getNode(Opc, DL, VT,
20637 DAG.getNode(ISD::TRUNCATE, DL,
20640 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
20641 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
20643 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
20644 return DAG.getNode(Opc, DL, VT,
20645 N0.getOperand(0), N1.getOperand(0),
20646 DAG.getNode(ISD::TRUNCATE, DL,
20653 // Generate NEG and CMOV for integer abs.
20654 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
20655 EVT VT = N->getValueType(0);
20657 // Since X86 does not have CMOV for 8-bit integer, we don't convert
20658 // 8-bit integer abs to NEG and CMOV.
20659 if (VT.isInteger() && VT.getSizeInBits() == 8)
20662 SDValue N0 = N->getOperand(0);
20663 SDValue N1 = N->getOperand(1);
20666 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
20667 // and change it to SUB and CMOV.
20668 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
20669 N0.getOpcode() == ISD::ADD &&
20670 N0.getOperand(1) == N1 &&
20671 N1.getOpcode() == ISD::SRA &&
20672 N1.getOperand(0) == N0.getOperand(0))
20673 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
20674 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
20675 // Generate SUB & CMOV.
20676 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
20677 DAG.getConstant(0, VT), N0.getOperand(0));
20679 SDValue Ops[] = { N0.getOperand(0), Neg,
20680 DAG.getConstant(X86::COND_GE, MVT::i8),
20681 SDValue(Neg.getNode(), 1) };
20682 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
20687 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20688 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20689 TargetLowering::DAGCombinerInfo &DCI,
20690 const X86Subtarget *Subtarget) {
20691 if (DCI.isBeforeLegalizeOps())
20694 if (Subtarget->hasCMov()) {
20695 SDValue RV = performIntegerAbsCombine(N, DAG);
20703 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20704 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20705 TargetLowering::DAGCombinerInfo &DCI,
20706 const X86Subtarget *Subtarget) {
20707 LoadSDNode *Ld = cast<LoadSDNode>(N);
20708 EVT RegVT = Ld->getValueType(0);
20709 EVT MemVT = Ld->getMemoryVT();
20711 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20712 unsigned RegSz = RegVT.getSizeInBits();
20714 // On Sandybridge unaligned 256bit loads are inefficient.
20715 ISD::LoadExtType Ext = Ld->getExtensionType();
20716 unsigned Alignment = Ld->getAlignment();
20717 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20718 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20719 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20720 unsigned NumElems = RegVT.getVectorNumElements();
20724 SDValue Ptr = Ld->getBasePtr();
20725 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20727 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20729 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20730 Ld->getPointerInfo(), Ld->isVolatile(),
20731 Ld->isNonTemporal(), Ld->isInvariant(),
20733 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20734 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20735 Ld->getPointerInfo(), Ld->isVolatile(),
20736 Ld->isNonTemporal(), Ld->isInvariant(),
20737 std::min(16U, Alignment));
20738 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20740 Load2.getValue(1));
20742 SDValue NewVec = DAG.getUNDEF(RegVT);
20743 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20744 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20745 return DCI.CombineTo(N, NewVec, TF, true);
20748 // If this is a vector EXT Load then attempt to optimize it using a
20749 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20750 // expansion is still better than scalar code.
20751 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20752 // emit a shuffle and a arithmetic shift.
20753 // TODO: It is possible to support ZExt by zeroing the undef values
20754 // during the shuffle phase or after the shuffle.
20755 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20756 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20757 assert(MemVT != RegVT && "Cannot extend to the same type");
20758 assert(MemVT.isVector() && "Must load a vector from memory");
20760 unsigned NumElems = RegVT.getVectorNumElements();
20761 unsigned MemSz = MemVT.getSizeInBits();
20762 assert(RegSz > MemSz && "Register size must be greater than the mem size");
20764 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20767 // All sizes must be a power of two.
20768 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20771 // Attempt to load the original value using scalar loads.
20772 // Find the largest scalar type that divides the total loaded size.
20773 MVT SclrLoadTy = MVT::i8;
20774 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20775 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20776 MVT Tp = (MVT::SimpleValueType)tp;
20777 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20782 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20783 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20785 SclrLoadTy = MVT::f64;
20787 // Calculate the number of scalar loads that we need to perform
20788 // in order to load our vector from memory.
20789 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20790 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20793 unsigned loadRegZize = RegSz;
20794 if (Ext == ISD::SEXTLOAD && RegSz == 256)
20797 // Represent our vector as a sequence of elements which are the
20798 // largest scalar that we can load.
20799 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20800 loadRegZize/SclrLoadTy.getSizeInBits());
20802 // Represent the data using the same element type that is stored in
20803 // memory. In practice, we ''widen'' MemVT.
20805 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20806 loadRegZize/MemVT.getScalarType().getSizeInBits());
20808 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20809 "Invalid vector type");
20811 // We can't shuffle using an illegal type.
20812 if (!TLI.isTypeLegal(WideVecVT))
20815 SmallVector<SDValue, 8> Chains;
20816 SDValue Ptr = Ld->getBasePtr();
20817 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20818 TLI.getPointerTy());
20819 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20821 for (unsigned i = 0; i < NumLoads; ++i) {
20822 // Perform a single load.
20823 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20824 Ptr, Ld->getPointerInfo(),
20825 Ld->isVolatile(), Ld->isNonTemporal(),
20826 Ld->isInvariant(), Ld->getAlignment());
20827 Chains.push_back(ScalarLoad.getValue(1));
20828 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20829 // another round of DAGCombining.
20831 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20833 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20834 ScalarLoad, DAG.getIntPtrConstant(i));
20836 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20839 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20841 // Bitcast the loaded value to a vector of the original element type, in
20842 // the size of the target vector type.
20843 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20844 unsigned SizeRatio = RegSz/MemSz;
20846 if (Ext == ISD::SEXTLOAD) {
20847 // If we have SSE4.1 we can directly emit a VSEXT node.
20848 if (Subtarget->hasSSE41()) {
20849 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20850 return DCI.CombineTo(N, Sext, TF, true);
20853 // Otherwise we'll shuffle the small elements in the high bits of the
20854 // larger type and perform an arithmetic shift. If the shift is not legal
20855 // it's better to scalarize.
20856 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20859 // Redistribute the loaded elements into the different locations.
20860 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20861 for (unsigned i = 0; i != NumElems; ++i)
20862 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20864 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20865 DAG.getUNDEF(WideVecVT),
20868 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20870 // Build the arithmetic shift.
20871 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20872 MemVT.getVectorElementType().getSizeInBits();
20873 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20874 DAG.getConstant(Amt, RegVT));
20876 return DCI.CombineTo(N, Shuff, TF, true);
20879 // Redistribute the loaded elements into the different locations.
20880 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20881 for (unsigned i = 0; i != NumElems; ++i)
20882 ShuffleVec[i*SizeRatio] = i;
20884 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20885 DAG.getUNDEF(WideVecVT),
20888 // Bitcast to the requested type.
20889 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20890 // Replace the original load with the new sequence
20891 // and return the new chain.
20892 return DCI.CombineTo(N, Shuff, TF, true);
20898 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
20899 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
20900 const X86Subtarget *Subtarget) {
20901 StoreSDNode *St = cast<StoreSDNode>(N);
20902 EVT VT = St->getValue().getValueType();
20903 EVT StVT = St->getMemoryVT();
20905 SDValue StoredVal = St->getOperand(1);
20906 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20908 // If we are saving a concatenation of two XMM registers, perform two stores.
20909 // On Sandy Bridge, 256-bit memory operations are executed by two
20910 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20911 // memory operation.
20912 unsigned Alignment = St->getAlignment();
20913 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20914 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20915 StVT == VT && !IsAligned) {
20916 unsigned NumElems = VT.getVectorNumElements();
20920 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20921 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20923 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20924 SDValue Ptr0 = St->getBasePtr();
20925 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20927 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20928 St->getPointerInfo(), St->isVolatile(),
20929 St->isNonTemporal(), Alignment);
20930 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20931 St->getPointerInfo(), St->isVolatile(),
20932 St->isNonTemporal(),
20933 std::min(16U, Alignment));
20934 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20937 // Optimize trunc store (of multiple scalars) to shuffle and store.
20938 // First, pack all of the elements in one place. Next, store to memory
20939 // in fewer chunks.
20940 if (St->isTruncatingStore() && VT.isVector()) {
20941 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20942 unsigned NumElems = VT.getVectorNumElements();
20943 assert(StVT != VT && "Cannot truncate to the same type");
20944 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20945 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20947 // From, To sizes and ElemCount must be pow of two
20948 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20949 // We are going to use the original vector elt for storing.
20950 // Accumulated smaller vector elements must be a multiple of the store size.
20951 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
20953 unsigned SizeRatio = FromSz / ToSz;
20955 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
20957 // Create a type on which we perform the shuffle
20958 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
20959 StVT.getScalarType(), NumElems*SizeRatio);
20961 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
20963 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
20964 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20965 for (unsigned i = 0; i != NumElems; ++i)
20966 ShuffleVec[i] = i * SizeRatio;
20968 // Can't shuffle using an illegal type.
20969 if (!TLI.isTypeLegal(WideVecVT))
20972 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
20973 DAG.getUNDEF(WideVecVT),
20975 // At this point all of the data is stored at the bottom of the
20976 // register. We now need to save it to mem.
20978 // Find the largest store unit
20979 MVT StoreType = MVT::i8;
20980 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20981 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20982 MVT Tp = (MVT::SimpleValueType)tp;
20983 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
20987 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20988 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
20989 (64 <= NumElems * ToSz))
20990 StoreType = MVT::f64;
20992 // Bitcast the original vector into a vector of store-size units
20993 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
20994 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
20995 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
20996 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
20997 SmallVector<SDValue, 8> Chains;
20998 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
20999 TLI.getPointerTy());
21000 SDValue Ptr = St->getBasePtr();
21002 // Perform one or more big stores into memory.
21003 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21004 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21005 StoreType, ShuffWide,
21006 DAG.getIntPtrConstant(i));
21007 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21008 St->getPointerInfo(), St->isVolatile(),
21009 St->isNonTemporal(), St->getAlignment());
21010 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21011 Chains.push_back(Ch);
21014 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21017 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
21018 // the FP state in cases where an emms may be missing.
21019 // A preferable solution to the general problem is to figure out the right
21020 // places to insert EMMS. This qualifies as a quick hack.
21022 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21023 if (VT.getSizeInBits() != 64)
21026 const Function *F = DAG.getMachineFunction().getFunction();
21027 bool NoImplicitFloatOps = F->getAttributes().
21028 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21029 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21030 && Subtarget->hasSSE2();
21031 if ((VT.isVector() ||
21032 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21033 isa<LoadSDNode>(St->getValue()) &&
21034 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21035 St->getChain().hasOneUse() && !St->isVolatile()) {
21036 SDNode* LdVal = St->getValue().getNode();
21037 LoadSDNode *Ld = nullptr;
21038 int TokenFactorIndex = -1;
21039 SmallVector<SDValue, 8> Ops;
21040 SDNode* ChainVal = St->getChain().getNode();
21041 // Must be a store of a load. We currently handle two cases: the load
21042 // is a direct child, and it's under an intervening TokenFactor. It is
21043 // possible to dig deeper under nested TokenFactors.
21044 if (ChainVal == LdVal)
21045 Ld = cast<LoadSDNode>(St->getChain());
21046 else if (St->getValue().hasOneUse() &&
21047 ChainVal->getOpcode() == ISD::TokenFactor) {
21048 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21049 if (ChainVal->getOperand(i).getNode() == LdVal) {
21050 TokenFactorIndex = i;
21051 Ld = cast<LoadSDNode>(St->getValue());
21053 Ops.push_back(ChainVal->getOperand(i));
21057 if (!Ld || !ISD::isNormalLoad(Ld))
21060 // If this is not the MMX case, i.e. we are just turning i64 load/store
21061 // into f64 load/store, avoid the transformation if there are multiple
21062 // uses of the loaded value.
21063 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21068 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21069 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21071 if (Subtarget->is64Bit() || F64IsLegal) {
21072 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21073 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21074 Ld->getPointerInfo(), Ld->isVolatile(),
21075 Ld->isNonTemporal(), Ld->isInvariant(),
21076 Ld->getAlignment());
21077 SDValue NewChain = NewLd.getValue(1);
21078 if (TokenFactorIndex != -1) {
21079 Ops.push_back(NewChain);
21080 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21082 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21083 St->getPointerInfo(),
21084 St->isVolatile(), St->isNonTemporal(),
21085 St->getAlignment());
21088 // Otherwise, lower to two pairs of 32-bit loads / stores.
21089 SDValue LoAddr = Ld->getBasePtr();
21090 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21091 DAG.getConstant(4, MVT::i32));
21093 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21094 Ld->getPointerInfo(),
21095 Ld->isVolatile(), Ld->isNonTemporal(),
21096 Ld->isInvariant(), Ld->getAlignment());
21097 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21098 Ld->getPointerInfo().getWithOffset(4),
21099 Ld->isVolatile(), Ld->isNonTemporal(),
21101 MinAlign(Ld->getAlignment(), 4));
21103 SDValue NewChain = LoLd.getValue(1);
21104 if (TokenFactorIndex != -1) {
21105 Ops.push_back(LoLd);
21106 Ops.push_back(HiLd);
21107 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21110 LoAddr = St->getBasePtr();
21111 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21112 DAG.getConstant(4, MVT::i32));
21114 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21115 St->getPointerInfo(),
21116 St->isVolatile(), St->isNonTemporal(),
21117 St->getAlignment());
21118 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21119 St->getPointerInfo().getWithOffset(4),
21121 St->isNonTemporal(),
21122 MinAlign(St->getAlignment(), 4));
21123 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21128 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21129 /// and return the operands for the horizontal operation in LHS and RHS. A
21130 /// horizontal operation performs the binary operation on successive elements
21131 /// of its first operand, then on successive elements of its second operand,
21132 /// returning the resulting values in a vector. For example, if
21133 /// A = < float a0, float a1, float a2, float a3 >
21135 /// B = < float b0, float b1, float b2, float b3 >
21136 /// then the result of doing a horizontal operation on A and B is
21137 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21138 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21139 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21140 /// set to A, RHS to B, and the routine returns 'true'.
21141 /// Note that the binary operation should have the property that if one of the
21142 /// operands is UNDEF then the result is UNDEF.
21143 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21144 // Look for the following pattern: if
21145 // A = < float a0, float a1, float a2, float a3 >
21146 // B = < float b0, float b1, float b2, float b3 >
21148 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21149 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21150 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21151 // which is A horizontal-op B.
21153 // At least one of the operands should be a vector shuffle.
21154 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21155 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21158 MVT VT = LHS.getSimpleValueType();
21160 assert((VT.is128BitVector() || VT.is256BitVector()) &&
21161 "Unsupported vector type for horizontal add/sub");
21163 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21164 // operate independently on 128-bit lanes.
21165 unsigned NumElts = VT.getVectorNumElements();
21166 unsigned NumLanes = VT.getSizeInBits()/128;
21167 unsigned NumLaneElts = NumElts / NumLanes;
21168 assert((NumLaneElts % 2 == 0) &&
21169 "Vector type should have an even number of elements in each lane");
21170 unsigned HalfLaneElts = NumLaneElts/2;
21172 // View LHS in the form
21173 // LHS = VECTOR_SHUFFLE A, B, LMask
21174 // If LHS is not a shuffle then pretend it is the shuffle
21175 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21176 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21179 SmallVector<int, 16> LMask(NumElts);
21180 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21181 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21182 A = LHS.getOperand(0);
21183 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21184 B = LHS.getOperand(1);
21185 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21186 std::copy(Mask.begin(), Mask.end(), LMask.begin());
21188 if (LHS.getOpcode() != ISD::UNDEF)
21190 for (unsigned i = 0; i != NumElts; ++i)
21194 // Likewise, view RHS in the form
21195 // RHS = VECTOR_SHUFFLE C, D, RMask
21197 SmallVector<int, 16> RMask(NumElts);
21198 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21199 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21200 C = RHS.getOperand(0);
21201 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21202 D = RHS.getOperand(1);
21203 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21204 std::copy(Mask.begin(), Mask.end(), RMask.begin());
21206 if (RHS.getOpcode() != ISD::UNDEF)
21208 for (unsigned i = 0; i != NumElts; ++i)
21212 // Check that the shuffles are both shuffling the same vectors.
21213 if (!(A == C && B == D) && !(A == D && B == C))
21216 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21217 if (!A.getNode() && !B.getNode())
21220 // If A and B occur in reverse order in RHS, then "swap" them (which means
21221 // rewriting the mask).
21223 CommuteVectorShuffleMask(RMask, NumElts);
21225 // At this point LHS and RHS are equivalent to
21226 // LHS = VECTOR_SHUFFLE A, B, LMask
21227 // RHS = VECTOR_SHUFFLE A, B, RMask
21228 // Check that the masks correspond to performing a horizontal operation.
21229 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21230 for (unsigned i = 0; i != NumLaneElts; ++i) {
21231 int LIdx = LMask[i+l], RIdx = RMask[i+l];
21233 // Ignore any UNDEF components.
21234 if (LIdx < 0 || RIdx < 0 ||
21235 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21236 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21239 // Check that successive elements are being operated on. If not, this is
21240 // not a horizontal operation.
21241 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21242 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21243 if (!(LIdx == Index && RIdx == Index + 1) &&
21244 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21249 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21250 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21254 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21255 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21256 const X86Subtarget *Subtarget) {
21257 EVT VT = N->getValueType(0);
21258 SDValue LHS = N->getOperand(0);
21259 SDValue RHS = N->getOperand(1);
21261 // Try to synthesize horizontal adds from adds of shuffles.
21262 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21263 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21264 isHorizontalBinOp(LHS, RHS, true))
21265 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21269 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21270 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21271 const X86Subtarget *Subtarget) {
21272 EVT VT = N->getValueType(0);
21273 SDValue LHS = N->getOperand(0);
21274 SDValue RHS = N->getOperand(1);
21276 // Try to synthesize horizontal subs from subs of shuffles.
21277 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21278 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21279 isHorizontalBinOp(LHS, RHS, false))
21280 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21284 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21285 /// X86ISD::FXOR nodes.
21286 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21287 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21288 // F[X]OR(0.0, x) -> x
21289 // F[X]OR(x, 0.0) -> x
21290 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21291 if (C->getValueAPF().isPosZero())
21292 return N->getOperand(1);
21293 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21294 if (C->getValueAPF().isPosZero())
21295 return N->getOperand(0);
21299 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21300 /// X86ISD::FMAX nodes.
21301 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21302 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21304 // Only perform optimizations if UnsafeMath is used.
21305 if (!DAG.getTarget().Options.UnsafeFPMath)
21308 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21309 // into FMINC and FMAXC, which are Commutative operations.
21310 unsigned NewOp = 0;
21311 switch (N->getOpcode()) {
21312 default: llvm_unreachable("unknown opcode");
21313 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
21314 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
21317 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21318 N->getOperand(0), N->getOperand(1));
21321 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21322 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21323 // FAND(0.0, x) -> 0.0
21324 // FAND(x, 0.0) -> 0.0
21325 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21326 if (C->getValueAPF().isPosZero())
21327 return N->getOperand(0);
21328 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21329 if (C->getValueAPF().isPosZero())
21330 return N->getOperand(1);
21334 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21335 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21336 // FANDN(x, 0.0) -> 0.0
21337 // FANDN(0.0, x) -> x
21338 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21339 if (C->getValueAPF().isPosZero())
21340 return N->getOperand(1);
21341 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21342 if (C->getValueAPF().isPosZero())
21343 return N->getOperand(1);
21347 static SDValue PerformBTCombine(SDNode *N,
21349 TargetLowering::DAGCombinerInfo &DCI) {
21350 // BT ignores high bits in the bit index operand.
21351 SDValue Op1 = N->getOperand(1);
21352 if (Op1.hasOneUse()) {
21353 unsigned BitWidth = Op1.getValueSizeInBits();
21354 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21355 APInt KnownZero, KnownOne;
21356 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21357 !DCI.isBeforeLegalizeOps());
21358 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21359 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21360 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21361 DCI.CommitTargetLoweringOpt(TLO);
21366 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21367 SDValue Op = N->getOperand(0);
21368 if (Op.getOpcode() == ISD::BITCAST)
21369 Op = Op.getOperand(0);
21370 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21371 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21372 VT.getVectorElementType().getSizeInBits() ==
21373 OpVT.getVectorElementType().getSizeInBits()) {
21374 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21379 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21380 const X86Subtarget *Subtarget) {
21381 EVT VT = N->getValueType(0);
21382 if (!VT.isVector())
21385 SDValue N0 = N->getOperand(0);
21386 SDValue N1 = N->getOperand(1);
21387 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21390 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21391 // both SSE and AVX2 since there is no sign-extended shift right
21392 // operation on a vector with 64-bit elements.
21393 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21394 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21395 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21396 N0.getOpcode() == ISD::SIGN_EXTEND)) {
21397 SDValue N00 = N0.getOperand(0);
21399 // EXTLOAD has a better solution on AVX2,
21400 // it may be replaced with X86ISD::VSEXT node.
21401 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21402 if (!ISD::isNormalLoad(N00.getNode()))
21405 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21406 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21408 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21414 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21415 TargetLowering::DAGCombinerInfo &DCI,
21416 const X86Subtarget *Subtarget) {
21417 if (!DCI.isBeforeLegalizeOps())
21420 if (!Subtarget->hasFp256())
21423 EVT VT = N->getValueType(0);
21424 if (VT.isVector() && VT.getSizeInBits() == 256) {
21425 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21433 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21434 const X86Subtarget* Subtarget) {
21436 EVT VT = N->getValueType(0);
21438 // Let legalize expand this if it isn't a legal type yet.
21439 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21442 EVT ScalarVT = VT.getScalarType();
21443 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21444 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21447 SDValue A = N->getOperand(0);
21448 SDValue B = N->getOperand(1);
21449 SDValue C = N->getOperand(2);
21451 bool NegA = (A.getOpcode() == ISD::FNEG);
21452 bool NegB = (B.getOpcode() == ISD::FNEG);
21453 bool NegC = (C.getOpcode() == ISD::FNEG);
21455 // Negative multiplication when NegA xor NegB
21456 bool NegMul = (NegA != NegB);
21458 A = A.getOperand(0);
21460 B = B.getOperand(0);
21462 C = C.getOperand(0);
21466 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21468 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21470 return DAG.getNode(Opcode, dl, VT, A, B, C);
21473 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21474 TargetLowering::DAGCombinerInfo &DCI,
21475 const X86Subtarget *Subtarget) {
21476 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
21477 // (and (i32 x86isd::setcc_carry), 1)
21478 // This eliminates the zext. This transformation is necessary because
21479 // ISD::SETCC is always legalized to i8.
21481 SDValue N0 = N->getOperand(0);
21482 EVT VT = N->getValueType(0);
21484 if (N0.getOpcode() == ISD::AND &&
21486 N0.getOperand(0).hasOneUse()) {
21487 SDValue N00 = N0.getOperand(0);
21488 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21489 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21490 if (!C || C->getZExtValue() != 1)
21492 return DAG.getNode(ISD::AND, dl, VT,
21493 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21494 N00.getOperand(0), N00.getOperand(1)),
21495 DAG.getConstant(1, VT));
21499 if (N0.getOpcode() == ISD::TRUNCATE &&
21501 N0.getOperand(0).hasOneUse()) {
21502 SDValue N00 = N0.getOperand(0);
21503 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21504 return DAG.getNode(ISD::AND, dl, VT,
21505 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21506 N00.getOperand(0), N00.getOperand(1)),
21507 DAG.getConstant(1, VT));
21510 if (VT.is256BitVector()) {
21511 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21519 // Optimize x == -y --> x+y == 0
21520 // x != -y --> x+y != 0
21521 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21522 const X86Subtarget* Subtarget) {
21523 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21524 SDValue LHS = N->getOperand(0);
21525 SDValue RHS = N->getOperand(1);
21526 EVT VT = N->getValueType(0);
21529 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21530 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21531 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21532 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21533 LHS.getValueType(), RHS, LHS.getOperand(1));
21534 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21535 addV, DAG.getConstant(0, addV.getValueType()), CC);
21537 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21538 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21539 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21540 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21541 RHS.getValueType(), LHS, RHS.getOperand(1));
21542 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21543 addV, DAG.getConstant(0, addV.getValueType()), CC);
21546 if (VT.getScalarType() == MVT::i1) {
21547 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21548 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21549 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21550 if (!IsSEXT0 && !IsVZero0)
21552 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21553 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21554 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21556 if (!IsSEXT1 && !IsVZero1)
21559 if (IsSEXT0 && IsVZero1) {
21560 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21561 if (CC == ISD::SETEQ)
21562 return DAG.getNOT(DL, LHS.getOperand(0), VT);
21563 return LHS.getOperand(0);
21565 if (IsSEXT1 && IsVZero0) {
21566 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21567 if (CC == ISD::SETEQ)
21568 return DAG.getNOT(DL, RHS.getOperand(0), VT);
21569 return RHS.getOperand(0);
21576 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21577 const X86Subtarget *Subtarget) {
21579 MVT VT = N->getOperand(1)->getSimpleValueType(0);
21580 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21581 "X86insertps is only defined for v4x32");
21583 SDValue Ld = N->getOperand(1);
21584 if (MayFoldLoad(Ld)) {
21585 // Extract the countS bits from the immediate so we can get the proper
21586 // address when narrowing the vector load to a specific element.
21587 // When the second source op is a memory address, interps doesn't use
21588 // countS and just gets an f32 from that address.
21589 unsigned DestIndex =
21590 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21591 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21595 // Create this as a scalar to vector to match the instruction pattern.
21596 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21597 // countS bits are ignored when loading from memory on insertps, which
21598 // means we don't need to explicitly set them to 0.
21599 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21600 LoadScalarToVector, N->getOperand(2));
21603 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21604 // as "sbb reg,reg", since it can be extended without zext and produces
21605 // an all-ones bit which is more useful than 0/1 in some cases.
21606 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21609 return DAG.getNode(ISD::AND, DL, VT,
21610 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21611 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21612 DAG.getConstant(1, VT));
21613 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21614 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21615 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21616 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21619 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21620 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21621 TargetLowering::DAGCombinerInfo &DCI,
21622 const X86Subtarget *Subtarget) {
21624 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21625 SDValue EFLAGS = N->getOperand(1);
21627 if (CC == X86::COND_A) {
21628 // Try to convert COND_A into COND_B in an attempt to facilitate
21629 // materializing "setb reg".
21631 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21632 // cannot take an immediate as its first operand.
21634 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21635 EFLAGS.getValueType().isInteger() &&
21636 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21637 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21638 EFLAGS.getNode()->getVTList(),
21639 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21640 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21641 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21645 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21646 // a zext and produces an all-ones bit which is more useful than 0/1 in some
21648 if (CC == X86::COND_B)
21649 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21653 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21654 if (Flags.getNode()) {
21655 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21656 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21662 // Optimize branch condition evaluation.
21664 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21665 TargetLowering::DAGCombinerInfo &DCI,
21666 const X86Subtarget *Subtarget) {
21668 SDValue Chain = N->getOperand(0);
21669 SDValue Dest = N->getOperand(1);
21670 SDValue EFLAGS = N->getOperand(3);
21671 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21675 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21676 if (Flags.getNode()) {
21677 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21678 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21685 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21686 const X86TargetLowering *XTLI) {
21687 SDValue Op0 = N->getOperand(0);
21688 EVT InVT = Op0->getValueType(0);
21690 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21691 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21693 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21694 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21695 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21698 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21699 // a 32-bit target where SSE doesn't support i64->FP operations.
21700 if (Op0.getOpcode() == ISD::LOAD) {
21701 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21702 EVT VT = Ld->getValueType(0);
21703 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21704 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21705 !XTLI->getSubtarget()->is64Bit() &&
21707 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21708 Ld->getChain(), Op0, DAG);
21709 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21716 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21717 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21718 X86TargetLowering::DAGCombinerInfo &DCI) {
21719 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21720 // the result is either zero or one (depending on the input carry bit).
21721 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21722 if (X86::isZeroNode(N->getOperand(0)) &&
21723 X86::isZeroNode(N->getOperand(1)) &&
21724 // We don't have a good way to replace an EFLAGS use, so only do this when
21726 SDValue(N, 1).use_empty()) {
21728 EVT VT = N->getValueType(0);
21729 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21730 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21731 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21732 DAG.getConstant(X86::COND_B,MVT::i8),
21734 DAG.getConstant(1, VT));
21735 return DCI.CombineTo(N, Res1, CarryOut);
21741 // fold (add Y, (sete X, 0)) -> adc 0, Y
21742 // (add Y, (setne X, 0)) -> sbb -1, Y
21743 // (sub (sete X, 0), Y) -> sbb 0, Y
21744 // (sub (setne X, 0), Y) -> adc -1, Y
21745 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21748 // Look through ZExts.
21749 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21750 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21753 SDValue SetCC = Ext.getOperand(0);
21754 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21757 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21758 if (CC != X86::COND_E && CC != X86::COND_NE)
21761 SDValue Cmp = SetCC.getOperand(1);
21762 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21763 !X86::isZeroNode(Cmp.getOperand(1)) ||
21764 !Cmp.getOperand(0).getValueType().isInteger())
21767 SDValue CmpOp0 = Cmp.getOperand(0);
21768 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21769 DAG.getConstant(1, CmpOp0.getValueType()));
21771 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21772 if (CC == X86::COND_NE)
21773 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21774 DL, OtherVal.getValueType(), OtherVal,
21775 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21776 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21777 DL, OtherVal.getValueType(), OtherVal,
21778 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21781 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21782 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21783 const X86Subtarget *Subtarget) {
21784 EVT VT = N->getValueType(0);
21785 SDValue Op0 = N->getOperand(0);
21786 SDValue Op1 = N->getOperand(1);
21788 // Try to synthesize horizontal adds from adds of shuffles.
21789 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21790 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21791 isHorizontalBinOp(Op0, Op1, true))
21792 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21794 return OptimizeConditionalInDecrement(N, DAG);
21797 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21798 const X86Subtarget *Subtarget) {
21799 SDValue Op0 = N->getOperand(0);
21800 SDValue Op1 = N->getOperand(1);
21802 // X86 can't encode an immediate LHS of a sub. See if we can push the
21803 // negation into a preceding instruction.
21804 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21805 // If the RHS of the sub is a XOR with one use and a constant, invert the
21806 // immediate. Then add one to the LHS of the sub so we can turn
21807 // X-Y -> X+~Y+1, saving one register.
21808 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21809 isa<ConstantSDNode>(Op1.getOperand(1))) {
21810 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21811 EVT VT = Op0.getValueType();
21812 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21814 DAG.getConstant(~XorC, VT));
21815 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21816 DAG.getConstant(C->getAPIntValue()+1, VT));
21820 // Try to synthesize horizontal adds from adds of shuffles.
21821 EVT VT = N->getValueType(0);
21822 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21823 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21824 isHorizontalBinOp(Op0, Op1, true))
21825 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21827 return OptimizeConditionalInDecrement(N, DAG);
21830 /// performVZEXTCombine - Performs build vector combines
21831 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21832 TargetLowering::DAGCombinerInfo &DCI,
21833 const X86Subtarget *Subtarget) {
21834 // (vzext (bitcast (vzext (x)) -> (vzext x)
21835 SDValue In = N->getOperand(0);
21836 while (In.getOpcode() == ISD::BITCAST)
21837 In = In.getOperand(0);
21839 if (In.getOpcode() != X86ISD::VZEXT)
21842 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21846 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
21847 DAGCombinerInfo &DCI) const {
21848 SelectionDAG &DAG = DCI.DAG;
21849 switch (N->getOpcode()) {
21851 case ISD::EXTRACT_VECTOR_ELT:
21852 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
21854 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
21855 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
21856 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
21857 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
21858 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
21859 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
21862 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
21863 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
21864 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
21865 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
21866 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
21867 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
21868 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
21869 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
21870 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
21872 case X86ISD::FOR: return PerformFORCombine(N, DAG);
21874 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
21875 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
21876 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
21877 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
21878 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
21879 case ISD::ANY_EXTEND:
21880 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
21881 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
21882 case ISD::SIGN_EXTEND_INREG:
21883 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
21884 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
21885 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
21886 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
21887 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
21888 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
21889 case X86ISD::SHUFP: // Handle all target specific shuffles
21890 case X86ISD::PALIGNR:
21891 case X86ISD::UNPCKH:
21892 case X86ISD::UNPCKL:
21893 case X86ISD::MOVHLPS:
21894 case X86ISD::MOVLHPS:
21895 case X86ISD::PSHUFD:
21896 case X86ISD::PSHUFHW:
21897 case X86ISD::PSHUFLW:
21898 case X86ISD::MOVSS:
21899 case X86ISD::MOVSD:
21900 case X86ISD::VPERMILP:
21901 case X86ISD::VPERM2X128:
21902 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
21903 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
21904 case ISD::INTRINSIC_WO_CHAIN:
21905 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
21906 case X86ISD::INSERTPS:
21907 return PerformINSERTPSCombine(N, DAG, Subtarget);
21908 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21914 /// isTypeDesirableForOp - Return true if the target has native support for
21915 /// the specified value type and it is 'desirable' to use the type for the
21916 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21917 /// instruction encodings are longer and some i16 instructions are slow.
21918 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21919 if (!isTypeLegal(VT))
21921 if (VT != MVT::i16)
21928 case ISD::SIGN_EXTEND:
21929 case ISD::ZERO_EXTEND:
21930 case ISD::ANY_EXTEND:
21943 /// IsDesirableToPromoteOp - This method query the target whether it is
21944 /// beneficial for dag combiner to promote the specified node. If true, it
21945 /// should return the desired promotion type by reference.
21946 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21947 EVT VT = Op.getValueType();
21948 if (VT != MVT::i16)
21951 bool Promote = false;
21952 bool Commute = false;
21953 switch (Op.getOpcode()) {
21956 LoadSDNode *LD = cast<LoadSDNode>(Op);
21957 // If the non-extending load has a single use and it's not live out, then it
21958 // might be folded.
21959 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
21960 Op.hasOneUse()*/) {
21961 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
21962 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
21963 // The only case where we'd want to promote LOAD (rather then it being
21964 // promoted as an operand is when it's only use is liveout.
21965 if (UI->getOpcode() != ISD::CopyToReg)
21972 case ISD::SIGN_EXTEND:
21973 case ISD::ZERO_EXTEND:
21974 case ISD::ANY_EXTEND:
21979 SDValue N0 = Op.getOperand(0);
21980 // Look out for (store (shl (load), x)).
21981 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
21994 SDValue N0 = Op.getOperand(0);
21995 SDValue N1 = Op.getOperand(1);
21996 if (!Commute && MayFoldLoad(N1))
21998 // Avoid disabling potential load folding opportunities.
21999 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22001 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22011 //===----------------------------------------------------------------------===//
22012 // X86 Inline Assembly Support
22013 //===----------------------------------------------------------------------===//
22016 // Helper to match a string separated by whitespace.
22017 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22018 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22020 for (unsigned i = 0, e = args.size(); i != e; ++i) {
22021 StringRef piece(*args[i]);
22022 if (!s.startswith(piece)) // Check if the piece matches.
22025 s = s.substr(piece.size());
22026 StringRef::size_type pos = s.find_first_not_of(" \t");
22027 if (pos == 0) // We matched a prefix.
22035 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22038 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22040 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22041 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22042 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22043 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22045 if (AsmPieces.size() == 3)
22047 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22054 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22055 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22057 std::string AsmStr = IA->getAsmString();
22059 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22060 if (!Ty || Ty->getBitWidth() % 16 != 0)
22063 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22064 SmallVector<StringRef, 4> AsmPieces;
22065 SplitString(AsmStr, AsmPieces, ";\n");
22067 switch (AsmPieces.size()) {
22068 default: return false;
22070 // FIXME: this should verify that we are targeting a 486 or better. If not,
22071 // we will turn this bswap into something that will be lowered to logical
22072 // ops instead of emitting the bswap asm. For now, we don't support 486 or
22073 // lower so don't worry about this.
22075 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22076 matchAsm(AsmPieces[0], "bswapl", "$0") ||
22077 matchAsm(AsmPieces[0], "bswapq", "$0") ||
22078 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22079 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22080 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22081 // No need to check constraints, nothing other than the equivalent of
22082 // "=r,0" would be valid here.
22083 return IntrinsicLowering::LowerToByteSwap(CI);
22086 // rorw $$8, ${0:w} --> llvm.bswap.i16
22087 if (CI->getType()->isIntegerTy(16) &&
22088 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22089 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22090 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22092 const std::string &ConstraintsStr = IA->getConstraintString();
22093 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22094 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22095 if (clobbersFlagRegisters(AsmPieces))
22096 return IntrinsicLowering::LowerToByteSwap(CI);
22100 if (CI->getType()->isIntegerTy(32) &&
22101 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22102 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22103 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22104 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22106 const std::string &ConstraintsStr = IA->getConstraintString();
22107 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22108 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22109 if (clobbersFlagRegisters(AsmPieces))
22110 return IntrinsicLowering::LowerToByteSwap(CI);
22113 if (CI->getType()->isIntegerTy(64)) {
22114 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22115 if (Constraints.size() >= 2 &&
22116 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22117 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22118 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
22119 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22120 matchAsm(AsmPieces[1], "bswap", "%edx") &&
22121 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22122 return IntrinsicLowering::LowerToByteSwap(CI);
22130 /// getConstraintType - Given a constraint letter, return the type of
22131 /// constraint it is for this target.
22132 X86TargetLowering::ConstraintType
22133 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22134 if (Constraint.size() == 1) {
22135 switch (Constraint[0]) {
22146 return C_RegisterClass;
22170 return TargetLowering::getConstraintType(Constraint);
22173 /// Examine constraint type and operand type and determine a weight value.
22174 /// This object must already have been set up with the operand type
22175 /// and the current alternative constraint selected.
22176 TargetLowering::ConstraintWeight
22177 X86TargetLowering::getSingleConstraintMatchWeight(
22178 AsmOperandInfo &info, const char *constraint) const {
22179 ConstraintWeight weight = CW_Invalid;
22180 Value *CallOperandVal = info.CallOperandVal;
22181 // If we don't have a value, we can't do a match,
22182 // but allow it at the lowest weight.
22183 if (!CallOperandVal)
22185 Type *type = CallOperandVal->getType();
22186 // Look at the constraint type.
22187 switch (*constraint) {
22189 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22200 if (CallOperandVal->getType()->isIntegerTy())
22201 weight = CW_SpecificReg;
22206 if (type->isFloatingPointTy())
22207 weight = CW_SpecificReg;
22210 if (type->isX86_MMXTy() && Subtarget->hasMMX())
22211 weight = CW_SpecificReg;
22215 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22216 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22217 weight = CW_Register;
22220 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22221 if (C->getZExtValue() <= 31)
22222 weight = CW_Constant;
22226 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22227 if (C->getZExtValue() <= 63)
22228 weight = CW_Constant;
22232 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22233 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22234 weight = CW_Constant;
22238 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22239 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22240 weight = CW_Constant;
22244 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22245 if (C->getZExtValue() <= 3)
22246 weight = CW_Constant;
22250 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22251 if (C->getZExtValue() <= 0xff)
22252 weight = CW_Constant;
22257 if (dyn_cast<ConstantFP>(CallOperandVal)) {
22258 weight = CW_Constant;
22262 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22263 if ((C->getSExtValue() >= -0x80000000LL) &&
22264 (C->getSExtValue() <= 0x7fffffffLL))
22265 weight = CW_Constant;
22269 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22270 if (C->getZExtValue() <= 0xffffffff)
22271 weight = CW_Constant;
22278 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22279 /// with another that has more specific requirements based on the type of the
22280 /// corresponding operand.
22281 const char *X86TargetLowering::
22282 LowerXConstraint(EVT ConstraintVT) const {
22283 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22284 // 'f' like normal targets.
22285 if (ConstraintVT.isFloatingPoint()) {
22286 if (Subtarget->hasSSE2())
22288 if (Subtarget->hasSSE1())
22292 return TargetLowering::LowerXConstraint(ConstraintVT);
22295 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22296 /// vector. If it is invalid, don't add anything to Ops.
22297 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22298 std::string &Constraint,
22299 std::vector<SDValue>&Ops,
22300 SelectionDAG &DAG) const {
22303 // Only support length 1 constraints for now.
22304 if (Constraint.length() > 1) return;
22306 char ConstraintLetter = Constraint[0];
22307 switch (ConstraintLetter) {
22310 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22311 if (C->getZExtValue() <= 31) {
22312 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22318 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22319 if (C->getZExtValue() <= 63) {
22320 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22326 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22327 if (isInt<8>(C->getSExtValue())) {
22328 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22334 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22335 if (C->getZExtValue() <= 255) {
22336 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22342 // 32-bit signed value
22343 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22344 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22345 C->getSExtValue())) {
22346 // Widen to 64 bits here to get it sign extended.
22347 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22350 // FIXME gcc accepts some relocatable values here too, but only in certain
22351 // memory models; it's complicated.
22356 // 32-bit unsigned value
22357 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22358 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22359 C->getZExtValue())) {
22360 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22364 // FIXME gcc accepts some relocatable values here too, but only in certain
22365 // memory models; it's complicated.
22369 // Literal immediates are always ok.
22370 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22371 // Widen to 64 bits here to get it sign extended.
22372 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22376 // In any sort of PIC mode addresses need to be computed at runtime by
22377 // adding in a register or some sort of table lookup. These can't
22378 // be used as immediates.
22379 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22382 // If we are in non-pic codegen mode, we allow the address of a global (with
22383 // an optional displacement) to be used with 'i'.
22384 GlobalAddressSDNode *GA = nullptr;
22385 int64_t Offset = 0;
22387 // Match either (GA), (GA+C), (GA+C1+C2), etc.
22389 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22390 Offset += GA->getOffset();
22392 } else if (Op.getOpcode() == ISD::ADD) {
22393 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22394 Offset += C->getZExtValue();
22395 Op = Op.getOperand(0);
22398 } else if (Op.getOpcode() == ISD::SUB) {
22399 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22400 Offset += -C->getZExtValue();
22401 Op = Op.getOperand(0);
22406 // Otherwise, this isn't something we can handle, reject it.
22410 const GlobalValue *GV = GA->getGlobal();
22411 // If we require an extra load to get this address, as in PIC mode, we
22412 // can't accept it.
22413 if (isGlobalStubReference(
22414 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22417 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22418 GA->getValueType(0), Offset);
22423 if (Result.getNode()) {
22424 Ops.push_back(Result);
22427 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22430 std::pair<unsigned, const TargetRegisterClass*>
22431 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22433 // First, see if this is a constraint that directly corresponds to an LLVM
22435 if (Constraint.size() == 1) {
22436 // GCC Constraint Letters
22437 switch (Constraint[0]) {
22439 // TODO: Slight differences here in allocation order and leaving
22440 // RIP in the class. Do they matter any more here than they do
22441 // in the normal allocation?
22442 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22443 if (Subtarget->is64Bit()) {
22444 if (VT == MVT::i32 || VT == MVT::f32)
22445 return std::make_pair(0U, &X86::GR32RegClass);
22446 if (VT == MVT::i16)
22447 return std::make_pair(0U, &X86::GR16RegClass);
22448 if (VT == MVT::i8 || VT == MVT::i1)
22449 return std::make_pair(0U, &X86::GR8RegClass);
22450 if (VT == MVT::i64 || VT == MVT::f64)
22451 return std::make_pair(0U, &X86::GR64RegClass);
22454 // 32-bit fallthrough
22455 case 'Q': // Q_REGS
22456 if (VT == MVT::i32 || VT == MVT::f32)
22457 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22458 if (VT == MVT::i16)
22459 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22460 if (VT == MVT::i8 || VT == MVT::i1)
22461 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22462 if (VT == MVT::i64)
22463 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22465 case 'r': // GENERAL_REGS
22466 case 'l': // INDEX_REGS
22467 if (VT == MVT::i8 || VT == MVT::i1)
22468 return std::make_pair(0U, &X86::GR8RegClass);
22469 if (VT == MVT::i16)
22470 return std::make_pair(0U, &X86::GR16RegClass);
22471 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22472 return std::make_pair(0U, &X86::GR32RegClass);
22473 return std::make_pair(0U, &X86::GR64RegClass);
22474 case 'R': // LEGACY_REGS
22475 if (VT == MVT::i8 || VT == MVT::i1)
22476 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22477 if (VT == MVT::i16)
22478 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22479 if (VT == MVT::i32 || !Subtarget->is64Bit())
22480 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22481 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22482 case 'f': // FP Stack registers.
22483 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22484 // value to the correct fpstack register class.
22485 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22486 return std::make_pair(0U, &X86::RFP32RegClass);
22487 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22488 return std::make_pair(0U, &X86::RFP64RegClass);
22489 return std::make_pair(0U, &X86::RFP80RegClass);
22490 case 'y': // MMX_REGS if MMX allowed.
22491 if (!Subtarget->hasMMX()) break;
22492 return std::make_pair(0U, &X86::VR64RegClass);
22493 case 'Y': // SSE_REGS if SSE2 allowed
22494 if (!Subtarget->hasSSE2()) break;
22496 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22497 if (!Subtarget->hasSSE1()) break;
22499 switch (VT.SimpleTy) {
22501 // Scalar SSE types.
22504 return std::make_pair(0U, &X86::FR32RegClass);
22507 return std::make_pair(0U, &X86::FR64RegClass);
22515 return std::make_pair(0U, &X86::VR128RegClass);
22523 return std::make_pair(0U, &X86::VR256RegClass);
22528 return std::make_pair(0U, &X86::VR512RegClass);
22534 // Use the default implementation in TargetLowering to convert the register
22535 // constraint into a member of a register class.
22536 std::pair<unsigned, const TargetRegisterClass*> Res;
22537 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22539 // Not found as a standard register?
22541 // Map st(0) -> st(7) -> ST0
22542 if (Constraint.size() == 7 && Constraint[0] == '{' &&
22543 tolower(Constraint[1]) == 's' &&
22544 tolower(Constraint[2]) == 't' &&
22545 Constraint[3] == '(' &&
22546 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22547 Constraint[5] == ')' &&
22548 Constraint[6] == '}') {
22550 Res.first = X86::ST0+Constraint[4]-'0';
22551 Res.second = &X86::RFP80RegClass;
22555 // GCC allows "st(0)" to be called just plain "st".
22556 if (StringRef("{st}").equals_lower(Constraint)) {
22557 Res.first = X86::ST0;
22558 Res.second = &X86::RFP80RegClass;
22563 if (StringRef("{flags}").equals_lower(Constraint)) {
22564 Res.first = X86::EFLAGS;
22565 Res.second = &X86::CCRRegClass;
22569 // 'A' means EAX + EDX.
22570 if (Constraint == "A") {
22571 Res.first = X86::EAX;
22572 Res.second = &X86::GR32_ADRegClass;
22578 // Otherwise, check to see if this is a register class of the wrong value
22579 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22580 // turn into {ax},{dx}.
22581 if (Res.second->hasType(VT))
22582 return Res; // Correct type already, nothing to do.
22584 // All of the single-register GCC register classes map their values onto
22585 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
22586 // really want an 8-bit or 32-bit register, map to the appropriate register
22587 // class and return the appropriate register.
22588 if (Res.second == &X86::GR16RegClass) {
22589 if (VT == MVT::i8 || VT == MVT::i1) {
22590 unsigned DestReg = 0;
22591 switch (Res.first) {
22593 case X86::AX: DestReg = X86::AL; break;
22594 case X86::DX: DestReg = X86::DL; break;
22595 case X86::CX: DestReg = X86::CL; break;
22596 case X86::BX: DestReg = X86::BL; break;
22599 Res.first = DestReg;
22600 Res.second = &X86::GR8RegClass;
22602 } else if (VT == MVT::i32 || VT == MVT::f32) {
22603 unsigned DestReg = 0;
22604 switch (Res.first) {
22606 case X86::AX: DestReg = X86::EAX; break;
22607 case X86::DX: DestReg = X86::EDX; break;
22608 case X86::CX: DestReg = X86::ECX; break;
22609 case X86::BX: DestReg = X86::EBX; break;
22610 case X86::SI: DestReg = X86::ESI; break;
22611 case X86::DI: DestReg = X86::EDI; break;
22612 case X86::BP: DestReg = X86::EBP; break;
22613 case X86::SP: DestReg = X86::ESP; break;
22616 Res.first = DestReg;
22617 Res.second = &X86::GR32RegClass;
22619 } else if (VT == MVT::i64 || VT == MVT::f64) {
22620 unsigned DestReg = 0;
22621 switch (Res.first) {
22623 case X86::AX: DestReg = X86::RAX; break;
22624 case X86::DX: DestReg = X86::RDX; break;
22625 case X86::CX: DestReg = X86::RCX; break;
22626 case X86::BX: DestReg = X86::RBX; break;
22627 case X86::SI: DestReg = X86::RSI; break;
22628 case X86::DI: DestReg = X86::RDI; break;
22629 case X86::BP: DestReg = X86::RBP; break;
22630 case X86::SP: DestReg = X86::RSP; break;
22633 Res.first = DestReg;
22634 Res.second = &X86::GR64RegClass;
22637 } else if (Res.second == &X86::FR32RegClass ||
22638 Res.second == &X86::FR64RegClass ||
22639 Res.second == &X86::VR128RegClass ||
22640 Res.second == &X86::VR256RegClass ||
22641 Res.second == &X86::FR32XRegClass ||
22642 Res.second == &X86::FR64XRegClass ||
22643 Res.second == &X86::VR128XRegClass ||
22644 Res.second == &X86::VR256XRegClass ||
22645 Res.second == &X86::VR512RegClass) {
22646 // Handle references to XMM physical registers that got mapped into the
22647 // wrong class. This can happen with constraints like {xmm0} where the
22648 // target independent register mapper will just pick the first match it can
22649 // find, ignoring the required type.
22651 if (VT == MVT::f32 || VT == MVT::i32)
22652 Res.second = &X86::FR32RegClass;
22653 else if (VT == MVT::f64 || VT == MVT::i64)
22654 Res.second = &X86::FR64RegClass;
22655 else if (X86::VR128RegClass.hasType(VT))
22656 Res.second = &X86::VR128RegClass;
22657 else if (X86::VR256RegClass.hasType(VT))
22658 Res.second = &X86::VR256RegClass;
22659 else if (X86::VR512RegClass.hasType(VT))
22660 Res.second = &X86::VR512RegClass;
22666 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22668 // Scaling factors are not free at all.
22669 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22670 // will take 2 allocations in the out of order engine instead of 1
22671 // for plain addressing mode, i.e. inst (reg1).
22673 // vaddps (%rsi,%drx), %ymm0, %ymm1
22674 // Requires two allocations (one for the load, one for the computation)
22676 // vaddps (%rsi), %ymm0, %ymm1
22677 // Requires just 1 allocation, i.e., freeing allocations for other operations
22678 // and having less micro operations to execute.
22680 // For some X86 architectures, this is even worse because for instance for
22681 // stores, the complex addressing mode forces the instruction to use the
22682 // "load" ports instead of the dedicated "store" port.
22683 // E.g., on Haswell:
22684 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22685 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
22686 if (isLegalAddressingMode(AM, Ty))
22687 // Scale represents reg2 * scale, thus account for 1
22688 // as soon as we use a second register.
22689 return AM.Scale != 0;
22693 bool X86TargetLowering::isTargetFTOL() const {
22694 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();