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/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 #define DEBUG_TYPE "x86-isel"
57 STATISTIC(NumTailCalls, "Number of tail calls");
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64 SelectionDAG &DAG, SDLoc dl,
65 unsigned vectorWidth) {
66 assert((vectorWidth == 128 || vectorWidth == 256) &&
67 "Unsupported vector width");
68 EVT VT = Vec.getValueType();
69 EVT ElVT = VT.getVectorElementType();
70 unsigned Factor = VT.getSizeInBits()/vectorWidth;
71 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72 VT.getVectorNumElements()/Factor);
74 // Extract from UNDEF is UNDEF.
75 if (Vec.getOpcode() == ISD::UNDEF)
76 return DAG.getUNDEF(ResultVT);
78 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
79 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
81 // This is the index of the first element of the vectorWidth-bit chunk
83 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
86 // If the input is a buildvector just emit a smaller one.
87 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
92 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106 SelectionDAG &DAG, SDLoc dl) {
107 assert((Vec.getValueType().is256BitVector() ||
108 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114 SelectionDAG &DAG, SDLoc dl) {
115 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120 unsigned IdxVal, SelectionDAG &DAG,
121 SDLoc dl, unsigned vectorWidth) {
122 assert((vectorWidth == 128 || vectorWidth == 256) &&
123 "Unsupported vector width");
124 // Inserting UNDEF is Result
125 if (Vec.getOpcode() == ISD::UNDEF)
127 EVT VT = Vec.getValueType();
128 EVT ElVT = VT.getVectorElementType();
129 EVT ResultVT = Result.getValueType();
131 // Insert the relevant vectorWidth bits.
132 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
134 // This is the index of the first element of the vectorWidth-bit chunk
136 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
139 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
143 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference. Idx is an index in the 128 bits
147 /// we want. It need not be aligned to a 128-bit bounday. That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150 unsigned IdxVal, SelectionDAG &DAG,
152 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157 unsigned IdxVal, SelectionDAG &DAG,
159 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168 unsigned NumElems, SelectionDAG &DAG,
170 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175 unsigned NumElems, SelectionDAG &DAG,
177 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
181 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
182 if (TT.isOSBinFormatMachO()) {
183 if (TT.getArch() == Triple::x86_64)
184 return new X86_64MachoTargetObjectFile();
185 return new TargetLoweringObjectFileMachO();
189 return new X86LinuxTargetObjectFile();
190 if (TT.isOSBinFormatELF())
191 return new TargetLoweringObjectFileELF();
192 if (TT.isKnownWindowsMSVCEnvironment())
193 return new X86WindowsTargetObjectFile();
194 if (TT.isOSBinFormatCOFF())
195 return new TargetLoweringObjectFileCOFF();
196 llvm_unreachable("unknown subtarget type");
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
201 Subtarget = &TM.getSubtarget<X86Subtarget>();
202 X86ScalarSSEf64 = Subtarget->hasSSE2();
203 X86ScalarSSEf32 = Subtarget->hasSSE1();
204 TD = getDataLayout();
206 resetOperationActions();
209 void X86TargetLowering::resetOperationActions() {
210 const TargetMachine &TM = getTargetMachine();
211 static bool FirstTimeThrough = true;
213 // If none of the target options have changed, then we don't need to reset the
214 // operation actions.
215 if (!FirstTimeThrough && TO == TM.Options) return;
217 if (!FirstTimeThrough) {
218 // Reinitialize the actions.
220 FirstTimeThrough = false;
225 // Set up the TargetLowering object.
226 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
228 // X86 is weird, it always uses i8 for shift amounts and setcc results.
229 setBooleanContents(ZeroOrOneBooleanContent);
230 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
233 // For 64-bit since we have so many registers use the ILP scheduler, for
234 // 32-bit code use the register pressure specific scheduling.
235 // For Atom, always use ILP scheduling.
236 if (Subtarget->isAtom())
237 setSchedulingPreference(Sched::ILP);
238 else if (Subtarget->is64Bit())
239 setSchedulingPreference(Sched::ILP);
241 setSchedulingPreference(Sched::RegPressure);
242 const X86RegisterInfo *RegInfo =
243 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
244 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
246 // Bypass expensive divides on Atom when compiling with O2
247 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
248 addBypassSlowDiv(32, 8);
249 if (Subtarget->is64Bit())
250 addBypassSlowDiv(64, 16);
253 if (Subtarget->isTargetKnownWindowsMSVC()) {
254 // Setup Windows compiler runtime calls.
255 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
256 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
257 setLibcallName(RTLIB::SREM_I64, "_allrem");
258 setLibcallName(RTLIB::UREM_I64, "_aullrem");
259 setLibcallName(RTLIB::MUL_I64, "_allmul");
260 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
261 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266 // The _ftol2 runtime function has an unusual calling conv, which
267 // is modeled by a special pseudo-instruction.
268 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
269 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
270 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
271 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
274 if (Subtarget->isTargetDarwin()) {
275 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
276 setUseUnderscoreSetJmp(false);
277 setUseUnderscoreLongJmp(false);
278 } else if (Subtarget->isTargetWindowsGNU()) {
279 // MS runtime is weird: it exports _setjmp, but longjmp!
280 setUseUnderscoreSetJmp(true);
281 setUseUnderscoreLongJmp(false);
283 setUseUnderscoreSetJmp(true);
284 setUseUnderscoreLongJmp(true);
287 // Set up the register classes.
288 addRegisterClass(MVT::i8, &X86::GR8RegClass);
289 addRegisterClass(MVT::i16, &X86::GR16RegClass);
290 addRegisterClass(MVT::i32, &X86::GR32RegClass);
291 if (Subtarget->is64Bit())
292 addRegisterClass(MVT::i64, &X86::GR64RegClass);
294 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296 // We don't accept any truncstore of integer registers.
297 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
304 // SETOEQ and SETUNE require checking two conditions.
305 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
312 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
314 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
315 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
316 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
318 if (Subtarget->is64Bit()) {
319 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
320 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
321 } else if (!TM.Options.UseSoftFloat) {
322 // We have an algorithm for SSE2->double, and we turn this into a
323 // 64-bit FILD followed by conditional FADD for other targets.
324 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
325 // We have an algorithm for SSE2, and we turn this into a 64-bit
326 // FILD for other targets.
327 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
330 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
332 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
333 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
335 if (!TM.Options.UseSoftFloat) {
336 // SSE has no i16 to fp conversion, only i32
337 if (X86ScalarSSEf32) {
338 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
339 // f32 and f64 cases are Legal, f80 case is not
340 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
342 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
343 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
346 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
347 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
350 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
351 // are Legal, f80 is custom lowered.
352 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
353 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
355 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
357 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
358 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
360 if (X86ScalarSSEf32) {
361 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
362 // f32 and f64 cases are Legal, f80 case is not
363 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
365 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
366 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
369 // Handle FP_TO_UINT by promoting the destination to a larger signed
371 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
372 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
373 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
375 if (Subtarget->is64Bit()) {
376 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
377 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
378 } else if (!TM.Options.UseSoftFloat) {
379 // Since AVX is a superset of SSE3, only check for SSE here.
380 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381 // Expand FP_TO_UINT into a select.
382 // FIXME: We would like to use a Custom expander here eventually to do
383 // the optimal thing for SSE vs. the default expansion in the legalizer.
384 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
386 // With SSE3 we can use fisttpll to convert to a signed i64; without
387 // SSE, we're stuck with a fistpll.
388 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
391 if (isTargetFTOL()) {
392 // Use the _ftol2 runtime function, which has a pseudo-instruction
393 // to handle its weird calling convention.
394 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
397 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398 if (!X86ScalarSSEf64) {
399 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
400 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
401 if (Subtarget->is64Bit()) {
402 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
403 // Without SSE, i64->f64 goes through memory.
404 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
408 // Scalar integer divide and remainder are lowered to use operations that
409 // produce two results, to match the available instructions. This exposes
410 // the two-result form to trivial CSE, which is able to combine x/y and x%y
411 // into a single instruction.
413 // Scalar integer multiply-high is also lowered to use two-result
414 // operations, to match the available instructions. However, plain multiply
415 // (low) operations are left as Legal, as there are single-result
416 // instructions for this in x86. Using the two-result multiply instructions
417 // when both high and low results are needed must be arranged by dagcombine.
418 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
420 setOperationAction(ISD::MULHS, VT, Expand);
421 setOperationAction(ISD::MULHU, VT, Expand);
422 setOperationAction(ISD::SDIV, VT, Expand);
423 setOperationAction(ISD::UDIV, VT, Expand);
424 setOperationAction(ISD::SREM, VT, Expand);
425 setOperationAction(ISD::UREM, VT, Expand);
427 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428 setOperationAction(ISD::ADDC, VT, Custom);
429 setOperationAction(ISD::ADDE, VT, Custom);
430 setOperationAction(ISD::SUBC, VT, Custom);
431 setOperationAction(ISD::SUBE, VT, Custom);
434 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
435 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
436 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
437 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
438 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
439 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
443 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
444 if (Subtarget->is64Bit())
445 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
449 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
450 setOperationAction(ISD::FREM , MVT::f32 , Expand);
451 setOperationAction(ISD::FREM , MVT::f64 , Expand);
452 setOperationAction(ISD::FREM , MVT::f80 , Expand);
453 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
455 // Promote the i8 variants and force them on up to i32 which has a shorter
457 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
458 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
459 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
460 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
461 if (Subtarget->hasBMI()) {
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
464 if (Subtarget->is64Bit())
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
467 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
468 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
469 if (Subtarget->is64Bit())
470 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
473 if (Subtarget->hasLZCNT()) {
474 // When promoting the i8 variants, force them to i32 for a shorter
476 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
477 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
478 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
482 if (Subtarget->is64Bit())
483 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
485 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
486 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
487 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
491 if (Subtarget->is64Bit()) {
492 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
493 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
497 if (Subtarget->hasPOPCNT()) {
498 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
500 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
501 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
502 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
507 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
509 if (!Subtarget->hasMOVBE())
510 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
512 // These should be promoted to a larger select which is supported.
513 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
514 // X86 wants to expand cmov itself.
515 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
516 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
517 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
518 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
519 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
521 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
522 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
524 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
525 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
527 if (Subtarget->is64Bit()) {
528 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
529 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
531 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
532 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
533 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
534 // support continuation, user-level threading, and etc.. As a result, no
535 // other SjLj exception interfaces are implemented and please don't build
536 // your own exception handling based on them.
537 // LLVM/Clang supports zero-cost DWARF exception handling.
538 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
539 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
542 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
543 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
544 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
545 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
546 if (Subtarget->is64Bit())
547 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
548 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
549 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
550 if (Subtarget->is64Bit()) {
551 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
552 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
553 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
554 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
555 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
557 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
558 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
559 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
560 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
561 if (Subtarget->is64Bit()) {
562 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
563 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
564 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
567 if (Subtarget->hasSSE1())
568 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
570 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
572 // Expand certain atomics
573 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
575 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
576 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
577 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
580 if (!Subtarget->is64Bit()) {
581 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
582 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
595 if (Subtarget->hasCmpxchg16b()) {
596 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
599 // FIXME - use subtarget debug flags
600 if (!Subtarget->isTargetDarwin() &&
601 !Subtarget->isTargetELF() &&
602 !Subtarget->isTargetCygMing()) {
603 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
606 if (Subtarget->is64Bit()) {
607 setExceptionPointerRegister(X86::RAX);
608 setExceptionSelectorRegister(X86::RDX);
610 setExceptionPointerRegister(X86::EAX);
611 setExceptionSelectorRegister(X86::EDX);
613 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
614 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
616 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
617 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
619 setOperationAction(ISD::TRAP, MVT::Other, Legal);
620 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
622 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
623 setOperationAction(ISD::VASTART , MVT::Other, Custom);
624 setOperationAction(ISD::VAEND , MVT::Other, Expand);
625 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
626 // TargetInfo::X86_64ABIBuiltinVaList
627 setOperationAction(ISD::VAARG , MVT::Other, Custom);
628 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
630 // TargetInfo::CharPtrBuiltinVaList
631 setOperationAction(ISD::VAARG , MVT::Other, Expand);
632 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
635 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
636 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
638 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639 MVT::i64 : MVT::i32, Custom);
641 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
642 // f32 and f64 use SSE.
643 // Set up the FP register classes.
644 addRegisterClass(MVT::f32, &X86::FR32RegClass);
645 addRegisterClass(MVT::f64, &X86::FR64RegClass);
647 // Use ANDPD to simulate FABS.
648 setOperationAction(ISD::FABS , MVT::f64, Custom);
649 setOperationAction(ISD::FABS , MVT::f32, Custom);
651 // Use XORP to simulate FNEG.
652 setOperationAction(ISD::FNEG , MVT::f64, Custom);
653 setOperationAction(ISD::FNEG , MVT::f32, Custom);
655 // Use ANDPD and ORPD to simulate FCOPYSIGN.
656 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
657 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
659 // Lower this to FGETSIGNx86 plus an AND.
660 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
661 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
663 // We don't support sin/cos/fmod
664 setOperationAction(ISD::FSIN , MVT::f64, Expand);
665 setOperationAction(ISD::FCOS , MVT::f64, Expand);
666 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
667 setOperationAction(ISD::FSIN , MVT::f32, Expand);
668 setOperationAction(ISD::FCOS , MVT::f32, Expand);
669 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
671 // Expand FP immediates into loads from the stack, except for the special
673 addLegalFPImmediate(APFloat(+0.0)); // xorpd
674 addLegalFPImmediate(APFloat(+0.0f)); // xorps
675 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
676 // Use SSE for f32, x87 for f64.
677 // Set up the FP register classes.
678 addRegisterClass(MVT::f32, &X86::FR32RegClass);
679 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
681 // Use ANDPS to simulate FABS.
682 setOperationAction(ISD::FABS , MVT::f32, Custom);
684 // Use XORP to simulate FNEG.
685 setOperationAction(ISD::FNEG , MVT::f32, Custom);
687 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
689 // Use ANDPS and ORPS to simulate FCOPYSIGN.
690 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
691 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
693 // We don't support sin/cos/fmod
694 setOperationAction(ISD::FSIN , MVT::f32, Expand);
695 setOperationAction(ISD::FCOS , MVT::f32, Expand);
696 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
698 // Special cases we handle for FP constants.
699 addLegalFPImmediate(APFloat(+0.0f)); // xorps
700 addLegalFPImmediate(APFloat(+0.0)); // FLD0
701 addLegalFPImmediate(APFloat(+1.0)); // FLD1
702 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
703 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
705 if (!TM.Options.UnsafeFPMath) {
706 setOperationAction(ISD::FSIN , MVT::f64, Expand);
707 setOperationAction(ISD::FCOS , MVT::f64, Expand);
708 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
710 } else if (!TM.Options.UseSoftFloat) {
711 // f32 and f64 in x87.
712 // Set up the FP register classes.
713 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
714 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
716 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
717 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
718 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
719 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
721 if (!TM.Options.UnsafeFPMath) {
722 setOperationAction(ISD::FSIN , MVT::f64, Expand);
723 setOperationAction(ISD::FSIN , MVT::f32, Expand);
724 setOperationAction(ISD::FCOS , MVT::f64, Expand);
725 setOperationAction(ISD::FCOS , MVT::f32, Expand);
726 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
727 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
729 addLegalFPImmediate(APFloat(+0.0)); // FLD0
730 addLegalFPImmediate(APFloat(+1.0)); // FLD1
731 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
732 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
733 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
734 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
735 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
736 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
739 // We don't support FMA.
740 setOperationAction(ISD::FMA, MVT::f64, Expand);
741 setOperationAction(ISD::FMA, MVT::f32, Expand);
743 // Long double always uses X87.
744 if (!TM.Options.UseSoftFloat) {
745 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
746 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
747 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
749 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
750 addLegalFPImmediate(TmpFlt); // FLD0
752 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
755 APFloat TmpFlt2(+1.0);
756 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
758 addLegalFPImmediate(TmpFlt2); // FLD1
759 TmpFlt2.changeSign();
760 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
763 if (!TM.Options.UnsafeFPMath) {
764 setOperationAction(ISD::FSIN , MVT::f80, Expand);
765 setOperationAction(ISD::FCOS , MVT::f80, Expand);
766 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
769 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
770 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
771 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
772 setOperationAction(ISD::FRINT, MVT::f80, Expand);
773 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
774 setOperationAction(ISD::FMA, MVT::f80, Expand);
777 // Always use a library call for pow.
778 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
779 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
780 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
782 setOperationAction(ISD::FLOG, MVT::f80, Expand);
783 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
784 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
785 setOperationAction(ISD::FEXP, MVT::f80, Expand);
786 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
788 // First set operation action for all vector types to either promote
789 // (for widening) or expand (for scalarization). Then we will selectively
790 // turn on ones that can be effectively codegen'd.
791 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
792 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
793 MVT VT = (MVT::SimpleValueType)i;
794 setOperationAction(ISD::ADD , VT, Expand);
795 setOperationAction(ISD::SUB , VT, Expand);
796 setOperationAction(ISD::FADD, VT, Expand);
797 setOperationAction(ISD::FNEG, VT, Expand);
798 setOperationAction(ISD::FSUB, VT, Expand);
799 setOperationAction(ISD::MUL , VT, Expand);
800 setOperationAction(ISD::FMUL, VT, Expand);
801 setOperationAction(ISD::SDIV, VT, Expand);
802 setOperationAction(ISD::UDIV, VT, Expand);
803 setOperationAction(ISD::FDIV, VT, Expand);
804 setOperationAction(ISD::SREM, VT, Expand);
805 setOperationAction(ISD::UREM, VT, Expand);
806 setOperationAction(ISD::LOAD, VT, Expand);
807 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
808 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
809 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
810 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
811 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
812 setOperationAction(ISD::FABS, VT, Expand);
813 setOperationAction(ISD::FSIN, VT, Expand);
814 setOperationAction(ISD::FSINCOS, VT, Expand);
815 setOperationAction(ISD::FCOS, VT, Expand);
816 setOperationAction(ISD::FSINCOS, VT, Expand);
817 setOperationAction(ISD::FREM, VT, Expand);
818 setOperationAction(ISD::FMA, VT, Expand);
819 setOperationAction(ISD::FPOWI, VT, Expand);
820 setOperationAction(ISD::FSQRT, VT, Expand);
821 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
822 setOperationAction(ISD::FFLOOR, VT, Expand);
823 setOperationAction(ISD::FCEIL, VT, Expand);
824 setOperationAction(ISD::FTRUNC, VT, Expand);
825 setOperationAction(ISD::FRINT, VT, Expand);
826 setOperationAction(ISD::FNEARBYINT, VT, Expand);
827 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
828 setOperationAction(ISD::MULHS, VT, Expand);
829 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
830 setOperationAction(ISD::MULHU, VT, Expand);
831 setOperationAction(ISD::SDIVREM, VT, Expand);
832 setOperationAction(ISD::UDIVREM, VT, Expand);
833 setOperationAction(ISD::FPOW, VT, Expand);
834 setOperationAction(ISD::CTPOP, VT, Expand);
835 setOperationAction(ISD::CTTZ, VT, Expand);
836 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
837 setOperationAction(ISD::CTLZ, VT, Expand);
838 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
839 setOperationAction(ISD::SHL, VT, Expand);
840 setOperationAction(ISD::SRA, VT, Expand);
841 setOperationAction(ISD::SRL, VT, Expand);
842 setOperationAction(ISD::ROTL, VT, Expand);
843 setOperationAction(ISD::ROTR, VT, Expand);
844 setOperationAction(ISD::BSWAP, VT, Expand);
845 setOperationAction(ISD::SETCC, VT, Expand);
846 setOperationAction(ISD::FLOG, VT, Expand);
847 setOperationAction(ISD::FLOG2, VT, Expand);
848 setOperationAction(ISD::FLOG10, VT, Expand);
849 setOperationAction(ISD::FEXP, VT, Expand);
850 setOperationAction(ISD::FEXP2, VT, Expand);
851 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
852 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
853 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
854 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
855 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
856 setOperationAction(ISD::TRUNCATE, VT, Expand);
857 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
858 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
859 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
860 setOperationAction(ISD::VSELECT, VT, Expand);
861 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
862 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
863 setTruncStoreAction(VT,
864 (MVT::SimpleValueType)InnerVT, Expand);
865 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
866 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
867 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
870 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
871 // with -msoft-float, disable use of MMX as well.
872 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
873 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
874 // No operations on x86mmx supported, everything uses intrinsics.
877 // MMX-sized vectors (other than x86mmx) are expected to be expanded
878 // into smaller operations.
879 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
880 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
881 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
882 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
883 setOperationAction(ISD::AND, MVT::v8i8, Expand);
884 setOperationAction(ISD::AND, MVT::v4i16, Expand);
885 setOperationAction(ISD::AND, MVT::v2i32, Expand);
886 setOperationAction(ISD::AND, MVT::v1i64, Expand);
887 setOperationAction(ISD::OR, MVT::v8i8, Expand);
888 setOperationAction(ISD::OR, MVT::v4i16, Expand);
889 setOperationAction(ISD::OR, MVT::v2i32, Expand);
890 setOperationAction(ISD::OR, MVT::v1i64, Expand);
891 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
892 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
893 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
894 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
895 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
899 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
900 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
901 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
902 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
903 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
904 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
909 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
910 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
912 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
913 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
914 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
915 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
916 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
917 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
918 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
919 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
920 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
921 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
922 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
923 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
926 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
927 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
929 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
930 // registers cannot be used even for integer operations.
931 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
932 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
933 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
934 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
936 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
937 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
938 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
939 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
940 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
941 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
942 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
943 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
944 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
945 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
946 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
947 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
948 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
949 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
950 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
951 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
952 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
953 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
954 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
955 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
956 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
957 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
959 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
960 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
961 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
962 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
964 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
965 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
970 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
971 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
972 MVT VT = (MVT::SimpleValueType)i;
973 // Do not attempt to custom lower non-power-of-2 vectors
974 if (!isPowerOf2_32(VT.getVectorNumElements()))
976 // Do not attempt to custom lower non-128-bit vectors
977 if (!VT.is128BitVector())
979 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
980 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
981 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
984 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
985 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
986 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
987 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
991 if (Subtarget->is64Bit()) {
992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
996 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
997 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
998 MVT VT = (MVT::SimpleValueType)i;
1000 // Do not attempt to promote non-128-bit vectors
1001 if (!VT.is128BitVector())
1004 setOperationAction(ISD::AND, VT, Promote);
1005 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1006 setOperationAction(ISD::OR, VT, Promote);
1007 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1008 setOperationAction(ISD::XOR, VT, Promote);
1009 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1010 setOperationAction(ISD::LOAD, VT, Promote);
1011 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1012 setOperationAction(ISD::SELECT, VT, Promote);
1013 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1016 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1018 // Custom lower v2i64 and v2f64 selects.
1019 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1020 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1021 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1022 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1024 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1025 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1027 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1028 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1029 // As there is no 64-bit GPR available, we need build a special custom
1030 // sequence to convert from v2i32 to v2f32.
1031 if (!Subtarget->is64Bit())
1032 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1034 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1035 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1037 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1039 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1040 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1041 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1044 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1045 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1046 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1047 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1048 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1049 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1050 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1051 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1052 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1053 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1054 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1056 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1057 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1058 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1059 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1060 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1061 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1062 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1063 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1064 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1065 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1067 // FIXME: Do we need to handle scalar-to-vector here?
1068 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1071 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1072 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1073 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1074 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1075 // There is no BLENDI for byte vectors. We don't need to custom lower
1076 // some vselects for now.
1077 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1079 // i8 and i16 vectors are custom , because the source register and source
1080 // source memory operand types are not the same width. f32 vectors are
1081 // custom since the immediate controlling the insert encodes additional
1083 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1084 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1085 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1086 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1088 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1089 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1090 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1091 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1093 // FIXME: these should be Legal but thats only for the case where
1094 // the index is constant. For now custom expand to deal with that.
1095 if (Subtarget->is64Bit()) {
1096 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1097 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1101 if (Subtarget->hasSSE2()) {
1102 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1103 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1105 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1106 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1108 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1109 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1111 // In the customized shift lowering, the legal cases in AVX2 will be
1113 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1114 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1116 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1117 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1119 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1122 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1123 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1124 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1125 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1126 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1127 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1128 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1130 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1131 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1132 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1134 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1140 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1142 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1143 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1145 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1147 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1153 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1154 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1156 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1158 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1160 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1161 // even though v8i16 is a legal type.
1162 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1163 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1164 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1166 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1167 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1168 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1170 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1171 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1173 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1175 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1176 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1182 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1184 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1185 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1186 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1187 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1189 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1190 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1191 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1193 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1194 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1195 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1196 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1198 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1199 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1200 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1201 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1202 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1203 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1204 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1205 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1206 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1207 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1208 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1209 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1211 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1212 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1213 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1214 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1215 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1216 setOperationAction(ISD::FMA, MVT::f32, Legal);
1217 setOperationAction(ISD::FMA, MVT::f64, Legal);
1220 if (Subtarget->hasInt256()) {
1221 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1222 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1223 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1224 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1226 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1227 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1228 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1229 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1231 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1232 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1233 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1234 // Don't lower v32i8 because there is no 128-bit byte mul
1236 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1237 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1238 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1239 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1241 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1242 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1244 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1245 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1246 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1247 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1249 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1250 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1251 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1252 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1254 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1255 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1256 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1257 // Don't lower v32i8 because there is no 128-bit byte mul
1260 // In the customized shift lowering, the legal cases in AVX2 will be
1262 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1263 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1265 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1266 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1268 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1270 // Custom lower several nodes for 256-bit types.
1271 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1272 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1273 MVT VT = (MVT::SimpleValueType)i;
1275 // Extract subvector is special because the value type
1276 // (result) is 128-bit but the source is 256-bit wide.
1277 if (VT.is128BitVector())
1278 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1280 // Do not attempt to custom lower other non-256-bit vectors
1281 if (!VT.is256BitVector())
1284 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1285 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1286 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1287 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1288 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1289 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1290 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1293 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1294 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1295 MVT VT = (MVT::SimpleValueType)i;
1297 // Do not attempt to promote non-256-bit vectors
1298 if (!VT.is256BitVector())
1301 setOperationAction(ISD::AND, VT, Promote);
1302 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1303 setOperationAction(ISD::OR, VT, Promote);
1304 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1305 setOperationAction(ISD::XOR, VT, Promote);
1306 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1307 setOperationAction(ISD::LOAD, VT, Promote);
1308 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1309 setOperationAction(ISD::SELECT, VT, Promote);
1310 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1314 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1315 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1316 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1317 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1318 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1320 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1321 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1322 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1324 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1325 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1326 setOperationAction(ISD::XOR, MVT::i1, Legal);
1327 setOperationAction(ISD::OR, MVT::i1, Legal);
1328 setOperationAction(ISD::AND, MVT::i1, Legal);
1329 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1330 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1331 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1332 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1333 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1334 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1336 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1337 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1338 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1339 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1340 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1341 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1343 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1344 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1345 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1346 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1347 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1348 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1349 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1350 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1352 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1353 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1354 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1355 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1356 if (Subtarget->is64Bit()) {
1357 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1358 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1359 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1360 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1362 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1363 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1364 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1365 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1366 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1367 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1368 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1369 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1370 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1371 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1373 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1374 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1375 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1376 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1377 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1378 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1379 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1380 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1381 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1382 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1383 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1384 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1385 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1387 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1388 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1389 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1390 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1391 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1392 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1394 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1395 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1397 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1400 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1403 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1404 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1405 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1406 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1407 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1409 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1410 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1412 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1413 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1415 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1417 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1418 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1420 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1421 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1423 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1424 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1426 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1427 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1428 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1429 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1430 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1431 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1433 // Custom lower several nodes.
1434 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1435 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1436 MVT VT = (MVT::SimpleValueType)i;
1438 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1439 // Extract subvector is special because the value type
1440 // (result) is 256/128-bit but the source is 512-bit wide.
1441 if (VT.is128BitVector() || VT.is256BitVector())
1442 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1444 if (VT.getVectorElementType() == MVT::i1)
1445 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1447 // Do not attempt to custom lower other non-512-bit vectors
1448 if (!VT.is512BitVector())
1451 if ( EltSize >= 32) {
1452 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1453 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1454 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1455 setOperationAction(ISD::VSELECT, VT, Legal);
1456 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1457 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1458 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1461 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1462 MVT VT = (MVT::SimpleValueType)i;
1464 // Do not attempt to promote non-256-bit vectors
1465 if (!VT.is512BitVector())
1468 setOperationAction(ISD::SELECT, VT, Promote);
1469 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1473 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1474 // of this type with custom code.
1475 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1476 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1477 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1481 // We want to custom lower some of our intrinsics.
1482 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1483 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1484 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1485 if (!Subtarget->is64Bit())
1486 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1488 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1489 // handle type legalization for these operations here.
1491 // FIXME: We really should do custom legalization for addition and
1492 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1493 // than generic legalization for 64-bit multiplication-with-overflow, though.
1494 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1495 // Add/Sub/Mul with overflow operations are custom lowered.
1497 setOperationAction(ISD::SADDO, VT, Custom);
1498 setOperationAction(ISD::UADDO, VT, Custom);
1499 setOperationAction(ISD::SSUBO, VT, Custom);
1500 setOperationAction(ISD::USUBO, VT, Custom);
1501 setOperationAction(ISD::SMULO, VT, Custom);
1502 setOperationAction(ISD::UMULO, VT, Custom);
1505 // There are no 8-bit 3-address imul/mul instructions
1506 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1507 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1509 if (!Subtarget->is64Bit()) {
1510 // These libcalls are not available in 32-bit.
1511 setLibcallName(RTLIB::SHL_I128, nullptr);
1512 setLibcallName(RTLIB::SRL_I128, nullptr);
1513 setLibcallName(RTLIB::SRA_I128, nullptr);
1516 // Combine sin / cos into one node or libcall if possible.
1517 if (Subtarget->hasSinCos()) {
1518 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1519 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1520 if (Subtarget->isTargetDarwin()) {
1521 // For MacOSX, we don't want to the normal expansion of a libcall to
1522 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1524 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1525 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1529 if (Subtarget->isTargetWin64()) {
1530 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1531 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1532 setOperationAction(ISD::SREM, MVT::i128, Custom);
1533 setOperationAction(ISD::UREM, MVT::i128, Custom);
1534 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1535 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1538 // We have target-specific dag combine patterns for the following nodes:
1539 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1540 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1541 setTargetDAGCombine(ISD::VSELECT);
1542 setTargetDAGCombine(ISD::SELECT);
1543 setTargetDAGCombine(ISD::SHL);
1544 setTargetDAGCombine(ISD::SRA);
1545 setTargetDAGCombine(ISD::SRL);
1546 setTargetDAGCombine(ISD::OR);
1547 setTargetDAGCombine(ISD::AND);
1548 setTargetDAGCombine(ISD::ADD);
1549 setTargetDAGCombine(ISD::FADD);
1550 setTargetDAGCombine(ISD::FSUB);
1551 setTargetDAGCombine(ISD::FMA);
1552 setTargetDAGCombine(ISD::SUB);
1553 setTargetDAGCombine(ISD::LOAD);
1554 setTargetDAGCombine(ISD::STORE);
1555 setTargetDAGCombine(ISD::ZERO_EXTEND);
1556 setTargetDAGCombine(ISD::ANY_EXTEND);
1557 setTargetDAGCombine(ISD::SIGN_EXTEND);
1558 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1559 setTargetDAGCombine(ISD::TRUNCATE);
1560 setTargetDAGCombine(ISD::SINT_TO_FP);
1561 setTargetDAGCombine(ISD::SETCC);
1562 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1563 if (Subtarget->is64Bit())
1564 setTargetDAGCombine(ISD::MUL);
1565 setTargetDAGCombine(ISD::XOR);
1567 computeRegisterProperties();
1569 // On Darwin, -Os means optimize for size without hurting performance,
1570 // do not reduce the limit.
1571 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1572 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1573 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1574 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1575 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1576 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1577 setPrefLoopAlignment(4); // 2^4 bytes.
1579 // Predictable cmov don't hurt on atom because it's in-order.
1580 PredictableSelectIsExpensive = !Subtarget->isAtom();
1582 setPrefFunctionAlignment(4); // 2^4 bytes.
1585 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1587 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1589 if (Subtarget->hasAVX512())
1590 switch(VT.getVectorNumElements()) {
1591 case 8: return MVT::v8i1;
1592 case 16: return MVT::v16i1;
1595 return VT.changeVectorElementTypeToInteger();
1598 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1599 /// the desired ByVal argument alignment.
1600 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1603 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1604 if (VTy->getBitWidth() == 128)
1606 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1607 unsigned EltAlign = 0;
1608 getMaxByValAlign(ATy->getElementType(), EltAlign);
1609 if (EltAlign > MaxAlign)
1610 MaxAlign = EltAlign;
1611 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1612 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1613 unsigned EltAlign = 0;
1614 getMaxByValAlign(STy->getElementType(i), EltAlign);
1615 if (EltAlign > MaxAlign)
1616 MaxAlign = EltAlign;
1623 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1624 /// function arguments in the caller parameter area. For X86, aggregates
1625 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1626 /// are at 4-byte boundaries.
1627 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1628 if (Subtarget->is64Bit()) {
1629 // Max of 8 and alignment of type.
1630 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1637 if (Subtarget->hasSSE1())
1638 getMaxByValAlign(Ty, Align);
1642 /// getOptimalMemOpType - Returns the target specific optimal type for load
1643 /// and store operations as a result of memset, memcpy, and memmove
1644 /// lowering. If DstAlign is zero that means it's safe to destination
1645 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1646 /// means there isn't a need to check it against alignment requirement,
1647 /// probably because the source does not need to be loaded. If 'IsMemset' is
1648 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1649 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1650 /// source is constant so it does not need to be loaded.
1651 /// It returns EVT::Other if the type should be determined using generic
1652 /// target-independent logic.
1654 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1655 unsigned DstAlign, unsigned SrcAlign,
1656 bool IsMemset, bool ZeroMemset,
1658 MachineFunction &MF) const {
1659 const Function *F = MF.getFunction();
1660 if ((!IsMemset || ZeroMemset) &&
1661 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1662 Attribute::NoImplicitFloat)) {
1664 (Subtarget->isUnalignedMemAccessFast() ||
1665 ((DstAlign == 0 || DstAlign >= 16) &&
1666 (SrcAlign == 0 || SrcAlign >= 16)))) {
1668 if (Subtarget->hasInt256())
1670 if (Subtarget->hasFp256())
1673 if (Subtarget->hasSSE2())
1675 if (Subtarget->hasSSE1())
1677 } else if (!MemcpyStrSrc && Size >= 8 &&
1678 !Subtarget->is64Bit() &&
1679 Subtarget->hasSSE2()) {
1680 // Do not use f64 to lower memcpy if source is string constant. It's
1681 // better to use i32 to avoid the loads.
1685 if (Subtarget->is64Bit() && Size >= 8)
1690 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1692 return X86ScalarSSEf32;
1693 else if (VT == MVT::f64)
1694 return X86ScalarSSEf64;
1699 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1703 *Fast = Subtarget->isUnalignedMemAccessFast();
1707 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1708 /// current function. The returned value is a member of the
1709 /// MachineJumpTableInfo::JTEntryKind enum.
1710 unsigned X86TargetLowering::getJumpTableEncoding() const {
1711 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1713 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1714 Subtarget->isPICStyleGOT())
1715 return MachineJumpTableInfo::EK_Custom32;
1717 // Otherwise, use the normal jump table encoding heuristics.
1718 return TargetLowering::getJumpTableEncoding();
1722 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1723 const MachineBasicBlock *MBB,
1724 unsigned uid,MCContext &Ctx) const{
1725 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1726 Subtarget->isPICStyleGOT());
1727 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1729 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1730 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1733 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1735 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1736 SelectionDAG &DAG) const {
1737 if (!Subtarget->is64Bit())
1738 // This doesn't have SDLoc associated with it, but is not really the
1739 // same as a Register.
1740 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1744 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1745 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1747 const MCExpr *X86TargetLowering::
1748 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1749 MCContext &Ctx) const {
1750 // X86-64 uses RIP relative addressing based on the jump table label.
1751 if (Subtarget->isPICStyleRIPRel())
1752 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1754 // Otherwise, the reference is relative to the PIC base.
1755 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1758 // FIXME: Why this routine is here? Move to RegInfo!
1759 std::pair<const TargetRegisterClass*, uint8_t>
1760 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1761 const TargetRegisterClass *RRC = nullptr;
1763 switch (VT.SimpleTy) {
1765 return TargetLowering::findRepresentativeClass(VT);
1766 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1767 RRC = Subtarget->is64Bit() ?
1768 (const TargetRegisterClass*)&X86::GR64RegClass :
1769 (const TargetRegisterClass*)&X86::GR32RegClass;
1772 RRC = &X86::VR64RegClass;
1774 case MVT::f32: case MVT::f64:
1775 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1776 case MVT::v4f32: case MVT::v2f64:
1777 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1779 RRC = &X86::VR128RegClass;
1782 return std::make_pair(RRC, Cost);
1785 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1786 unsigned &Offset) const {
1787 if (!Subtarget->isTargetLinux())
1790 if (Subtarget->is64Bit()) {
1791 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1793 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1805 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1806 unsigned DestAS) const {
1807 assert(SrcAS != DestAS && "Expected different address spaces!");
1809 return SrcAS < 256 && DestAS < 256;
1812 //===----------------------------------------------------------------------===//
1813 // Return Value Calling Convention Implementation
1814 //===----------------------------------------------------------------------===//
1816 #include "X86GenCallingConv.inc"
1819 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1820 MachineFunction &MF, bool isVarArg,
1821 const SmallVectorImpl<ISD::OutputArg> &Outs,
1822 LLVMContext &Context) const {
1823 SmallVector<CCValAssign, 16> RVLocs;
1824 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1826 return CCInfo.CheckReturn(Outs, RetCC_X86);
1829 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1830 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1835 X86TargetLowering::LowerReturn(SDValue Chain,
1836 CallingConv::ID CallConv, bool isVarArg,
1837 const SmallVectorImpl<ISD::OutputArg> &Outs,
1838 const SmallVectorImpl<SDValue> &OutVals,
1839 SDLoc dl, SelectionDAG &DAG) const {
1840 MachineFunction &MF = DAG.getMachineFunction();
1841 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1843 SmallVector<CCValAssign, 16> RVLocs;
1844 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1845 RVLocs, *DAG.getContext());
1846 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1849 SmallVector<SDValue, 6> RetOps;
1850 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1851 // Operand #1 = Bytes To Pop
1852 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1855 // Copy the result values into the output registers.
1856 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1857 CCValAssign &VA = RVLocs[i];
1858 assert(VA.isRegLoc() && "Can only return in registers!");
1859 SDValue ValToCopy = OutVals[i];
1860 EVT ValVT = ValToCopy.getValueType();
1862 // Promote values to the appropriate types
1863 if (VA.getLocInfo() == CCValAssign::SExt)
1864 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1865 else if (VA.getLocInfo() == CCValAssign::ZExt)
1866 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1867 else if (VA.getLocInfo() == CCValAssign::AExt)
1868 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1869 else if (VA.getLocInfo() == CCValAssign::BCvt)
1870 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1872 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1873 "Unexpected FP-extend for return value.");
1875 // If this is x86-64, and we disabled SSE, we can't return FP values,
1876 // or SSE or MMX vectors.
1877 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1878 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1879 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1880 report_fatal_error("SSE register return with SSE disabled");
1882 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1883 // llvm-gcc has never done it right and no one has noticed, so this
1884 // should be OK for now.
1885 if (ValVT == MVT::f64 &&
1886 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1887 report_fatal_error("SSE2 register return with SSE2 disabled");
1889 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1890 // the RET instruction and handled by the FP Stackifier.
1891 if (VA.getLocReg() == X86::ST0 ||
1892 VA.getLocReg() == X86::ST1) {
1893 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1894 // change the value to the FP stack register class.
1895 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1896 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1897 RetOps.push_back(ValToCopy);
1898 // Don't emit a copytoreg.
1902 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1903 // which is returned in RAX / RDX.
1904 if (Subtarget->is64Bit()) {
1905 if (ValVT == MVT::x86mmx) {
1906 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1907 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1908 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1910 // If we don't have SSE2 available, convert to v4f32 so the generated
1911 // register is legal.
1912 if (!Subtarget->hasSSE2())
1913 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1918 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1919 Flag = Chain.getValue(1);
1920 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1923 // The x86-64 ABIs require that for returning structs by value we copy
1924 // the sret argument into %rax/%eax (depending on ABI) for the return.
1925 // Win32 requires us to put the sret argument to %eax as well.
1926 // We saved the argument into a virtual register in the entry block,
1927 // so now we copy the value out and into %rax/%eax.
1928 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1929 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1930 MachineFunction &MF = DAG.getMachineFunction();
1931 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1932 unsigned Reg = FuncInfo->getSRetReturnReg();
1934 "SRetReturnReg should have been set in LowerFormalArguments().");
1935 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1938 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1939 X86::RAX : X86::EAX;
1940 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1941 Flag = Chain.getValue(1);
1943 // RAX/EAX now acts like a return value.
1944 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1947 RetOps[0] = Chain; // Update chain.
1949 // Add the flag if we have it.
1951 RetOps.push_back(Flag);
1953 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1956 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1957 if (N->getNumValues() != 1)
1959 if (!N->hasNUsesOfValue(1, 0))
1962 SDValue TCChain = Chain;
1963 SDNode *Copy = *N->use_begin();
1964 if (Copy->getOpcode() == ISD::CopyToReg) {
1965 // If the copy has a glue operand, we conservatively assume it isn't safe to
1966 // perform a tail call.
1967 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1969 TCChain = Copy->getOperand(0);
1970 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1973 bool HasRet = false;
1974 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1976 if (UI->getOpcode() != X86ISD::RET_FLAG)
1989 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1990 ISD::NodeType ExtendKind) const {
1992 // TODO: Is this also valid on 32-bit?
1993 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1994 ReturnMVT = MVT::i8;
1996 ReturnMVT = MVT::i32;
1998 MVT MinVT = getRegisterType(ReturnMVT);
1999 return VT.bitsLT(MinVT) ? MinVT : VT;
2002 /// LowerCallResult - Lower the result values of a call into the
2003 /// appropriate copies out of appropriate physical registers.
2006 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2007 CallingConv::ID CallConv, bool isVarArg,
2008 const SmallVectorImpl<ISD::InputArg> &Ins,
2009 SDLoc dl, SelectionDAG &DAG,
2010 SmallVectorImpl<SDValue> &InVals) const {
2012 // Assign locations to each value returned by this call.
2013 SmallVector<CCValAssign, 16> RVLocs;
2014 bool Is64Bit = Subtarget->is64Bit();
2015 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2016 getTargetMachine(), RVLocs, *DAG.getContext());
2017 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2019 // Copy all of the result registers out of their specified physreg.
2020 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2021 CCValAssign &VA = RVLocs[i];
2022 EVT CopyVT = VA.getValVT();
2024 // If this is x86-64, and we disabled SSE, we can't return FP values
2025 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2026 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2027 report_fatal_error("SSE register return with SSE disabled");
2032 // If this is a call to a function that returns an fp value on the floating
2033 // point stack, we must guarantee the value is popped from the stack, so
2034 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2035 // if the return value is not used. We use the FpPOP_RETVAL instruction
2037 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2038 // If we prefer to use the value in xmm registers, copy it out as f80 and
2039 // use a truncate to move it from fp stack reg to xmm reg.
2040 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2041 SDValue Ops[] = { Chain, InFlag };
2042 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2043 MVT::Other, MVT::Glue, Ops), 1);
2044 Val = Chain.getValue(0);
2046 // Round the f80 to the right size, which also moves it to the appropriate
2048 if (CopyVT != VA.getValVT())
2049 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2050 // This truncation won't change the value.
2051 DAG.getIntPtrConstant(1));
2053 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2054 CopyVT, InFlag).getValue(1);
2055 Val = Chain.getValue(0);
2057 InFlag = Chain.getValue(2);
2058 InVals.push_back(Val);
2064 //===----------------------------------------------------------------------===//
2065 // C & StdCall & Fast Calling Convention implementation
2066 //===----------------------------------------------------------------------===//
2067 // StdCall calling convention seems to be standard for many Windows' API
2068 // routines and around. It differs from C calling convention just a little:
2069 // callee should clean up the stack, not caller. Symbols should be also
2070 // decorated in some fancy way :) It doesn't support any vector arguments.
2071 // For info on fast calling convention see Fast Calling Convention (tail call)
2072 // implementation LowerX86_32FastCCCallTo.
2074 /// CallIsStructReturn - Determines whether a call uses struct return
2076 enum StructReturnType {
2081 static StructReturnType
2082 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2084 return NotStructReturn;
2086 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2087 if (!Flags.isSRet())
2088 return NotStructReturn;
2089 if (Flags.isInReg())
2090 return RegStructReturn;
2091 return StackStructReturn;
2094 /// ArgsAreStructReturn - Determines whether a function uses struct
2095 /// return semantics.
2096 static StructReturnType
2097 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2099 return NotStructReturn;
2101 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2102 if (!Flags.isSRet())
2103 return NotStructReturn;
2104 if (Flags.isInReg())
2105 return RegStructReturn;
2106 return StackStructReturn;
2109 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2110 /// by "Src" to address "Dst" with size and alignment information specified by
2111 /// the specific parameter attribute. The copy will be passed as a byval
2112 /// function parameter.
2114 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2115 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2117 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2119 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2120 /*isVolatile*/false, /*AlwaysInline=*/true,
2121 MachinePointerInfo(), MachinePointerInfo());
2124 /// IsTailCallConvention - Return true if the calling convention is one that
2125 /// supports tail call optimization.
2126 static bool IsTailCallConvention(CallingConv::ID CC) {
2127 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2128 CC == CallingConv::HiPE);
2131 /// \brief Return true if the calling convention is a C calling convention.
2132 static bool IsCCallConvention(CallingConv::ID CC) {
2133 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2134 CC == CallingConv::X86_64_SysV);
2137 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2138 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2142 CallingConv::ID CalleeCC = CS.getCallingConv();
2143 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2149 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2150 /// a tailcall target by changing its ABI.
2151 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2152 bool GuaranteedTailCallOpt) {
2153 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2157 X86TargetLowering::LowerMemArgument(SDValue Chain,
2158 CallingConv::ID CallConv,
2159 const SmallVectorImpl<ISD::InputArg> &Ins,
2160 SDLoc dl, SelectionDAG &DAG,
2161 const CCValAssign &VA,
2162 MachineFrameInfo *MFI,
2164 // Create the nodes corresponding to a load from this parameter slot.
2165 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2166 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2167 getTargetMachine().Options.GuaranteedTailCallOpt);
2168 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2171 // If value is passed by pointer we have address passed instead of the value
2173 if (VA.getLocInfo() == CCValAssign::Indirect)
2174 ValVT = VA.getLocVT();
2176 ValVT = VA.getValVT();
2178 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2179 // changed with more analysis.
2180 // In case of tail call optimization mark all arguments mutable. Since they
2181 // could be overwritten by lowering of arguments in case of a tail call.
2182 if (Flags.isByVal()) {
2183 unsigned Bytes = Flags.getByValSize();
2184 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2185 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2186 return DAG.getFrameIndex(FI, getPointerTy());
2188 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2189 VA.getLocMemOffset(), isImmutable);
2190 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2191 return DAG.getLoad(ValVT, dl, Chain, FIN,
2192 MachinePointerInfo::getFixedStack(FI),
2193 false, false, false, 0);
2198 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2199 CallingConv::ID CallConv,
2201 const SmallVectorImpl<ISD::InputArg> &Ins,
2204 SmallVectorImpl<SDValue> &InVals)
2206 MachineFunction &MF = DAG.getMachineFunction();
2207 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2209 const Function* Fn = MF.getFunction();
2210 if (Fn->hasExternalLinkage() &&
2211 Subtarget->isTargetCygMing() &&
2212 Fn->getName() == "main")
2213 FuncInfo->setForceFramePointer(true);
2215 MachineFrameInfo *MFI = MF.getFrameInfo();
2216 bool Is64Bit = Subtarget->is64Bit();
2217 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2219 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2220 "Var args not supported with calling convention fastcc, ghc or hipe");
2222 // Assign locations to all of the incoming arguments.
2223 SmallVector<CCValAssign, 16> ArgLocs;
2224 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2225 ArgLocs, *DAG.getContext());
2227 // Allocate shadow area for Win64
2229 CCInfo.AllocateStack(32, 8);
2231 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2233 unsigned LastVal = ~0U;
2235 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2236 CCValAssign &VA = ArgLocs[i];
2237 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2239 assert(VA.getValNo() != LastVal &&
2240 "Don't support value assigned to multiple locs yet");
2242 LastVal = VA.getValNo();
2244 if (VA.isRegLoc()) {
2245 EVT RegVT = VA.getLocVT();
2246 const TargetRegisterClass *RC;
2247 if (RegVT == MVT::i32)
2248 RC = &X86::GR32RegClass;
2249 else if (Is64Bit && RegVT == MVT::i64)
2250 RC = &X86::GR64RegClass;
2251 else if (RegVT == MVT::f32)
2252 RC = &X86::FR32RegClass;
2253 else if (RegVT == MVT::f64)
2254 RC = &X86::FR64RegClass;
2255 else if (RegVT.is512BitVector())
2256 RC = &X86::VR512RegClass;
2257 else if (RegVT.is256BitVector())
2258 RC = &X86::VR256RegClass;
2259 else if (RegVT.is128BitVector())
2260 RC = &X86::VR128RegClass;
2261 else if (RegVT == MVT::x86mmx)
2262 RC = &X86::VR64RegClass;
2263 else if (RegVT == MVT::i1)
2264 RC = &X86::VK1RegClass;
2265 else if (RegVT == MVT::v8i1)
2266 RC = &X86::VK8RegClass;
2267 else if (RegVT == MVT::v16i1)
2268 RC = &X86::VK16RegClass;
2270 llvm_unreachable("Unknown argument type!");
2272 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2273 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2275 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2276 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2278 if (VA.getLocInfo() == CCValAssign::SExt)
2279 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2280 DAG.getValueType(VA.getValVT()));
2281 else if (VA.getLocInfo() == CCValAssign::ZExt)
2282 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2283 DAG.getValueType(VA.getValVT()));
2284 else if (VA.getLocInfo() == CCValAssign::BCvt)
2285 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2287 if (VA.isExtInLoc()) {
2288 // Handle MMX values passed in XMM regs.
2289 if (RegVT.isVector())
2290 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2292 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2295 assert(VA.isMemLoc());
2296 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2299 // If value is passed via pointer - do a load.
2300 if (VA.getLocInfo() == CCValAssign::Indirect)
2301 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2302 MachinePointerInfo(), false, false, false, 0);
2304 InVals.push_back(ArgValue);
2307 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2308 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2309 // The x86-64 ABIs require that for returning structs by value we copy
2310 // the sret argument into %rax/%eax (depending on ABI) for the return.
2311 // Win32 requires us to put the sret argument to %eax as well.
2312 // Save the argument into a virtual register so that we can access it
2313 // from the return points.
2314 if (Ins[i].Flags.isSRet()) {
2315 unsigned Reg = FuncInfo->getSRetReturnReg();
2317 MVT PtrTy = getPointerTy();
2318 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2319 FuncInfo->setSRetReturnReg(Reg);
2321 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2322 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2328 unsigned StackSize = CCInfo.getNextStackOffset();
2329 // Align stack specially for tail calls.
2330 if (FuncIsMadeTailCallSafe(CallConv,
2331 MF.getTarget().Options.GuaranteedTailCallOpt))
2332 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2334 // If the function takes variable number of arguments, make a frame index for
2335 // the start of the first vararg value... for expansion of llvm.va_start.
2337 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2338 CallConv != CallingConv::X86_ThisCall)) {
2339 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2342 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2344 // FIXME: We should really autogenerate these arrays
2345 static const MCPhysReg GPR64ArgRegsWin64[] = {
2346 X86::RCX, X86::RDX, X86::R8, X86::R9
2348 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2349 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2351 static const MCPhysReg XMMArgRegs64Bit[] = {
2352 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2353 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2355 const MCPhysReg *GPR64ArgRegs;
2356 unsigned NumXMMRegs = 0;
2359 // The XMM registers which might contain var arg parameters are shadowed
2360 // in their paired GPR. So we only need to save the GPR to their home
2362 TotalNumIntRegs = 4;
2363 GPR64ArgRegs = GPR64ArgRegsWin64;
2365 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2366 GPR64ArgRegs = GPR64ArgRegs64Bit;
2368 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2371 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2374 bool NoImplicitFloatOps = Fn->getAttributes().
2375 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2376 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2377 "SSE register cannot be used when SSE is disabled!");
2378 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2379 NoImplicitFloatOps) &&
2380 "SSE register cannot be used when SSE is disabled!");
2381 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2382 !Subtarget->hasSSE1())
2383 // Kernel mode asks for SSE to be disabled, so don't push them
2385 TotalNumXMMRegs = 0;
2388 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2389 // Get to the caller-allocated home save location. Add 8 to account
2390 // for the return address.
2391 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2392 FuncInfo->setRegSaveFrameIndex(
2393 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2394 // Fixup to set vararg frame on shadow area (4 x i64).
2396 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2398 // For X86-64, if there are vararg parameters that are passed via
2399 // registers, then we must store them to their spots on the stack so
2400 // they may be loaded by deferencing the result of va_next.
2401 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2402 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2403 FuncInfo->setRegSaveFrameIndex(
2404 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2408 // Store the integer parameter registers.
2409 SmallVector<SDValue, 8> MemOps;
2410 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2412 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2413 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2414 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2415 DAG.getIntPtrConstant(Offset));
2416 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2417 &X86::GR64RegClass);
2418 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2420 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2421 MachinePointerInfo::getFixedStack(
2422 FuncInfo->getRegSaveFrameIndex(), Offset),
2424 MemOps.push_back(Store);
2428 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2429 // Now store the XMM (fp + vector) parameter registers.
2430 SmallVector<SDValue, 11> SaveXMMOps;
2431 SaveXMMOps.push_back(Chain);
2433 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2434 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2435 SaveXMMOps.push_back(ALVal);
2437 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2438 FuncInfo->getRegSaveFrameIndex()));
2439 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2440 FuncInfo->getVarArgsFPOffset()));
2442 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2443 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2444 &X86::VR128RegClass);
2445 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2446 SaveXMMOps.push_back(Val);
2448 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2449 MVT::Other, SaveXMMOps));
2452 if (!MemOps.empty())
2453 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2457 // Some CCs need callee pop.
2458 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2459 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2460 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2462 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2463 // If this is an sret function, the return should pop the hidden pointer.
2464 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2465 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2466 argsAreStructReturn(Ins) == StackStructReturn)
2467 FuncInfo->setBytesToPopOnReturn(4);
2471 // RegSaveFrameIndex is X86-64 only.
2472 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2473 if (CallConv == CallingConv::X86_FastCall ||
2474 CallConv == CallingConv::X86_ThisCall)
2475 // fastcc functions can't have varargs.
2476 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2479 FuncInfo->setArgumentStackSize(StackSize);
2485 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2486 SDValue StackPtr, SDValue Arg,
2487 SDLoc dl, SelectionDAG &DAG,
2488 const CCValAssign &VA,
2489 ISD::ArgFlagsTy Flags) const {
2490 unsigned LocMemOffset = VA.getLocMemOffset();
2491 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2492 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2493 if (Flags.isByVal())
2494 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2496 return DAG.getStore(Chain, dl, Arg, PtrOff,
2497 MachinePointerInfo::getStack(LocMemOffset),
2501 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2502 /// optimization is performed and it is required.
2504 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2505 SDValue &OutRetAddr, SDValue Chain,
2506 bool IsTailCall, bool Is64Bit,
2507 int FPDiff, SDLoc dl) const {
2508 // Adjust the Return address stack slot.
2509 EVT VT = getPointerTy();
2510 OutRetAddr = getReturnAddressFrameIndex(DAG);
2512 // Load the "old" Return address.
2513 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2514 false, false, false, 0);
2515 return SDValue(OutRetAddr.getNode(), 1);
2518 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2519 /// optimization is performed and it is required (FPDiff!=0).
2520 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2521 SDValue Chain, SDValue RetAddrFrIdx,
2522 EVT PtrVT, unsigned SlotSize,
2523 int FPDiff, SDLoc dl) {
2524 // Store the return address to the appropriate stack slot.
2525 if (!FPDiff) return Chain;
2526 // Calculate the new stack slot for the return address.
2527 int NewReturnAddrFI =
2528 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2530 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2531 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2532 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2538 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2539 SmallVectorImpl<SDValue> &InVals) const {
2540 SelectionDAG &DAG = CLI.DAG;
2542 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2543 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2544 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2545 SDValue Chain = CLI.Chain;
2546 SDValue Callee = CLI.Callee;
2547 CallingConv::ID CallConv = CLI.CallConv;
2548 bool &isTailCall = CLI.IsTailCall;
2549 bool isVarArg = CLI.IsVarArg;
2551 MachineFunction &MF = DAG.getMachineFunction();
2552 bool Is64Bit = Subtarget->is64Bit();
2553 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2554 StructReturnType SR = callIsStructReturn(Outs);
2555 bool IsSibcall = false;
2557 if (MF.getTarget().Options.DisableTailCalls)
2560 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2562 // Force this to be a tail call. The verifier rules are enough to ensure
2563 // that we can lower this successfully without moving the return address
2566 } else if (isTailCall) {
2567 // Check if it's really possible to do a tail call.
2568 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2569 isVarArg, SR != NotStructReturn,
2570 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2571 Outs, OutVals, Ins, DAG);
2573 // Sibcalls are automatically detected tailcalls which do not require
2575 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2582 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2583 "Var args not supported with calling convention fastcc, ghc or hipe");
2585 // Analyze operands of the call, assigning locations to each operand.
2586 SmallVector<CCValAssign, 16> ArgLocs;
2587 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2588 ArgLocs, *DAG.getContext());
2590 // Allocate shadow area for Win64
2592 CCInfo.AllocateStack(32, 8);
2594 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2596 // Get a count of how many bytes are to be pushed on the stack.
2597 unsigned NumBytes = CCInfo.getNextStackOffset();
2599 // This is a sibcall. The memory operands are available in caller's
2600 // own caller's stack.
2602 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2603 IsTailCallConvention(CallConv))
2604 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2607 if (isTailCall && !IsSibcall && !IsMustTail) {
2608 // Lower arguments at fp - stackoffset + fpdiff.
2609 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2610 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2612 FPDiff = NumBytesCallerPushed - NumBytes;
2614 // Set the delta of movement of the returnaddr stackslot.
2615 // But only set if delta is greater than previous delta.
2616 if (FPDiff < X86Info->getTCReturnAddrDelta())
2617 X86Info->setTCReturnAddrDelta(FPDiff);
2620 unsigned NumBytesToPush = NumBytes;
2621 unsigned NumBytesToPop = NumBytes;
2623 // If we have an inalloca argument, all stack space has already been allocated
2624 // for us and be right at the top of the stack. We don't support multiple
2625 // arguments passed in memory when using inalloca.
2626 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2628 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2629 "an inalloca argument must be the only memory argument");
2633 Chain = DAG.getCALLSEQ_START(
2634 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2636 SDValue RetAddrFrIdx;
2637 // Load return address for tail calls.
2638 if (isTailCall && FPDiff)
2639 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2640 Is64Bit, FPDiff, dl);
2642 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2643 SmallVector<SDValue, 8> MemOpChains;
2646 // Walk the register/memloc assignments, inserting copies/loads. In the case
2647 // of tail call optimization arguments are handle later.
2648 const X86RegisterInfo *RegInfo =
2649 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2650 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2651 // Skip inalloca arguments, they have already been written.
2652 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2653 if (Flags.isInAlloca())
2656 CCValAssign &VA = ArgLocs[i];
2657 EVT RegVT = VA.getLocVT();
2658 SDValue Arg = OutVals[i];
2659 bool isByVal = Flags.isByVal();
2661 // Promote the value if needed.
2662 switch (VA.getLocInfo()) {
2663 default: llvm_unreachable("Unknown loc info!");
2664 case CCValAssign::Full: break;
2665 case CCValAssign::SExt:
2666 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2668 case CCValAssign::ZExt:
2669 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2671 case CCValAssign::AExt:
2672 if (RegVT.is128BitVector()) {
2673 // Special case: passing MMX values in XMM registers.
2674 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2675 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2676 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2678 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2680 case CCValAssign::BCvt:
2681 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2683 case CCValAssign::Indirect: {
2684 // Store the argument.
2685 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2686 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2687 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2688 MachinePointerInfo::getFixedStack(FI),
2695 if (VA.isRegLoc()) {
2696 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2697 if (isVarArg && IsWin64) {
2698 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2699 // shadow reg if callee is a varargs function.
2700 unsigned ShadowReg = 0;
2701 switch (VA.getLocReg()) {
2702 case X86::XMM0: ShadowReg = X86::RCX; break;
2703 case X86::XMM1: ShadowReg = X86::RDX; break;
2704 case X86::XMM2: ShadowReg = X86::R8; break;
2705 case X86::XMM3: ShadowReg = X86::R9; break;
2708 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2710 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2711 assert(VA.isMemLoc());
2712 if (!StackPtr.getNode())
2713 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2715 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2716 dl, DAG, VA, Flags));
2720 if (!MemOpChains.empty())
2721 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2723 if (Subtarget->isPICStyleGOT()) {
2724 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2727 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2728 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2730 // If we are tail calling and generating PIC/GOT style code load the
2731 // address of the callee into ECX. The value in ecx is used as target of
2732 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2733 // for tail calls on PIC/GOT architectures. Normally we would just put the
2734 // address of GOT into ebx and then call target@PLT. But for tail calls
2735 // ebx would be restored (since ebx is callee saved) before jumping to the
2738 // Note: The actual moving to ECX is done further down.
2739 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2740 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2741 !G->getGlobal()->hasProtectedVisibility())
2742 Callee = LowerGlobalAddress(Callee, DAG);
2743 else if (isa<ExternalSymbolSDNode>(Callee))
2744 Callee = LowerExternalSymbol(Callee, DAG);
2748 if (Is64Bit && isVarArg && !IsWin64) {
2749 // From AMD64 ABI document:
2750 // For calls that may call functions that use varargs or stdargs
2751 // (prototype-less calls or calls to functions containing ellipsis (...) in
2752 // the declaration) %al is used as hidden argument to specify the number
2753 // of SSE registers used. The contents of %al do not need to match exactly
2754 // the number of registers, but must be an ubound on the number of SSE
2755 // registers used and is in the range 0 - 8 inclusive.
2757 // Count the number of XMM registers allocated.
2758 static const MCPhysReg XMMArgRegs[] = {
2759 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2760 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2762 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2763 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2764 && "SSE registers cannot be used when SSE is disabled");
2766 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2767 DAG.getConstant(NumXMMRegs, MVT::i8)));
2770 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2771 // don't need this because the eligibility check rejects calls that require
2772 // shuffling arguments passed in memory.
2773 if (!IsSibcall && isTailCall) {
2774 // Force all the incoming stack arguments to be loaded from the stack
2775 // before any new outgoing arguments are stored to the stack, because the
2776 // outgoing stack slots may alias the incoming argument stack slots, and
2777 // the alias isn't otherwise explicit. This is slightly more conservative
2778 // than necessary, because it means that each store effectively depends
2779 // on every argument instead of just those arguments it would clobber.
2780 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2782 SmallVector<SDValue, 8> MemOpChains2;
2785 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2786 CCValAssign &VA = ArgLocs[i];
2789 assert(VA.isMemLoc());
2790 SDValue Arg = OutVals[i];
2791 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2792 // Skip inalloca arguments. They don't require any work.
2793 if (Flags.isInAlloca())
2795 // Create frame index.
2796 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2797 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2798 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2799 FIN = DAG.getFrameIndex(FI, getPointerTy());
2801 if (Flags.isByVal()) {
2802 // Copy relative to framepointer.
2803 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2804 if (!StackPtr.getNode())
2805 StackPtr = DAG.getCopyFromReg(Chain, dl,
2806 RegInfo->getStackRegister(),
2808 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2810 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2814 // Store relative to framepointer.
2815 MemOpChains2.push_back(
2816 DAG.getStore(ArgChain, dl, Arg, FIN,
2817 MachinePointerInfo::getFixedStack(FI),
2822 if (!MemOpChains2.empty())
2823 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2825 // Store the return address to the appropriate stack slot.
2826 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2827 getPointerTy(), RegInfo->getSlotSize(),
2831 // Build a sequence of copy-to-reg nodes chained together with token chain
2832 // and flag operands which copy the outgoing args into registers.
2834 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2835 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2836 RegsToPass[i].second, InFlag);
2837 InFlag = Chain.getValue(1);
2840 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2841 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2842 // In the 64-bit large code model, we have to make all calls
2843 // through a register, since the call instruction's 32-bit
2844 // pc-relative offset may not be large enough to hold the whole
2846 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2847 // If the callee is a GlobalAddress node (quite common, every direct call
2848 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2851 // We should use extra load for direct calls to dllimported functions in
2853 const GlobalValue *GV = G->getGlobal();
2854 if (!GV->hasDLLImportStorageClass()) {
2855 unsigned char OpFlags = 0;
2856 bool ExtraLoad = false;
2857 unsigned WrapperKind = ISD::DELETED_NODE;
2859 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2860 // external symbols most go through the PLT in PIC mode. If the symbol
2861 // has hidden or protected visibility, or if it is static or local, then
2862 // we don't need to use the PLT - we can directly call it.
2863 if (Subtarget->isTargetELF() &&
2864 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2865 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2866 OpFlags = X86II::MO_PLT;
2867 } else if (Subtarget->isPICStyleStubAny() &&
2868 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2869 (!Subtarget->getTargetTriple().isMacOSX() ||
2870 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2871 // PC-relative references to external symbols should go through $stub,
2872 // unless we're building with the leopard linker or later, which
2873 // automatically synthesizes these stubs.
2874 OpFlags = X86II::MO_DARWIN_STUB;
2875 } else if (Subtarget->isPICStyleRIPRel() &&
2876 isa<Function>(GV) &&
2877 cast<Function>(GV)->getAttributes().
2878 hasAttribute(AttributeSet::FunctionIndex,
2879 Attribute::NonLazyBind)) {
2880 // If the function is marked as non-lazy, generate an indirect call
2881 // which loads from the GOT directly. This avoids runtime overhead
2882 // at the cost of eager binding (and one extra byte of encoding).
2883 OpFlags = X86II::MO_GOTPCREL;
2884 WrapperKind = X86ISD::WrapperRIP;
2888 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2889 G->getOffset(), OpFlags);
2891 // Add a wrapper if needed.
2892 if (WrapperKind != ISD::DELETED_NODE)
2893 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2894 // Add extra indirection if needed.
2896 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2897 MachinePointerInfo::getGOT(),
2898 false, false, false, 0);
2900 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2901 unsigned char OpFlags = 0;
2903 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2904 // external symbols should go through the PLT.
2905 if (Subtarget->isTargetELF() &&
2906 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2907 OpFlags = X86II::MO_PLT;
2908 } else if (Subtarget->isPICStyleStubAny() &&
2909 (!Subtarget->getTargetTriple().isMacOSX() ||
2910 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2911 // PC-relative references to external symbols should go through $stub,
2912 // unless we're building with the leopard linker or later, which
2913 // automatically synthesizes these stubs.
2914 OpFlags = X86II::MO_DARWIN_STUB;
2917 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2921 // Returns a chain & a flag for retval copy to use.
2922 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2923 SmallVector<SDValue, 8> Ops;
2925 if (!IsSibcall && isTailCall) {
2926 Chain = DAG.getCALLSEQ_END(Chain,
2927 DAG.getIntPtrConstant(NumBytesToPop, true),
2928 DAG.getIntPtrConstant(0, true), InFlag, dl);
2929 InFlag = Chain.getValue(1);
2932 Ops.push_back(Chain);
2933 Ops.push_back(Callee);
2936 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2938 // Add argument registers to the end of the list so that they are known live
2940 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2941 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2942 RegsToPass[i].second.getValueType()));
2944 // Add a register mask operand representing the call-preserved registers.
2945 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2946 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2947 assert(Mask && "Missing call preserved mask for calling convention");
2948 Ops.push_back(DAG.getRegisterMask(Mask));
2950 if (InFlag.getNode())
2951 Ops.push_back(InFlag);
2955 //// If this is the first return lowered for this function, add the regs
2956 //// to the liveout set for the function.
2957 // This isn't right, although it's probably harmless on x86; liveouts
2958 // should be computed from returns not tail calls. Consider a void
2959 // function making a tail call to a function returning int.
2960 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2963 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2964 InFlag = Chain.getValue(1);
2966 // Create the CALLSEQ_END node.
2967 unsigned NumBytesForCalleeToPop;
2968 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2969 getTargetMachine().Options.GuaranteedTailCallOpt))
2970 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2971 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2972 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2973 SR == StackStructReturn)
2974 // If this is a call to a struct-return function, the callee
2975 // pops the hidden struct pointer, so we have to push it back.
2976 // This is common for Darwin/X86, Linux & Mingw32 targets.
2977 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2978 NumBytesForCalleeToPop = 4;
2980 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2982 // Returns a flag for retval copy to use.
2984 Chain = DAG.getCALLSEQ_END(Chain,
2985 DAG.getIntPtrConstant(NumBytesToPop, true),
2986 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2989 InFlag = Chain.getValue(1);
2992 // Handle result values, copying them out of physregs into vregs that we
2994 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2995 Ins, dl, DAG, InVals);
2998 //===----------------------------------------------------------------------===//
2999 // Fast Calling Convention (tail call) implementation
3000 //===----------------------------------------------------------------------===//
3002 // Like std call, callee cleans arguments, convention except that ECX is
3003 // reserved for storing the tail called function address. Only 2 registers are
3004 // free for argument passing (inreg). Tail call optimization is performed
3006 // * tailcallopt is enabled
3007 // * caller/callee are fastcc
3008 // On X86_64 architecture with GOT-style position independent code only local
3009 // (within module) calls are supported at the moment.
3010 // To keep the stack aligned according to platform abi the function
3011 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3012 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3013 // If a tail called function callee has more arguments than the caller the
3014 // caller needs to make sure that there is room to move the RETADDR to. This is
3015 // achieved by reserving an area the size of the argument delta right after the
3016 // original REtADDR, but before the saved framepointer or the spilled registers
3017 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3029 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3030 /// for a 16 byte align requirement.
3032 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3033 SelectionDAG& DAG) const {
3034 MachineFunction &MF = DAG.getMachineFunction();
3035 const TargetMachine &TM = MF.getTarget();
3036 const X86RegisterInfo *RegInfo =
3037 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3038 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3039 unsigned StackAlignment = TFI.getStackAlignment();
3040 uint64_t AlignMask = StackAlignment - 1;
3041 int64_t Offset = StackSize;
3042 unsigned SlotSize = RegInfo->getSlotSize();
3043 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3044 // Number smaller than 12 so just add the difference.
3045 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3047 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3048 Offset = ((~AlignMask) & Offset) + StackAlignment +
3049 (StackAlignment-SlotSize);
3054 /// MatchingStackOffset - Return true if the given stack call argument is
3055 /// already available in the same position (relatively) of the caller's
3056 /// incoming argument stack.
3058 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3059 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3060 const X86InstrInfo *TII) {
3061 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3063 if (Arg.getOpcode() == ISD::CopyFromReg) {
3064 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3065 if (!TargetRegisterInfo::isVirtualRegister(VR))
3067 MachineInstr *Def = MRI->getVRegDef(VR);
3070 if (!Flags.isByVal()) {
3071 if (!TII->isLoadFromStackSlot(Def, FI))
3074 unsigned Opcode = Def->getOpcode();
3075 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3076 Def->getOperand(1).isFI()) {
3077 FI = Def->getOperand(1).getIndex();
3078 Bytes = Flags.getByValSize();
3082 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3083 if (Flags.isByVal())
3084 // ByVal argument is passed in as a pointer but it's now being
3085 // dereferenced. e.g.
3086 // define @foo(%struct.X* %A) {
3087 // tail call @bar(%struct.X* byval %A)
3090 SDValue Ptr = Ld->getBasePtr();
3091 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3094 FI = FINode->getIndex();
3095 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3096 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3097 FI = FINode->getIndex();
3098 Bytes = Flags.getByValSize();
3102 assert(FI != INT_MAX);
3103 if (!MFI->isFixedObjectIndex(FI))
3105 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3108 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3109 /// for tail call optimization. Targets which want to do tail call
3110 /// optimization should implement this function.
3112 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3113 CallingConv::ID CalleeCC,
3115 bool isCalleeStructRet,
3116 bool isCallerStructRet,
3118 const SmallVectorImpl<ISD::OutputArg> &Outs,
3119 const SmallVectorImpl<SDValue> &OutVals,
3120 const SmallVectorImpl<ISD::InputArg> &Ins,
3121 SelectionDAG &DAG) const {
3122 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3125 // If -tailcallopt is specified, make fastcc functions tail-callable.
3126 const MachineFunction &MF = DAG.getMachineFunction();
3127 const Function *CallerF = MF.getFunction();
3129 // If the function return type is x86_fp80 and the callee return type is not,
3130 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3131 // perform a tailcall optimization here.
3132 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3135 CallingConv::ID CallerCC = CallerF->getCallingConv();
3136 bool CCMatch = CallerCC == CalleeCC;
3137 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3138 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3140 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3141 if (IsTailCallConvention(CalleeCC) && CCMatch)
3146 // Look for obvious safe cases to perform tail call optimization that do not
3147 // require ABI changes. This is what gcc calls sibcall.
3149 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3150 // emit a special epilogue.
3151 const X86RegisterInfo *RegInfo =
3152 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3153 if (RegInfo->needsStackRealignment(MF))
3156 // Also avoid sibcall optimization if either caller or callee uses struct
3157 // return semantics.
3158 if (isCalleeStructRet || isCallerStructRet)
3161 // An stdcall/thiscall caller is expected to clean up its arguments; the
3162 // callee isn't going to do that.
3163 // FIXME: this is more restrictive than needed. We could produce a tailcall
3164 // when the stack adjustment matches. For example, with a thiscall that takes
3165 // only one argument.
3166 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3167 CallerCC == CallingConv::X86_ThisCall))
3170 // Do not sibcall optimize vararg calls unless all arguments are passed via
3172 if (isVarArg && !Outs.empty()) {
3174 // Optimizing for varargs on Win64 is unlikely to be safe without
3175 // additional testing.
3176 if (IsCalleeWin64 || IsCallerWin64)
3179 SmallVector<CCValAssign, 16> ArgLocs;
3180 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3181 getTargetMachine(), ArgLocs, *DAG.getContext());
3183 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3184 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3185 if (!ArgLocs[i].isRegLoc())
3189 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3190 // stack. Therefore, if it's not used by the call it is not safe to optimize
3191 // this into a sibcall.
3192 bool Unused = false;
3193 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3200 SmallVector<CCValAssign, 16> RVLocs;
3201 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3202 getTargetMachine(), RVLocs, *DAG.getContext());
3203 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3204 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3205 CCValAssign &VA = RVLocs[i];
3206 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3211 // If the calling conventions do not match, then we'd better make sure the
3212 // results are returned in the same way as what the caller expects.
3214 SmallVector<CCValAssign, 16> RVLocs1;
3215 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3216 getTargetMachine(), RVLocs1, *DAG.getContext());
3217 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3219 SmallVector<CCValAssign, 16> RVLocs2;
3220 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3221 getTargetMachine(), RVLocs2, *DAG.getContext());
3222 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3224 if (RVLocs1.size() != RVLocs2.size())
3226 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3227 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3229 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3231 if (RVLocs1[i].isRegLoc()) {
3232 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3235 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3241 // If the callee takes no arguments then go on to check the results of the
3243 if (!Outs.empty()) {
3244 // Check if stack adjustment is needed. For now, do not do this if any
3245 // argument is passed on the stack.
3246 SmallVector<CCValAssign, 16> ArgLocs;
3247 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3248 getTargetMachine(), ArgLocs, *DAG.getContext());
3250 // Allocate shadow area for Win64
3252 CCInfo.AllocateStack(32, 8);
3254 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3255 if (CCInfo.getNextStackOffset()) {
3256 MachineFunction &MF = DAG.getMachineFunction();
3257 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3260 // Check if the arguments are already laid out in the right way as
3261 // the caller's fixed stack objects.
3262 MachineFrameInfo *MFI = MF.getFrameInfo();
3263 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3264 const X86InstrInfo *TII =
3265 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3266 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3267 CCValAssign &VA = ArgLocs[i];
3268 SDValue Arg = OutVals[i];
3269 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3270 if (VA.getLocInfo() == CCValAssign::Indirect)
3272 if (!VA.isRegLoc()) {
3273 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3280 // If the tailcall address may be in a register, then make sure it's
3281 // possible to register allocate for it. In 32-bit, the call address can
3282 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3283 // callee-saved registers are restored. These happen to be the same
3284 // registers used to pass 'inreg' arguments so watch out for those.
3285 if (!Subtarget->is64Bit() &&
3286 ((!isa<GlobalAddressSDNode>(Callee) &&
3287 !isa<ExternalSymbolSDNode>(Callee)) ||
3288 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3289 unsigned NumInRegs = 0;
3290 // In PIC we need an extra register to formulate the address computation
3292 unsigned MaxInRegs =
3293 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3295 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3296 CCValAssign &VA = ArgLocs[i];
3299 unsigned Reg = VA.getLocReg();
3302 case X86::EAX: case X86::EDX: case X86::ECX:
3303 if (++NumInRegs == MaxInRegs)
3315 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3316 const TargetLibraryInfo *libInfo) const {
3317 return X86::createFastISel(funcInfo, libInfo);
3320 //===----------------------------------------------------------------------===//
3321 // Other Lowering Hooks
3322 //===----------------------------------------------------------------------===//
3324 static bool MayFoldLoad(SDValue Op) {
3325 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3328 static bool MayFoldIntoStore(SDValue Op) {
3329 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3332 static bool isTargetShuffle(unsigned Opcode) {
3334 default: return false;
3335 case X86ISD::PSHUFD:
3336 case X86ISD::PSHUFHW:
3337 case X86ISD::PSHUFLW:
3339 case X86ISD::PALIGNR:
3340 case X86ISD::MOVLHPS:
3341 case X86ISD::MOVLHPD:
3342 case X86ISD::MOVHLPS:
3343 case X86ISD::MOVLPS:
3344 case X86ISD::MOVLPD:
3345 case X86ISD::MOVSHDUP:
3346 case X86ISD::MOVSLDUP:
3347 case X86ISD::MOVDDUP:
3350 case X86ISD::UNPCKL:
3351 case X86ISD::UNPCKH:
3352 case X86ISD::VPERMILP:
3353 case X86ISD::VPERM2X128:
3354 case X86ISD::VPERMI:
3359 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3360 SDValue V1, SelectionDAG &DAG) {
3362 default: llvm_unreachable("Unknown x86 shuffle node");
3363 case X86ISD::MOVSHDUP:
3364 case X86ISD::MOVSLDUP:
3365 case X86ISD::MOVDDUP:
3366 return DAG.getNode(Opc, dl, VT, V1);
3370 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3371 SDValue V1, unsigned TargetMask,
3372 SelectionDAG &DAG) {
3374 default: llvm_unreachable("Unknown x86 shuffle node");
3375 case X86ISD::PSHUFD:
3376 case X86ISD::PSHUFHW:
3377 case X86ISD::PSHUFLW:
3378 case X86ISD::VPERMILP:
3379 case X86ISD::VPERMI:
3380 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3384 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3385 SDValue V1, SDValue V2, unsigned TargetMask,
3386 SelectionDAG &DAG) {
3388 default: llvm_unreachable("Unknown x86 shuffle node");
3389 case X86ISD::PALIGNR:
3391 case X86ISD::VPERM2X128:
3392 return DAG.getNode(Opc, dl, VT, V1, V2,
3393 DAG.getConstant(TargetMask, MVT::i8));
3397 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3398 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3400 default: llvm_unreachable("Unknown x86 shuffle node");
3401 case X86ISD::MOVLHPS:
3402 case X86ISD::MOVLHPD:
3403 case X86ISD::MOVHLPS:
3404 case X86ISD::MOVLPS:
3405 case X86ISD::MOVLPD:
3408 case X86ISD::UNPCKL:
3409 case X86ISD::UNPCKH:
3410 return DAG.getNode(Opc, dl, VT, V1, V2);
3414 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3415 MachineFunction &MF = DAG.getMachineFunction();
3416 const X86RegisterInfo *RegInfo =
3417 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3418 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3419 int ReturnAddrIndex = FuncInfo->getRAIndex();
3421 if (ReturnAddrIndex == 0) {
3422 // Set up a frame object for the return address.
3423 unsigned SlotSize = RegInfo->getSlotSize();
3424 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3427 FuncInfo->setRAIndex(ReturnAddrIndex);
3430 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3433 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3434 bool hasSymbolicDisplacement) {
3435 // Offset should fit into 32 bit immediate field.
3436 if (!isInt<32>(Offset))
3439 // If we don't have a symbolic displacement - we don't have any extra
3441 if (!hasSymbolicDisplacement)
3444 // FIXME: Some tweaks might be needed for medium code model.
3445 if (M != CodeModel::Small && M != CodeModel::Kernel)
3448 // For small code model we assume that latest object is 16MB before end of 31
3449 // bits boundary. We may also accept pretty large negative constants knowing
3450 // that all objects are in the positive half of address space.
3451 if (M == CodeModel::Small && Offset < 16*1024*1024)
3454 // For kernel code model we know that all object resist in the negative half
3455 // of 32bits address space. We may not accept negative offsets, since they may
3456 // be just off and we may accept pretty large positive ones.
3457 if (M == CodeModel::Kernel && Offset > 0)
3463 /// isCalleePop - Determines whether the callee is required to pop its
3464 /// own arguments. Callee pop is necessary to support tail calls.
3465 bool X86::isCalleePop(CallingConv::ID CallingConv,
3466 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3470 switch (CallingConv) {
3473 case CallingConv::X86_StdCall:
3475 case CallingConv::X86_FastCall:
3477 case CallingConv::X86_ThisCall:
3479 case CallingConv::Fast:
3481 case CallingConv::GHC:
3483 case CallingConv::HiPE:
3488 /// \brief Return true if the condition is an unsigned comparison operation.
3489 static bool isX86CCUnsigned(unsigned X86CC) {
3491 default: llvm_unreachable("Invalid integer condition!");
3492 case X86::COND_E: return true;
3493 case X86::COND_G: return false;
3494 case X86::COND_GE: return false;
3495 case X86::COND_L: return false;
3496 case X86::COND_LE: return false;
3497 case X86::COND_NE: return true;
3498 case X86::COND_B: return true;
3499 case X86::COND_A: return true;
3500 case X86::COND_BE: return true;
3501 case X86::COND_AE: return true;
3503 llvm_unreachable("covered switch fell through?!");
3506 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3507 /// specific condition code, returning the condition code and the LHS/RHS of the
3508 /// comparison to make.
3509 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3510 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3512 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3513 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3514 // X > -1 -> X == 0, jump !sign.
3515 RHS = DAG.getConstant(0, RHS.getValueType());
3516 return X86::COND_NS;
3518 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3519 // X < 0 -> X == 0, jump on sign.
3522 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3524 RHS = DAG.getConstant(0, RHS.getValueType());
3525 return X86::COND_LE;
3529 switch (SetCCOpcode) {
3530 default: llvm_unreachable("Invalid integer condition!");
3531 case ISD::SETEQ: return X86::COND_E;
3532 case ISD::SETGT: return X86::COND_G;
3533 case ISD::SETGE: return X86::COND_GE;
3534 case ISD::SETLT: return X86::COND_L;
3535 case ISD::SETLE: return X86::COND_LE;
3536 case ISD::SETNE: return X86::COND_NE;
3537 case ISD::SETULT: return X86::COND_B;
3538 case ISD::SETUGT: return X86::COND_A;
3539 case ISD::SETULE: return X86::COND_BE;
3540 case ISD::SETUGE: return X86::COND_AE;
3544 // First determine if it is required or is profitable to flip the operands.
3546 // If LHS is a foldable load, but RHS is not, flip the condition.
3547 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3548 !ISD::isNON_EXTLoad(RHS.getNode())) {
3549 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3550 std::swap(LHS, RHS);
3553 switch (SetCCOpcode) {
3559 std::swap(LHS, RHS);
3563 // On a floating point condition, the flags are set as follows:
3565 // 0 | 0 | 0 | X > Y
3566 // 0 | 0 | 1 | X < Y
3567 // 1 | 0 | 0 | X == Y
3568 // 1 | 1 | 1 | unordered
3569 switch (SetCCOpcode) {
3570 default: llvm_unreachable("Condcode should be pre-legalized away");
3572 case ISD::SETEQ: return X86::COND_E;
3573 case ISD::SETOLT: // flipped
3575 case ISD::SETGT: return X86::COND_A;
3576 case ISD::SETOLE: // flipped
3578 case ISD::SETGE: return X86::COND_AE;
3579 case ISD::SETUGT: // flipped
3581 case ISD::SETLT: return X86::COND_B;
3582 case ISD::SETUGE: // flipped
3584 case ISD::SETLE: return X86::COND_BE;
3586 case ISD::SETNE: return X86::COND_NE;
3587 case ISD::SETUO: return X86::COND_P;
3588 case ISD::SETO: return X86::COND_NP;
3590 case ISD::SETUNE: return X86::COND_INVALID;
3594 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3595 /// code. Current x86 isa includes the following FP cmov instructions:
3596 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3597 static bool hasFPCMov(unsigned X86CC) {
3613 /// isFPImmLegal - Returns true if the target can instruction select the
3614 /// specified FP immediate natively. If false, the legalizer will
3615 /// materialize the FP immediate as a load from a constant pool.
3616 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3617 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3618 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3624 /// \brief Returns true if it is beneficial to convert a load of a constant
3625 /// to just the constant itself.
3626 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3628 assert(Ty->isIntegerTy());
3630 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3631 if (BitSize == 0 || BitSize > 64)
3636 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3637 /// the specified range (L, H].
3638 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3639 return (Val < 0) || (Val >= Low && Val < Hi);
3642 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3643 /// specified value.
3644 static bool isUndefOrEqual(int Val, int CmpVal) {
3645 return (Val < 0 || Val == CmpVal);
3648 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3649 /// from position Pos and ending in Pos+Size, falls within the specified
3650 /// sequential range (L, L+Pos]. or is undef.
3651 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3652 unsigned Pos, unsigned Size, int Low) {
3653 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3654 if (!isUndefOrEqual(Mask[i], Low))
3659 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3660 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3661 /// the second operand.
3662 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3663 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3664 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3665 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3666 return (Mask[0] < 2 && Mask[1] < 2);
3670 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3671 /// is suitable for input to PSHUFHW.
3672 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3673 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3676 // Lower quadword copied in order or undef.
3677 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3680 // Upper quadword shuffled.
3681 for (unsigned i = 4; i != 8; ++i)
3682 if (!isUndefOrInRange(Mask[i], 4, 8))
3685 if (VT == MVT::v16i16) {
3686 // Lower quadword copied in order or undef.
3687 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3690 // Upper quadword shuffled.
3691 for (unsigned i = 12; i != 16; ++i)
3692 if (!isUndefOrInRange(Mask[i], 12, 16))
3699 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3700 /// is suitable for input to PSHUFLW.
3701 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3702 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3705 // Upper quadword copied in order.
3706 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3709 // Lower quadword shuffled.
3710 for (unsigned i = 0; i != 4; ++i)
3711 if (!isUndefOrInRange(Mask[i], 0, 4))
3714 if (VT == MVT::v16i16) {
3715 // Upper quadword copied in order.
3716 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3719 // Lower quadword shuffled.
3720 for (unsigned i = 8; i != 12; ++i)
3721 if (!isUndefOrInRange(Mask[i], 8, 12))
3728 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3729 /// is suitable for input to PALIGNR.
3730 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3731 const X86Subtarget *Subtarget) {
3732 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3733 (VT.is256BitVector() && !Subtarget->hasInt256()))
3736 unsigned NumElts = VT.getVectorNumElements();
3737 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3738 unsigned NumLaneElts = NumElts/NumLanes;
3740 // Do not handle 64-bit element shuffles with palignr.
3741 if (NumLaneElts == 2)
3744 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3746 for (i = 0; i != NumLaneElts; ++i) {
3751 // Lane is all undef, go to next lane
3752 if (i == NumLaneElts)
3755 int Start = Mask[i+l];
3757 // Make sure its in this lane in one of the sources
3758 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3759 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3762 // If not lane 0, then we must match lane 0
3763 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3766 // Correct second source to be contiguous with first source
3767 if (Start >= (int)NumElts)
3768 Start -= NumElts - NumLaneElts;
3770 // Make sure we're shifting in the right direction.
3771 if (Start <= (int)(i+l))
3776 // Check the rest of the elements to see if they are consecutive.
3777 for (++i; i != NumLaneElts; ++i) {
3778 int Idx = Mask[i+l];
3780 // Make sure its in this lane
3781 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3782 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3785 // If not lane 0, then we must match lane 0
3786 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3789 if (Idx >= (int)NumElts)
3790 Idx -= NumElts - NumLaneElts;
3792 if (!isUndefOrEqual(Idx, Start+i))
3801 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3802 /// the two vector operands have swapped position.
3803 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3804 unsigned NumElems) {
3805 for (unsigned i = 0; i != NumElems; ++i) {
3809 else if (idx < (int)NumElems)
3810 Mask[i] = idx + NumElems;
3812 Mask[i] = idx - NumElems;
3816 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3817 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3818 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3819 /// reverse of what x86 shuffles want.
3820 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3822 unsigned NumElems = VT.getVectorNumElements();
3823 unsigned NumLanes = VT.getSizeInBits()/128;
3824 unsigned NumLaneElems = NumElems/NumLanes;
3826 if (NumLaneElems != 2 && NumLaneElems != 4)
3829 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3830 bool symetricMaskRequired =
3831 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3833 // VSHUFPSY divides the resulting vector into 4 chunks.
3834 // The sources are also splitted into 4 chunks, and each destination
3835 // chunk must come from a different source chunk.
3837 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3838 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3840 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3841 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3843 // VSHUFPDY divides the resulting vector into 4 chunks.
3844 // The sources are also splitted into 4 chunks, and each destination
3845 // chunk must come from a different source chunk.
3847 // SRC1 => X3 X2 X1 X0
3848 // SRC2 => Y3 Y2 Y1 Y0
3850 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3852 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3853 unsigned HalfLaneElems = NumLaneElems/2;
3854 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3855 for (unsigned i = 0; i != NumLaneElems; ++i) {
3856 int Idx = Mask[i+l];
3857 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3858 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3860 // For VSHUFPSY, the mask of the second half must be the same as the
3861 // first but with the appropriate offsets. This works in the same way as
3862 // VPERMILPS works with masks.
3863 if (!symetricMaskRequired || Idx < 0)
3865 if (MaskVal[i] < 0) {
3866 MaskVal[i] = Idx - l;
3869 if ((signed)(Idx - l) != MaskVal[i])
3877 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3878 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3879 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3880 if (!VT.is128BitVector())
3883 unsigned NumElems = VT.getVectorNumElements();
3888 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3889 return isUndefOrEqual(Mask[0], 6) &&
3890 isUndefOrEqual(Mask[1], 7) &&
3891 isUndefOrEqual(Mask[2], 2) &&
3892 isUndefOrEqual(Mask[3], 3);
3895 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3896 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3898 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3899 if (!VT.is128BitVector())
3902 unsigned NumElems = VT.getVectorNumElements();
3907 return isUndefOrEqual(Mask[0], 2) &&
3908 isUndefOrEqual(Mask[1], 3) &&
3909 isUndefOrEqual(Mask[2], 2) &&
3910 isUndefOrEqual(Mask[3], 3);
3913 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3914 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3915 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3916 if (!VT.is128BitVector())
3919 unsigned NumElems = VT.getVectorNumElements();
3921 if (NumElems != 2 && NumElems != 4)
3924 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3925 if (!isUndefOrEqual(Mask[i], i + NumElems))
3928 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3929 if (!isUndefOrEqual(Mask[i], i))
3935 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3937 static bool isMOVLHPSMask(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))
3950 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3951 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3957 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3958 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3959 /// i. e: If all but one element come from the same vector.
3960 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3961 // TODO: Deal with AVX's VINSERTPS
3962 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3965 unsigned CorrectPosV1 = 0;
3966 unsigned CorrectPosV2 = 0;
3967 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3968 if (Mask[i] == -1) {
3976 else if (Mask[i] == i + 4)
3980 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3981 // We have 3 elements (undefs count as elements from any vector) from one
3982 // vector, and one from another.
3989 // Some special combinations that can be optimized.
3992 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3993 SelectionDAG &DAG) {
3994 MVT VT = SVOp->getSimpleValueType(0);
3997 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4000 ArrayRef<int> Mask = SVOp->getMask();
4002 // These are the special masks that may be optimized.
4003 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4004 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4005 bool MatchEvenMask = true;
4006 bool MatchOddMask = true;
4007 for (int i=0; i<8; ++i) {
4008 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4009 MatchEvenMask = false;
4010 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4011 MatchOddMask = false;
4014 if (!MatchEvenMask && !MatchOddMask)
4017 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4019 SDValue Op0 = SVOp->getOperand(0);
4020 SDValue Op1 = SVOp->getOperand(1);
4022 if (MatchEvenMask) {
4023 // Shift the second operand right to 32 bits.
4024 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4025 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4027 // Shift the first operand left to 32 bits.
4028 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4029 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4031 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4032 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4035 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4036 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4037 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4038 bool HasInt256, bool V2IsSplat = false) {
4040 assert(VT.getSizeInBits() >= 128 &&
4041 "Unsupported vector type for unpckl");
4043 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4045 unsigned NumOf256BitLanes;
4046 unsigned NumElts = VT.getVectorNumElements();
4047 if (VT.is256BitVector()) {
4048 if (NumElts != 4 && NumElts != 8 &&
4049 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4052 NumOf256BitLanes = 1;
4053 } else if (VT.is512BitVector()) {
4054 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4055 "Unsupported vector type for unpckh");
4057 NumOf256BitLanes = 2;
4060 NumOf256BitLanes = 1;
4063 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4064 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4066 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4067 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4068 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4069 int BitI = Mask[l256*NumEltsInStride+l+i];
4070 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4071 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4073 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4075 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4083 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4084 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4085 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4086 bool HasInt256, bool V2IsSplat = false) {
4087 assert(VT.getSizeInBits() >= 128 &&
4088 "Unsupported vector type for unpckh");
4090 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4092 unsigned NumOf256BitLanes;
4093 unsigned NumElts = VT.getVectorNumElements();
4094 if (VT.is256BitVector()) {
4095 if (NumElts != 4 && NumElts != 8 &&
4096 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4099 NumOf256BitLanes = 1;
4100 } else if (VT.is512BitVector()) {
4101 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4102 "Unsupported vector type for unpckh");
4104 NumOf256BitLanes = 2;
4107 NumOf256BitLanes = 1;
4110 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4111 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4113 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4114 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4115 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4116 int BitI = Mask[l256*NumEltsInStride+l+i];
4117 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4118 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4120 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4122 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4130 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4131 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4133 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4134 unsigned NumElts = VT.getVectorNumElements();
4135 bool Is256BitVec = VT.is256BitVector();
4137 if (VT.is512BitVector())
4139 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4140 "Unsupported vector type for unpckh");
4142 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4143 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4146 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4147 // FIXME: Need a better way to get rid of this, there's no latency difference
4148 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4149 // the former later. We should also remove the "_undef" special mask.
4150 if (NumElts == 4 && Is256BitVec)
4153 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4154 // independently on 128-bit lanes.
4155 unsigned NumLanes = VT.getSizeInBits()/128;
4156 unsigned NumLaneElts = NumElts/NumLanes;
4158 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4159 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4160 int BitI = Mask[l+i];
4161 int BitI1 = Mask[l+i+1];
4163 if (!isUndefOrEqual(BitI, j))
4165 if (!isUndefOrEqual(BitI1, j))
4173 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4174 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4176 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4177 unsigned NumElts = VT.getVectorNumElements();
4179 if (VT.is512BitVector())
4182 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4183 "Unsupported vector type for unpckh");
4185 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4186 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4189 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4190 // independently on 128-bit lanes.
4191 unsigned NumLanes = VT.getSizeInBits()/128;
4192 unsigned NumLaneElts = NumElts/NumLanes;
4194 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4195 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4196 int BitI = Mask[l+i];
4197 int BitI1 = Mask[l+i+1];
4198 if (!isUndefOrEqual(BitI, j))
4200 if (!isUndefOrEqual(BitI1, j))
4207 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4208 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4209 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4210 if (!VT.is512BitVector())
4213 unsigned NumElts = VT.getVectorNumElements();
4214 unsigned HalfSize = NumElts/2;
4215 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4216 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4221 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4222 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4230 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4231 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4232 /// MOVSD, and MOVD, i.e. setting the lowest element.
4233 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4234 if (VT.getVectorElementType().getSizeInBits() < 32)
4236 if (!VT.is128BitVector())
4239 unsigned NumElts = VT.getVectorNumElements();
4241 if (!isUndefOrEqual(Mask[0], NumElts))
4244 for (unsigned i = 1; i != NumElts; ++i)
4245 if (!isUndefOrEqual(Mask[i], i))
4251 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4252 /// as permutations between 128-bit chunks or halves. As an example: this
4254 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4255 /// The first half comes from the second half of V1 and the second half from the
4256 /// the second half of V2.
4257 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4258 if (!HasFp256 || !VT.is256BitVector())
4261 // The shuffle result is divided into half A and half B. In total the two
4262 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4263 // B must come from C, D, E or F.
4264 unsigned HalfSize = VT.getVectorNumElements()/2;
4265 bool MatchA = false, MatchB = false;
4267 // Check if A comes from one of C, D, E, F.
4268 for (unsigned Half = 0; Half != 4; ++Half) {
4269 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4275 // Check if B comes from one of C, D, E, F.
4276 for (unsigned Half = 0; Half != 4; ++Half) {
4277 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4283 return MatchA && MatchB;
4286 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4287 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4288 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4289 MVT VT = SVOp->getSimpleValueType(0);
4291 unsigned HalfSize = VT.getVectorNumElements()/2;
4293 unsigned FstHalf = 0, SndHalf = 0;
4294 for (unsigned i = 0; i < HalfSize; ++i) {
4295 if (SVOp->getMaskElt(i) > 0) {
4296 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4300 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4301 if (SVOp->getMaskElt(i) > 0) {
4302 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4307 return (FstHalf | (SndHalf << 4));
4310 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4311 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4312 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4316 unsigned NumElts = VT.getVectorNumElements();
4318 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4319 for (unsigned i = 0; i != NumElts; ++i) {
4322 Imm8 |= Mask[i] << (i*2);
4327 unsigned LaneSize = 4;
4328 SmallVector<int, 4> MaskVal(LaneSize, -1);
4330 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4331 for (unsigned i = 0; i != LaneSize; ++i) {
4332 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4336 if (MaskVal[i] < 0) {
4337 MaskVal[i] = Mask[i+l] - l;
4338 Imm8 |= MaskVal[i] << (i*2);
4341 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4348 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4349 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4350 /// Note that VPERMIL mask matching is different depending whether theunderlying
4351 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4352 /// to the same elements of the low, but to the higher half of the source.
4353 /// In VPERMILPD the two lanes could be shuffled independently of each other
4354 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4355 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4356 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4357 if (VT.getSizeInBits() < 256 || EltSize < 32)
4359 bool symetricMaskRequired = (EltSize == 32);
4360 unsigned NumElts = VT.getVectorNumElements();
4362 unsigned NumLanes = VT.getSizeInBits()/128;
4363 unsigned LaneSize = NumElts/NumLanes;
4364 // 2 or 4 elements in one lane
4366 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4367 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4368 for (unsigned i = 0; i != LaneSize; ++i) {
4369 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4371 if (symetricMaskRequired) {
4372 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4373 ExpectedMaskVal[i] = Mask[i+l] - l;
4376 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4384 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4385 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4386 /// element of vector 2 and the other elements to come from vector 1 in order.
4387 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4388 bool V2IsSplat = false, bool V2IsUndef = false) {
4389 if (!VT.is128BitVector())
4392 unsigned NumOps = VT.getVectorNumElements();
4393 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4396 if (!isUndefOrEqual(Mask[0], 0))
4399 for (unsigned i = 1; i != NumOps; ++i)
4400 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4401 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4402 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4408 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4409 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4410 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4411 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4412 const X86Subtarget *Subtarget) {
4413 if (!Subtarget->hasSSE3())
4416 unsigned NumElems = VT.getVectorNumElements();
4418 if ((VT.is128BitVector() && NumElems != 4) ||
4419 (VT.is256BitVector() && NumElems != 8) ||
4420 (VT.is512BitVector() && NumElems != 16))
4423 // "i+1" is the value the indexed mask element must have
4424 for (unsigned i = 0; i != NumElems; i += 2)
4425 if (!isUndefOrEqual(Mask[i], i+1) ||
4426 !isUndefOrEqual(Mask[i+1], i+1))
4432 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4433 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4434 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4435 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4436 const X86Subtarget *Subtarget) {
4437 if (!Subtarget->hasSSE3())
4440 unsigned NumElems = VT.getVectorNumElements();
4442 if ((VT.is128BitVector() && NumElems != 4) ||
4443 (VT.is256BitVector() && NumElems != 8) ||
4444 (VT.is512BitVector() && NumElems != 16))
4447 // "i" is the value the indexed mask element must have
4448 for (unsigned i = 0; i != NumElems; i += 2)
4449 if (!isUndefOrEqual(Mask[i], i) ||
4450 !isUndefOrEqual(Mask[i+1], i))
4456 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4457 /// specifies a shuffle of elements that is suitable for input to 256-bit
4458 /// version of MOVDDUP.
4459 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4460 if (!HasFp256 || !VT.is256BitVector())
4463 unsigned NumElts = VT.getVectorNumElements();
4467 for (unsigned i = 0; i != NumElts/2; ++i)
4468 if (!isUndefOrEqual(Mask[i], 0))
4470 for (unsigned i = NumElts/2; i != NumElts; ++i)
4471 if (!isUndefOrEqual(Mask[i], NumElts/2))
4476 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4477 /// specifies a shuffle of elements that is suitable for input to 128-bit
4478 /// version of MOVDDUP.
4479 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4480 if (!VT.is128BitVector())
4483 unsigned e = VT.getVectorNumElements() / 2;
4484 for (unsigned i = 0; i != e; ++i)
4485 if (!isUndefOrEqual(Mask[i], i))
4487 for (unsigned i = 0; i != e; ++i)
4488 if (!isUndefOrEqual(Mask[e+i], i))
4493 /// isVEXTRACTIndex - Return true if the specified
4494 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4495 /// suitable for instruction that extract 128 or 256 bit vectors
4496 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4497 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4498 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4501 // The index should be aligned on a vecWidth-bit boundary.
4503 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4505 MVT VT = N->getSimpleValueType(0);
4506 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4507 bool Result = (Index * ElSize) % vecWidth == 0;
4512 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4513 /// operand specifies a subvector insert that is suitable for input to
4514 /// insertion of 128 or 256-bit subvectors
4515 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4516 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4517 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4519 // The index should be aligned on a vecWidth-bit boundary.
4521 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4523 MVT VT = N->getSimpleValueType(0);
4524 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4525 bool Result = (Index * ElSize) % vecWidth == 0;
4530 bool X86::isVINSERT128Index(SDNode *N) {
4531 return isVINSERTIndex(N, 128);
4534 bool X86::isVINSERT256Index(SDNode *N) {
4535 return isVINSERTIndex(N, 256);
4538 bool X86::isVEXTRACT128Index(SDNode *N) {
4539 return isVEXTRACTIndex(N, 128);
4542 bool X86::isVEXTRACT256Index(SDNode *N) {
4543 return isVEXTRACTIndex(N, 256);
4546 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4547 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4548 /// Handles 128-bit and 256-bit.
4549 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4550 MVT VT = N->getSimpleValueType(0);
4552 assert((VT.getSizeInBits() >= 128) &&
4553 "Unsupported vector type for PSHUF/SHUFP");
4555 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4556 // independently on 128-bit lanes.
4557 unsigned NumElts = VT.getVectorNumElements();
4558 unsigned NumLanes = VT.getSizeInBits()/128;
4559 unsigned NumLaneElts = NumElts/NumLanes;
4561 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4562 "Only supports 2, 4 or 8 elements per lane");
4564 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4566 for (unsigned i = 0; i != NumElts; ++i) {
4567 int Elt = N->getMaskElt(i);
4568 if (Elt < 0) continue;
4569 Elt &= NumLaneElts - 1;
4570 unsigned ShAmt = (i << Shift) % 8;
4571 Mask |= Elt << ShAmt;
4577 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4578 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4579 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4580 MVT VT = N->getSimpleValueType(0);
4582 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4583 "Unsupported vector type for PSHUFHW");
4585 unsigned NumElts = VT.getVectorNumElements();
4588 for (unsigned l = 0; l != NumElts; l += 8) {
4589 // 8 nodes per lane, but we only care about the last 4.
4590 for (unsigned i = 0; i < 4; ++i) {
4591 int Elt = N->getMaskElt(l+i+4);
4592 if (Elt < 0) continue;
4593 Elt &= 0x3; // only 2-bits.
4594 Mask |= Elt << (i * 2);
4601 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4602 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4603 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4604 MVT VT = N->getSimpleValueType(0);
4606 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4607 "Unsupported vector type for PSHUFHW");
4609 unsigned NumElts = VT.getVectorNumElements();
4612 for (unsigned l = 0; l != NumElts; l += 8) {
4613 // 8 nodes per lane, but we only care about the first 4.
4614 for (unsigned i = 0; i < 4; ++i) {
4615 int Elt = N->getMaskElt(l+i);
4616 if (Elt < 0) continue;
4617 Elt &= 0x3; // only 2-bits
4618 Mask |= Elt << (i * 2);
4625 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4626 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4627 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4628 MVT VT = SVOp->getSimpleValueType(0);
4629 unsigned EltSize = VT.is512BitVector() ? 1 :
4630 VT.getVectorElementType().getSizeInBits() >> 3;
4632 unsigned NumElts = VT.getVectorNumElements();
4633 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4634 unsigned NumLaneElts = NumElts/NumLanes;
4638 for (i = 0; i != NumElts; ++i) {
4639 Val = SVOp->getMaskElt(i);
4643 if (Val >= (int)NumElts)
4644 Val -= NumElts - NumLaneElts;
4646 assert(Val - i > 0 && "PALIGNR imm should be positive");
4647 return (Val - i) * EltSize;
4650 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4651 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4652 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4653 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4656 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4658 MVT VecVT = N->getOperand(0).getSimpleValueType();
4659 MVT ElVT = VecVT.getVectorElementType();
4661 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4662 return Index / NumElemsPerChunk;
4665 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4666 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4667 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4668 llvm_unreachable("Illegal insert subvector for VINSERT");
4671 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4673 MVT VecVT = N->getSimpleValueType(0);
4674 MVT ElVT = VecVT.getVectorElementType();
4676 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4677 return Index / NumElemsPerChunk;
4680 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4681 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4682 /// and VINSERTI128 instructions.
4683 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4684 return getExtractVEXTRACTImmediate(N, 128);
4687 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4688 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4689 /// and VINSERTI64x4 instructions.
4690 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4691 return getExtractVEXTRACTImmediate(N, 256);
4694 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4695 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4696 /// and VINSERTI128 instructions.
4697 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4698 return getInsertVINSERTImmediate(N, 128);
4701 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4702 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4703 /// and VINSERTI64x4 instructions.
4704 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4705 return getInsertVINSERTImmediate(N, 256);
4708 /// isZero - Returns true if Elt is a constant integer zero
4709 static bool isZero(SDValue V) {
4710 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4711 return C && C->isNullValue();
4714 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4716 bool X86::isZeroNode(SDValue Elt) {
4719 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4720 return CFP->getValueAPF().isPosZero();
4724 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4725 /// their permute mask.
4726 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4727 SelectionDAG &DAG) {
4728 MVT VT = SVOp->getSimpleValueType(0);
4729 unsigned NumElems = VT.getVectorNumElements();
4730 SmallVector<int, 8> MaskVec;
4732 for (unsigned i = 0; i != NumElems; ++i) {
4733 int Idx = SVOp->getMaskElt(i);
4735 if (Idx < (int)NumElems)
4740 MaskVec.push_back(Idx);
4742 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4743 SVOp->getOperand(0), &MaskVec[0]);
4746 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4747 /// match movhlps. The lower half elements should come from upper half of
4748 /// V1 (and in order), and the upper half elements should come from the upper
4749 /// half of V2 (and in order).
4750 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4751 if (!VT.is128BitVector())
4753 if (VT.getVectorNumElements() != 4)
4755 for (unsigned i = 0, e = 2; i != e; ++i)
4756 if (!isUndefOrEqual(Mask[i], i+2))
4758 for (unsigned i = 2; i != 4; ++i)
4759 if (!isUndefOrEqual(Mask[i], i+4))
4764 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4765 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4767 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4768 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4770 N = N->getOperand(0).getNode();
4771 if (!ISD::isNON_EXTLoad(N))
4774 *LD = cast<LoadSDNode>(N);
4778 // Test whether the given value is a vector value which will be legalized
4780 static bool WillBeConstantPoolLoad(SDNode *N) {
4781 if (N->getOpcode() != ISD::BUILD_VECTOR)
4784 // Check for any non-constant elements.
4785 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4786 switch (N->getOperand(i).getNode()->getOpcode()) {
4788 case ISD::ConstantFP:
4795 // Vectors of all-zeros and all-ones are materialized with special
4796 // instructions rather than being loaded.
4797 return !ISD::isBuildVectorAllZeros(N) &&
4798 !ISD::isBuildVectorAllOnes(N);
4801 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4802 /// match movlp{s|d}. The lower half elements should come from lower half of
4803 /// V1 (and in order), and the upper half elements should come from the upper
4804 /// half of V2 (and in order). And since V1 will become the source of the
4805 /// MOVLP, it must be either a vector load or a scalar load to vector.
4806 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4807 ArrayRef<int> Mask, MVT VT) {
4808 if (!VT.is128BitVector())
4811 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4813 // Is V2 is a vector load, don't do this transformation. We will try to use
4814 // load folding shufps op.
4815 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4818 unsigned NumElems = VT.getVectorNumElements();
4820 if (NumElems != 2 && NumElems != 4)
4822 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4823 if (!isUndefOrEqual(Mask[i], i))
4825 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4826 if (!isUndefOrEqual(Mask[i], i+NumElems))
4831 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4833 static bool isSplatVector(SDNode *N) {
4834 if (N->getOpcode() != ISD::BUILD_VECTOR)
4837 SDValue SplatValue = N->getOperand(0);
4838 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4839 if (N->getOperand(i) != SplatValue)
4844 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4845 /// to an zero vector.
4846 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4847 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4848 SDValue V1 = N->getOperand(0);
4849 SDValue V2 = N->getOperand(1);
4850 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4851 for (unsigned i = 0; i != NumElems; ++i) {
4852 int Idx = N->getMaskElt(i);
4853 if (Idx >= (int)NumElems) {
4854 unsigned Opc = V2.getOpcode();
4855 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4857 if (Opc != ISD::BUILD_VECTOR ||
4858 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4860 } else if (Idx >= 0) {
4861 unsigned Opc = V1.getOpcode();
4862 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4864 if (Opc != ISD::BUILD_VECTOR ||
4865 !X86::isZeroNode(V1.getOperand(Idx)))
4872 /// getZeroVector - Returns a vector of specified type with all zero elements.
4874 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4875 SelectionDAG &DAG, SDLoc dl) {
4876 assert(VT.isVector() && "Expected a vector type");
4878 // Always build SSE zero vectors as <4 x i32> bitcasted
4879 // to their dest type. This ensures they get CSE'd.
4881 if (VT.is128BitVector()) { // SSE
4882 if (Subtarget->hasSSE2()) { // SSE2
4883 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4884 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4886 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4887 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4889 } else if (VT.is256BitVector()) { // AVX
4890 if (Subtarget->hasInt256()) { // AVX2
4891 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4892 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4893 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4895 // 256-bit logic and arithmetic instructions in AVX are all
4896 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4897 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4898 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4899 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4901 } else if (VT.is512BitVector()) { // AVX-512
4902 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4903 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4904 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4905 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4906 } else if (VT.getScalarType() == MVT::i1) {
4907 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4908 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4909 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4910 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4912 llvm_unreachable("Unexpected vector type");
4914 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4917 /// getOnesVector - Returns a vector of specified type with all bits set.
4918 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4919 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4920 /// Then bitcast to their original type, ensuring they get CSE'd.
4921 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4923 assert(VT.isVector() && "Expected a vector type");
4925 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4927 if (VT.is256BitVector()) {
4928 if (HasInt256) { // AVX2
4929 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4930 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4932 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4933 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4935 } else if (VT.is128BitVector()) {
4936 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4938 llvm_unreachable("Unexpected vector type");
4940 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4943 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4944 /// that point to V2 points to its first element.
4945 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4946 for (unsigned i = 0; i != NumElems; ++i) {
4947 if (Mask[i] > (int)NumElems) {
4953 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4954 /// operation of specified width.
4955 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4957 unsigned NumElems = VT.getVectorNumElements();
4958 SmallVector<int, 8> Mask;
4959 Mask.push_back(NumElems);
4960 for (unsigned i = 1; i != NumElems; ++i)
4962 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4965 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4966 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4968 unsigned NumElems = VT.getVectorNumElements();
4969 SmallVector<int, 8> Mask;
4970 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4972 Mask.push_back(i + NumElems);
4974 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4977 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4978 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4980 unsigned NumElems = VT.getVectorNumElements();
4981 SmallVector<int, 8> Mask;
4982 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4983 Mask.push_back(i + Half);
4984 Mask.push_back(i + NumElems + Half);
4986 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4989 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4990 // a generic shuffle instruction because the target has no such instructions.
4991 // Generate shuffles which repeat i16 and i8 several times until they can be
4992 // represented by v4f32 and then be manipulated by target suported shuffles.
4993 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4994 MVT VT = V.getSimpleValueType();
4995 int NumElems = VT.getVectorNumElements();
4998 while (NumElems > 4) {
4999 if (EltNo < NumElems/2) {
5000 V = getUnpackl(DAG, dl, VT, V, V);
5002 V = getUnpackh(DAG, dl, VT, V, V);
5003 EltNo -= NumElems/2;
5010 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5011 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5012 MVT VT = V.getSimpleValueType();
5015 if (VT.is128BitVector()) {
5016 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5017 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5018 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5020 } else if (VT.is256BitVector()) {
5021 // To use VPERMILPS to splat scalars, the second half of indicies must
5022 // refer to the higher part, which is a duplication of the lower one,
5023 // because VPERMILPS can only handle in-lane permutations.
5024 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5025 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5027 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5028 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5031 llvm_unreachable("Vector size not supported");
5033 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5036 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5037 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5038 MVT SrcVT = SV->getSimpleValueType(0);
5039 SDValue V1 = SV->getOperand(0);
5042 int EltNo = SV->getSplatIndex();
5043 int NumElems = SrcVT.getVectorNumElements();
5044 bool Is256BitVec = SrcVT.is256BitVector();
5046 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5047 "Unknown how to promote splat for type");
5049 // Extract the 128-bit part containing the splat element and update
5050 // the splat element index when it refers to the higher register.
5052 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5053 if (EltNo >= NumElems/2)
5054 EltNo -= NumElems/2;
5057 // All i16 and i8 vector types can't be used directly by a generic shuffle
5058 // instruction because the target has no such instruction. Generate shuffles
5059 // which repeat i16 and i8 several times until they fit in i32, and then can
5060 // be manipulated by target suported shuffles.
5061 MVT EltVT = SrcVT.getVectorElementType();
5062 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5063 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5065 // Recreate the 256-bit vector and place the same 128-bit vector
5066 // into the low and high part. This is necessary because we want
5067 // to use VPERM* to shuffle the vectors
5069 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5072 return getLegalSplat(DAG, V1, EltNo);
5075 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5076 /// vector of zero or undef vector. This produces a shuffle where the low
5077 /// element of V2 is swizzled into the zero/undef vector, landing at element
5078 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5079 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5081 const X86Subtarget *Subtarget,
5082 SelectionDAG &DAG) {
5083 MVT VT = V2.getSimpleValueType();
5085 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5086 unsigned NumElems = VT.getVectorNumElements();
5087 SmallVector<int, 16> MaskVec;
5088 for (unsigned i = 0; i != NumElems; ++i)
5089 // If this is the insertion idx, put the low elt of V2 here.
5090 MaskVec.push_back(i == Idx ? NumElems : i);
5091 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5094 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5095 /// target specific opcode. Returns true if the Mask could be calculated.
5096 /// Sets IsUnary to true if only uses one source.
5097 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5098 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5099 unsigned NumElems = VT.getVectorNumElements();
5103 switch(N->getOpcode()) {
5105 ImmN = N->getOperand(N->getNumOperands()-1);
5106 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5108 case X86ISD::UNPCKH:
5109 DecodeUNPCKHMask(VT, Mask);
5111 case X86ISD::UNPCKL:
5112 DecodeUNPCKLMask(VT, Mask);
5114 case X86ISD::MOVHLPS:
5115 DecodeMOVHLPSMask(NumElems, Mask);
5117 case X86ISD::MOVLHPS:
5118 DecodeMOVLHPSMask(NumElems, Mask);
5120 case X86ISD::PALIGNR:
5121 ImmN = N->getOperand(N->getNumOperands()-1);
5122 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5124 case X86ISD::PSHUFD:
5125 case X86ISD::VPERMILP:
5126 ImmN = N->getOperand(N->getNumOperands()-1);
5127 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5130 case X86ISD::PSHUFHW:
5131 ImmN = N->getOperand(N->getNumOperands()-1);
5132 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5135 case X86ISD::PSHUFLW:
5136 ImmN = N->getOperand(N->getNumOperands()-1);
5137 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5140 case X86ISD::VPERMI:
5141 ImmN = N->getOperand(N->getNumOperands()-1);
5142 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5146 case X86ISD::MOVSD: {
5147 // The index 0 always comes from the first element of the second source,
5148 // this is why MOVSS and MOVSD are used in the first place. The other
5149 // elements come from the other positions of the first source vector
5150 Mask.push_back(NumElems);
5151 for (unsigned i = 1; i != NumElems; ++i) {
5156 case X86ISD::VPERM2X128:
5157 ImmN = N->getOperand(N->getNumOperands()-1);
5158 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5159 if (Mask.empty()) return false;
5161 case X86ISD::MOVDDUP:
5162 case X86ISD::MOVLHPD:
5163 case X86ISD::MOVLPD:
5164 case X86ISD::MOVLPS:
5165 case X86ISD::MOVSHDUP:
5166 case X86ISD::MOVSLDUP:
5167 // Not yet implemented
5169 default: llvm_unreachable("unknown target shuffle node");
5175 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5176 /// element of the result of the vector shuffle.
5177 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5180 return SDValue(); // Limit search depth.
5182 SDValue V = SDValue(N, 0);
5183 EVT VT = V.getValueType();
5184 unsigned Opcode = V.getOpcode();
5186 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5187 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5188 int Elt = SV->getMaskElt(Index);
5191 return DAG.getUNDEF(VT.getVectorElementType());
5193 unsigned NumElems = VT.getVectorNumElements();
5194 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5195 : SV->getOperand(1);
5196 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5199 // Recurse into target specific vector shuffles to find scalars.
5200 if (isTargetShuffle(Opcode)) {
5201 MVT ShufVT = V.getSimpleValueType();
5202 unsigned NumElems = ShufVT.getVectorNumElements();
5203 SmallVector<int, 16> ShuffleMask;
5206 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5209 int Elt = ShuffleMask[Index];
5211 return DAG.getUNDEF(ShufVT.getVectorElementType());
5213 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5215 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5219 // Actual nodes that may contain scalar elements
5220 if (Opcode == ISD::BITCAST) {
5221 V = V.getOperand(0);
5222 EVT SrcVT = V.getValueType();
5223 unsigned NumElems = VT.getVectorNumElements();
5225 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5229 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5230 return (Index == 0) ? V.getOperand(0)
5231 : DAG.getUNDEF(VT.getVectorElementType());
5233 if (V.getOpcode() == ISD::BUILD_VECTOR)
5234 return V.getOperand(Index);
5239 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5240 /// shuffle operation which come from a consecutively from a zero. The
5241 /// search can start in two different directions, from left or right.
5242 /// We count undefs as zeros until PreferredNum is reached.
5243 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5244 unsigned NumElems, bool ZerosFromLeft,
5246 unsigned PreferredNum = -1U) {
5247 unsigned NumZeros = 0;
5248 for (unsigned i = 0; i != NumElems; ++i) {
5249 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5250 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5254 if (X86::isZeroNode(Elt))
5256 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5257 NumZeros = std::min(NumZeros + 1, PreferredNum);
5265 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5266 /// correspond consecutively to elements from one of the vector operands,
5267 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5269 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5270 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5271 unsigned NumElems, unsigned &OpNum) {
5272 bool SeenV1 = false;
5273 bool SeenV2 = false;
5275 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5276 int Idx = SVOp->getMaskElt(i);
5277 // Ignore undef indicies
5281 if (Idx < (int)NumElems)
5286 // Only accept consecutive elements from the same vector
5287 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5291 OpNum = SeenV1 ? 0 : 1;
5295 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5296 /// logical left shift of a vector.
5297 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5298 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5300 SVOp->getSimpleValueType(0).getVectorNumElements();
5301 unsigned NumZeros = getNumOfConsecutiveZeros(
5302 SVOp, NumElems, false /* check zeros from right */, DAG,
5303 SVOp->getMaskElt(0));
5309 // Considering the elements in the mask that are not consecutive zeros,
5310 // check if they consecutively come from only one of the source vectors.
5312 // V1 = {X, A, B, C} 0
5314 // vector_shuffle V1, V2 <1, 2, 3, X>
5316 if (!isShuffleMaskConsecutive(SVOp,
5317 0, // Mask Start Index
5318 NumElems-NumZeros, // Mask End Index(exclusive)
5319 NumZeros, // Where to start looking in the src vector
5320 NumElems, // Number of elements in vector
5321 OpSrc)) // Which source operand ?
5326 ShVal = SVOp->getOperand(OpSrc);
5330 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5331 /// logical left shift of a vector.
5332 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5333 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5335 SVOp->getSimpleValueType(0).getVectorNumElements();
5336 unsigned NumZeros = getNumOfConsecutiveZeros(
5337 SVOp, NumElems, true /* check zeros from left */, DAG,
5338 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5344 // Considering the elements in the mask that are not consecutive zeros,
5345 // check if they consecutively come from only one of the source vectors.
5347 // 0 { A, B, X, X } = V2
5349 // vector_shuffle V1, V2 <X, X, 4, 5>
5351 if (!isShuffleMaskConsecutive(SVOp,
5352 NumZeros, // Mask Start Index
5353 NumElems, // Mask End Index(exclusive)
5354 0, // Where to start looking in the src vector
5355 NumElems, // Number of elements in vector
5356 OpSrc)) // Which source operand ?
5361 ShVal = SVOp->getOperand(OpSrc);
5365 /// isVectorShift - Returns true if the shuffle can be implemented as a
5366 /// logical left or right shift of a vector.
5367 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5368 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5369 // Although the logic below support any bitwidth size, there are no
5370 // shift instructions which handle more than 128-bit vectors.
5371 if (!SVOp->getSimpleValueType(0).is128BitVector())
5374 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5375 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5381 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5383 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5384 unsigned NumNonZero, unsigned NumZero,
5386 const X86Subtarget* Subtarget,
5387 const TargetLowering &TLI) {
5394 for (unsigned i = 0; i < 16; ++i) {
5395 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5396 if (ThisIsNonZero && First) {
5398 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5400 V = DAG.getUNDEF(MVT::v8i16);
5405 SDValue ThisElt, LastElt;
5406 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5407 if (LastIsNonZero) {
5408 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5409 MVT::i16, Op.getOperand(i-1));
5411 if (ThisIsNonZero) {
5412 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5413 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5414 ThisElt, DAG.getConstant(8, MVT::i8));
5416 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5420 if (ThisElt.getNode())
5421 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5422 DAG.getIntPtrConstant(i/2));
5426 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5429 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5431 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5432 unsigned NumNonZero, unsigned NumZero,
5434 const X86Subtarget* Subtarget,
5435 const TargetLowering &TLI) {
5442 for (unsigned i = 0; i < 8; ++i) {
5443 bool isNonZero = (NonZeros & (1 << i)) != 0;
5447 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5449 V = DAG.getUNDEF(MVT::v8i16);
5452 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5453 MVT::v8i16, V, Op.getOperand(i),
5454 DAG.getIntPtrConstant(i));
5461 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5462 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5463 unsigned NonZeros, unsigned NumNonZero,
5464 unsigned NumZero, SelectionDAG &DAG,
5465 const X86Subtarget *Subtarget,
5466 const TargetLowering &TLI) {
5467 // We know there's at least one non-zero element
5468 unsigned FirstNonZeroIdx = 0;
5469 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5470 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5471 X86::isZeroNode(FirstNonZero)) {
5473 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5476 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5477 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5480 SDValue V = FirstNonZero.getOperand(0);
5481 MVT VVT = V.getSimpleValueType();
5482 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5485 unsigned FirstNonZeroDst =
5486 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5487 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5488 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5489 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5491 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5492 SDValue Elem = Op.getOperand(Idx);
5493 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5496 // TODO: What else can be here? Deal with it.
5497 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5500 // TODO: Some optimizations are still possible here
5501 // ex: Getting one element from a vector, and the rest from another.
5502 if (Elem.getOperand(0) != V)
5505 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5508 else if (IncorrectIdx == -1U) {
5512 // There was already one element with an incorrect index.
5513 // We can't optimize this case to an insertps.
5517 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5519 EVT VT = Op.getSimpleValueType();
5520 unsigned ElementMoveMask = 0;
5521 if (IncorrectIdx == -1U)
5522 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5524 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5526 SDValue InsertpsMask =
5527 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5528 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5534 /// getVShift - Return a vector logical shift node.
5536 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5537 unsigned NumBits, SelectionDAG &DAG,
5538 const TargetLowering &TLI, SDLoc dl) {
5539 assert(VT.is128BitVector() && "Unknown type for VShift");
5540 EVT ShVT = MVT::v2i64;
5541 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5542 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5543 return DAG.getNode(ISD::BITCAST, dl, VT,
5544 DAG.getNode(Opc, dl, ShVT, SrcOp,
5545 DAG.getConstant(NumBits,
5546 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5550 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5552 // Check if the scalar load can be widened into a vector load. And if
5553 // the address is "base + cst" see if the cst can be "absorbed" into
5554 // the shuffle mask.
5555 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5556 SDValue Ptr = LD->getBasePtr();
5557 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5559 EVT PVT = LD->getValueType(0);
5560 if (PVT != MVT::i32 && PVT != MVT::f32)
5565 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5566 FI = FINode->getIndex();
5568 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5569 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5570 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5571 Offset = Ptr.getConstantOperandVal(1);
5572 Ptr = Ptr.getOperand(0);
5577 // FIXME: 256-bit vector instructions don't require a strict alignment,
5578 // improve this code to support it better.
5579 unsigned RequiredAlign = VT.getSizeInBits()/8;
5580 SDValue Chain = LD->getChain();
5581 // Make sure the stack object alignment is at least 16 or 32.
5582 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5583 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5584 if (MFI->isFixedObjectIndex(FI)) {
5585 // Can't change the alignment. FIXME: It's possible to compute
5586 // the exact stack offset and reference FI + adjust offset instead.
5587 // If someone *really* cares about this. That's the way to implement it.
5590 MFI->setObjectAlignment(FI, RequiredAlign);
5594 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5595 // Ptr + (Offset & ~15).
5598 if ((Offset % RequiredAlign) & 3)
5600 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5602 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5603 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5605 int EltNo = (Offset - StartOffset) >> 2;
5606 unsigned NumElems = VT.getVectorNumElements();
5608 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5609 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5610 LD->getPointerInfo().getWithOffset(StartOffset),
5611 false, false, false, 0);
5613 SmallVector<int, 8> Mask;
5614 for (unsigned i = 0; i != NumElems; ++i)
5615 Mask.push_back(EltNo);
5617 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5623 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5624 /// vector of type 'VT', see if the elements can be replaced by a single large
5625 /// load which has the same value as a build_vector whose operands are 'elts'.
5627 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5629 /// FIXME: we'd also like to handle the case where the last elements are zero
5630 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5631 /// There's even a handy isZeroNode for that purpose.
5632 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5633 SDLoc &DL, SelectionDAG &DAG,
5634 bool isAfterLegalize) {
5635 EVT EltVT = VT.getVectorElementType();
5636 unsigned NumElems = Elts.size();
5638 LoadSDNode *LDBase = nullptr;
5639 unsigned LastLoadedElt = -1U;
5641 // For each element in the initializer, see if we've found a load or an undef.
5642 // If we don't find an initial load element, or later load elements are
5643 // non-consecutive, bail out.
5644 for (unsigned i = 0; i < NumElems; ++i) {
5645 SDValue Elt = Elts[i];
5647 if (!Elt.getNode() ||
5648 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5651 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5653 LDBase = cast<LoadSDNode>(Elt.getNode());
5657 if (Elt.getOpcode() == ISD::UNDEF)
5660 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5661 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5666 // If we have found an entire vector of loads and undefs, then return a large
5667 // load of the entire vector width starting at the base pointer. If we found
5668 // consecutive loads for the low half, generate a vzext_load node.
5669 if (LastLoadedElt == NumElems - 1) {
5671 if (isAfterLegalize &&
5672 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5675 SDValue NewLd = SDValue();
5677 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5678 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5679 LDBase->getPointerInfo(),
5680 LDBase->isVolatile(), LDBase->isNonTemporal(),
5681 LDBase->isInvariant(), 0);
5682 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5683 LDBase->getPointerInfo(),
5684 LDBase->isVolatile(), LDBase->isNonTemporal(),
5685 LDBase->isInvariant(), LDBase->getAlignment());
5687 if (LDBase->hasAnyUseOfValue(1)) {
5688 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5690 SDValue(NewLd.getNode(), 1));
5691 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5692 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5693 SDValue(NewLd.getNode(), 1));
5698 if (NumElems == 4 && LastLoadedElt == 1 &&
5699 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5700 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5701 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5703 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5704 LDBase->getPointerInfo(),
5705 LDBase->getAlignment(),
5706 false/*isVolatile*/, true/*ReadMem*/,
5709 // Make sure the newly-created LOAD is in the same position as LDBase in
5710 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5711 // update uses of LDBase's output chain to use the TokenFactor.
5712 if (LDBase->hasAnyUseOfValue(1)) {
5713 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5714 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5715 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5716 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5717 SDValue(ResNode.getNode(), 1));
5720 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5725 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5726 /// to generate a splat value for the following cases:
5727 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5728 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5729 /// a scalar load, or a constant.
5730 /// The VBROADCAST node is returned when a pattern is found,
5731 /// or SDValue() otherwise.
5732 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5733 SelectionDAG &DAG) {
5734 if (!Subtarget->hasFp256())
5737 MVT VT = Op.getSimpleValueType();
5740 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5741 "Unsupported vector type for broadcast.");
5746 switch (Op.getOpcode()) {
5748 // Unknown pattern found.
5751 case ISD::BUILD_VECTOR: {
5752 // The BUILD_VECTOR node must be a splat.
5753 if (!isSplatVector(Op.getNode()))
5756 Ld = Op.getOperand(0);
5757 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5758 Ld.getOpcode() == ISD::ConstantFP);
5760 // The suspected load node has several users. Make sure that all
5761 // of its users are from the BUILD_VECTOR node.
5762 // Constants may have multiple users.
5763 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5768 case ISD::VECTOR_SHUFFLE: {
5769 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5771 // Shuffles must have a splat mask where the first element is
5773 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5776 SDValue Sc = Op.getOperand(0);
5777 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5778 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5780 if (!Subtarget->hasInt256())
5783 // Use the register form of the broadcast instruction available on AVX2.
5784 if (VT.getSizeInBits() >= 256)
5785 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5786 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5789 Ld = Sc.getOperand(0);
5790 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5791 Ld.getOpcode() == ISD::ConstantFP);
5793 // The scalar_to_vector node and the suspected
5794 // load node must have exactly one user.
5795 // Constants may have multiple users.
5797 // AVX-512 has register version of the broadcast
5798 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5799 Ld.getValueType().getSizeInBits() >= 32;
5800 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5807 bool IsGE256 = (VT.getSizeInBits() >= 256);
5809 // Handle the broadcasting a single constant scalar from the constant pool
5810 // into a vector. On Sandybridge it is still better to load a constant vector
5811 // from the constant pool and not to broadcast it from a scalar.
5812 if (ConstSplatVal && Subtarget->hasInt256()) {
5813 EVT CVT = Ld.getValueType();
5814 assert(!CVT.isVector() && "Must not broadcast a vector type");
5815 unsigned ScalarSize = CVT.getSizeInBits();
5817 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5818 const Constant *C = nullptr;
5819 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5820 C = CI->getConstantIntValue();
5821 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5822 C = CF->getConstantFPValue();
5824 assert(C && "Invalid constant type");
5826 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5827 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5828 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5829 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5830 MachinePointerInfo::getConstantPool(),
5831 false, false, false, Alignment);
5833 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5837 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5838 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5840 // Handle AVX2 in-register broadcasts.
5841 if (!IsLoad && Subtarget->hasInt256() &&
5842 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5843 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5845 // The scalar source must be a normal load.
5849 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5850 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5852 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5853 // double since there is no vbroadcastsd xmm
5854 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5855 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5856 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5859 // Unsupported broadcast.
5863 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5864 /// underlying vector and index.
5866 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5868 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5870 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5871 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5874 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5876 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5878 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5879 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5882 // In this case the vector is the extract_subvector expression and the index
5883 // is 2, as specified by the shuffle.
5884 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5885 SDValue ShuffleVec = SVOp->getOperand(0);
5886 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5887 assert(ShuffleVecVT.getVectorElementType() ==
5888 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5890 int ShuffleIdx = SVOp->getMaskElt(Idx);
5891 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5892 ExtractedFromVec = ShuffleVec;
5898 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5899 MVT VT = Op.getSimpleValueType();
5901 // Skip if insert_vec_elt is not supported.
5902 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5903 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5907 unsigned NumElems = Op.getNumOperands();
5911 SmallVector<unsigned, 4> InsertIndices;
5912 SmallVector<int, 8> Mask(NumElems, -1);
5914 for (unsigned i = 0; i != NumElems; ++i) {
5915 unsigned Opc = Op.getOperand(i).getOpcode();
5917 if (Opc == ISD::UNDEF)
5920 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5921 // Quit if more than 1 elements need inserting.
5922 if (InsertIndices.size() > 1)
5925 InsertIndices.push_back(i);
5929 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5930 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5931 // Quit if non-constant index.
5932 if (!isa<ConstantSDNode>(ExtIdx))
5934 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5936 // Quit if extracted from vector of different type.
5937 if (ExtractedFromVec.getValueType() != VT)
5940 if (!VecIn1.getNode())
5941 VecIn1 = ExtractedFromVec;
5942 else if (VecIn1 != ExtractedFromVec) {
5943 if (!VecIn2.getNode())
5944 VecIn2 = ExtractedFromVec;
5945 else if (VecIn2 != ExtractedFromVec)
5946 // Quit if more than 2 vectors to shuffle
5950 if (ExtractedFromVec == VecIn1)
5952 else if (ExtractedFromVec == VecIn2)
5953 Mask[i] = Idx + NumElems;
5956 if (!VecIn1.getNode())
5959 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5960 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5961 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5962 unsigned Idx = InsertIndices[i];
5963 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5964 DAG.getIntPtrConstant(Idx));
5970 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5972 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5974 MVT VT = Op.getSimpleValueType();
5975 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5976 "Unexpected type in LowerBUILD_VECTORvXi1!");
5979 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5980 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5981 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5982 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5985 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5986 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5987 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5988 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5991 bool AllContants = true;
5992 uint64_t Immediate = 0;
5993 int NonConstIdx = -1;
5994 bool IsSplat = true;
5995 unsigned NumNonConsts = 0;
5996 unsigned NumConsts = 0;
5997 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5998 SDValue In = Op.getOperand(idx);
5999 if (In.getOpcode() == ISD::UNDEF)
6001 if (!isa<ConstantSDNode>(In)) {
6002 AllContants = false;
6008 if (cast<ConstantSDNode>(In)->getZExtValue())
6009 Immediate |= (1ULL << idx);
6011 if (In != Op.getOperand(0))
6016 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6017 DAG.getConstant(Immediate, MVT::i16));
6018 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6019 DAG.getIntPtrConstant(0));
6022 if (NumNonConsts == 1 && NonConstIdx != 0) {
6025 SDValue VecAsImm = DAG.getConstant(Immediate,
6026 MVT::getIntegerVT(VT.getSizeInBits()));
6027 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6030 DstVec = DAG.getUNDEF(VT);
6031 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6032 Op.getOperand(NonConstIdx),
6033 DAG.getIntPtrConstant(NonConstIdx));
6035 if (!IsSplat && (NonConstIdx != 0))
6036 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6037 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6040 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6041 DAG.getConstant(-1, SelectVT),
6042 DAG.getConstant(0, SelectVT));
6044 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6045 DAG.getConstant((Immediate | 1), SelectVT),
6046 DAG.getConstant(Immediate, SelectVT));
6047 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6051 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6054 MVT VT = Op.getSimpleValueType();
6055 MVT ExtVT = VT.getVectorElementType();
6056 unsigned NumElems = Op.getNumOperands();
6058 // Generate vectors for predicate vectors.
6059 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6060 return LowerBUILD_VECTORvXi1(Op, DAG);
6062 // Vectors containing all zeros can be matched by pxor and xorps later
6063 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6064 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6065 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6066 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6069 return getZeroVector(VT, Subtarget, DAG, dl);
6072 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6073 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6074 // vpcmpeqd on 256-bit vectors.
6075 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6076 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6079 if (!VT.is512BitVector())
6080 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6083 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6084 if (Broadcast.getNode())
6087 unsigned EVTBits = ExtVT.getSizeInBits();
6089 unsigned NumZero = 0;
6090 unsigned NumNonZero = 0;
6091 unsigned NonZeros = 0;
6092 bool IsAllConstants = true;
6093 SmallSet<SDValue, 8> Values;
6094 for (unsigned i = 0; i < NumElems; ++i) {
6095 SDValue Elt = Op.getOperand(i);
6096 if (Elt.getOpcode() == ISD::UNDEF)
6099 if (Elt.getOpcode() != ISD::Constant &&
6100 Elt.getOpcode() != ISD::ConstantFP)
6101 IsAllConstants = false;
6102 if (X86::isZeroNode(Elt))
6105 NonZeros |= (1 << i);
6110 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6111 if (NumNonZero == 0)
6112 return DAG.getUNDEF(VT);
6114 // Special case for single non-zero, non-undef, element.
6115 if (NumNonZero == 1) {
6116 unsigned Idx = countTrailingZeros(NonZeros);
6117 SDValue Item = Op.getOperand(Idx);
6119 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6120 // the value are obviously zero, truncate the value to i32 and do the
6121 // insertion that way. Only do this if the value is non-constant or if the
6122 // value is a constant being inserted into element 0. It is cheaper to do
6123 // a constant pool load than it is to do a movd + shuffle.
6124 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6125 (!IsAllConstants || Idx == 0)) {
6126 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6128 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6129 EVT VecVT = MVT::v4i32;
6130 unsigned VecElts = 4;
6132 // Truncate the value (which may itself be a constant) to i32, and
6133 // convert it to a vector with movd (S2V+shuffle to zero extend).
6134 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6135 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6136 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6138 // Now we have our 32-bit value zero extended in the low element of
6139 // a vector. If Idx != 0, swizzle it into place.
6141 SmallVector<int, 4> Mask;
6142 Mask.push_back(Idx);
6143 for (unsigned i = 1; i != VecElts; ++i)
6145 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6148 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6152 // If we have a constant or non-constant insertion into the low element of
6153 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6154 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6155 // depending on what the source datatype is.
6158 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6160 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6161 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6162 if (VT.is256BitVector() || VT.is512BitVector()) {
6163 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6164 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6165 Item, DAG.getIntPtrConstant(0));
6167 assert(VT.is128BitVector() && "Expected an SSE value type!");
6168 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6169 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6170 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6173 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6174 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6175 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6176 if (VT.is256BitVector()) {
6177 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6178 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6180 assert(VT.is128BitVector() && "Expected an SSE value type!");
6181 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6183 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6187 // Is it a vector logical left shift?
6188 if (NumElems == 2 && Idx == 1 &&
6189 X86::isZeroNode(Op.getOperand(0)) &&
6190 !X86::isZeroNode(Op.getOperand(1))) {
6191 unsigned NumBits = VT.getSizeInBits();
6192 return getVShift(true, VT,
6193 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6194 VT, Op.getOperand(1)),
6195 NumBits/2, DAG, *this, dl);
6198 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6201 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6202 // is a non-constant being inserted into an element other than the low one,
6203 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6204 // movd/movss) to move this into the low element, then shuffle it into
6206 if (EVTBits == 32) {
6207 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6209 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6210 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6211 SmallVector<int, 8> MaskVec;
6212 for (unsigned i = 0; i != NumElems; ++i)
6213 MaskVec.push_back(i == Idx ? 0 : 1);
6214 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6218 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6219 if (Values.size() == 1) {
6220 if (EVTBits == 32) {
6221 // Instead of a shuffle like this:
6222 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6223 // Check if it's possible to issue this instead.
6224 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6225 unsigned Idx = countTrailingZeros(NonZeros);
6226 SDValue Item = Op.getOperand(Idx);
6227 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6228 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6233 // A vector full of immediates; various special cases are already
6234 // handled, so this is best done with a single constant-pool load.
6238 // For AVX-length vectors, build the individual 128-bit pieces and use
6239 // shuffles to put them in place.
6240 if (VT.is256BitVector() || VT.is512BitVector()) {
6241 SmallVector<SDValue, 64> V;
6242 for (unsigned i = 0; i != NumElems; ++i)
6243 V.push_back(Op.getOperand(i));
6245 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6247 // Build both the lower and upper subvector.
6248 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6249 makeArrayRef(&V[0], NumElems/2));
6250 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6251 makeArrayRef(&V[NumElems / 2], NumElems/2));
6253 // Recreate the wider vector with the lower and upper part.
6254 if (VT.is256BitVector())
6255 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6256 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6259 // Let legalizer expand 2-wide build_vectors.
6260 if (EVTBits == 64) {
6261 if (NumNonZero == 1) {
6262 // One half is zero or undef.
6263 unsigned Idx = countTrailingZeros(NonZeros);
6264 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6265 Op.getOperand(Idx));
6266 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6271 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6272 if (EVTBits == 8 && NumElems == 16) {
6273 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6275 if (V.getNode()) return V;
6278 if (EVTBits == 16 && NumElems == 8) {
6279 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6281 if (V.getNode()) return V;
6284 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6285 if (EVTBits == 32 && NumElems == 4) {
6286 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6287 NumZero, DAG, Subtarget, *this);
6292 // If element VT is == 32 bits, turn it into a number of shuffles.
6293 SmallVector<SDValue, 8> V(NumElems);
6294 if (NumElems == 4 && NumZero > 0) {
6295 for (unsigned i = 0; i < 4; ++i) {
6296 bool isZero = !(NonZeros & (1 << i));
6298 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6300 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6303 for (unsigned i = 0; i < 2; ++i) {
6304 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6307 V[i] = V[i*2]; // Must be a zero vector.
6310 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6313 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6316 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6321 bool Reverse1 = (NonZeros & 0x3) == 2;
6322 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6326 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6327 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6329 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6332 if (Values.size() > 1 && VT.is128BitVector()) {
6333 // Check for a build vector of consecutive loads.
6334 for (unsigned i = 0; i < NumElems; ++i)
6335 V[i] = Op.getOperand(i);
6337 // Check for elements which are consecutive loads.
6338 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6342 // Check for a build vector from mostly shuffle plus few inserting.
6343 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6347 // For SSE 4.1, use insertps to put the high elements into the low element.
6348 if (getSubtarget()->hasSSE41()) {
6350 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6351 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6353 Result = DAG.getUNDEF(VT);
6355 for (unsigned i = 1; i < NumElems; ++i) {
6356 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6357 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6358 Op.getOperand(i), DAG.getIntPtrConstant(i));
6363 // Otherwise, expand into a number of unpckl*, start by extending each of
6364 // our (non-undef) elements to the full vector width with the element in the
6365 // bottom slot of the vector (which generates no code for SSE).
6366 for (unsigned i = 0; i < NumElems; ++i) {
6367 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6368 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6370 V[i] = DAG.getUNDEF(VT);
6373 // Next, we iteratively mix elements, e.g. for v4f32:
6374 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6375 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6376 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6377 unsigned EltStride = NumElems >> 1;
6378 while (EltStride != 0) {
6379 for (unsigned i = 0; i < EltStride; ++i) {
6380 // If V[i+EltStride] is undef and this is the first round of mixing,
6381 // then it is safe to just drop this shuffle: V[i] is already in the
6382 // right place, the one element (since it's the first round) being
6383 // inserted as undef can be dropped. This isn't safe for successive
6384 // rounds because they will permute elements within both vectors.
6385 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6386 EltStride == NumElems/2)
6389 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6398 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6399 // to create 256-bit vectors from two other 128-bit ones.
6400 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6402 MVT ResVT = Op.getSimpleValueType();
6404 assert((ResVT.is256BitVector() ||
6405 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6407 SDValue V1 = Op.getOperand(0);
6408 SDValue V2 = Op.getOperand(1);
6409 unsigned NumElems = ResVT.getVectorNumElements();
6410 if(ResVT.is256BitVector())
6411 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6413 if (Op.getNumOperands() == 4) {
6414 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6415 ResVT.getVectorNumElements()/2);
6416 SDValue V3 = Op.getOperand(2);
6417 SDValue V4 = Op.getOperand(3);
6418 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6419 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6421 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6424 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6425 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6426 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6427 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6428 Op.getNumOperands() == 4)));
6430 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6431 // from two other 128-bit ones.
6433 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6434 return LowerAVXCONCAT_VECTORS(Op, DAG);
6437 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6438 bool hasInt256, unsigned *MaskOut = nullptr) {
6439 MVT EltVT = VT.getVectorElementType();
6441 // There is no blend with immediate in AVX-512.
6442 if (VT.is512BitVector())
6445 if (!hasSSE41 || EltVT == MVT::i8)
6447 if (!hasInt256 && VT == MVT::v16i16)
6450 unsigned MaskValue = 0;
6451 unsigned NumElems = VT.getVectorNumElements();
6452 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6453 unsigned NumLanes = (NumElems - 1) / 8 + 1;
6454 unsigned NumElemsInLane = NumElems / NumLanes;
6456 // Blend for v16i16 should be symetric for the both lanes.
6457 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6459 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6460 int EltIdx = MaskVals[i];
6462 if ((EltIdx < 0 || EltIdx == (int)i) &&
6463 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6466 if (((unsigned)EltIdx == (i + NumElems)) &&
6467 (SndLaneEltIdx < 0 ||
6468 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6469 MaskValue |= (1 << i);
6475 *MaskOut = MaskValue;
6479 // Try to lower a shuffle node into a simple blend instruction.
6480 // This function assumes isBlendMask returns true for this
6481 // SuffleVectorSDNode
6482 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6484 const X86Subtarget *Subtarget,
6485 SelectionDAG &DAG) {
6486 MVT VT = SVOp->getSimpleValueType(0);
6487 MVT EltVT = VT.getVectorElementType();
6488 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6489 Subtarget->hasInt256() && "Trying to lower a "
6490 "VECTOR_SHUFFLE to a Blend but "
6491 "with the wrong mask"));
6492 SDValue V1 = SVOp->getOperand(0);
6493 SDValue V2 = SVOp->getOperand(1);
6495 unsigned NumElems = VT.getVectorNumElements();
6497 // Convert i32 vectors to floating point if it is not AVX2.
6498 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6500 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6501 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6503 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6504 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6507 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6508 DAG.getConstant(MaskValue, MVT::i32));
6509 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6512 /// In vector type \p VT, return true if the element at index \p InputIdx
6513 /// falls on a different 128-bit lane than \p OutputIdx.
6514 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6515 unsigned OutputIdx) {
6516 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6517 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6520 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6521 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6522 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6523 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6525 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6526 SelectionDAG &DAG) {
6527 MVT VT = V1.getSimpleValueType();
6528 assert(VT.is128BitVector() || VT.is256BitVector());
6530 MVT EltVT = VT.getVectorElementType();
6531 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6532 unsigned NumElts = VT.getVectorNumElements();
6534 SmallVector<SDValue, 32> PshufbMask;
6535 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6536 int InputIdx = MaskVals[OutputIdx];
6537 unsigned InputByteIdx;
6539 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6540 InputByteIdx = 0x80;
6542 // Cross lane is not allowed.
6543 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6545 InputByteIdx = InputIdx * EltSizeInBytes;
6546 // Index is an byte offset within the 128-bit lane.
6547 InputByteIdx &= 0xf;
6550 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6551 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6552 if (InputByteIdx != 0x80)
6557 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6559 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6560 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6561 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6564 // v8i16 shuffles - Prefer shuffles in the following order:
6565 // 1. [all] pshuflw, pshufhw, optional move
6566 // 2. [ssse3] 1 x pshufb
6567 // 3. [ssse3] 2 x pshufb + 1 x por
6568 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6570 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6571 SelectionDAG &DAG) {
6572 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6573 SDValue V1 = SVOp->getOperand(0);
6574 SDValue V2 = SVOp->getOperand(1);
6576 SmallVector<int, 8> MaskVals;
6578 // Determine if more than 1 of the words in each of the low and high quadwords
6579 // of the result come from the same quadword of one of the two inputs. Undef
6580 // mask values count as coming from any quadword, for better codegen.
6582 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6583 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6584 unsigned LoQuad[] = { 0, 0, 0, 0 };
6585 unsigned HiQuad[] = { 0, 0, 0, 0 };
6586 // Indices of quads used.
6587 std::bitset<4> InputQuads;
6588 for (unsigned i = 0; i < 8; ++i) {
6589 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6590 int EltIdx = SVOp->getMaskElt(i);
6591 MaskVals.push_back(EltIdx);
6600 InputQuads.set(EltIdx / 4);
6603 int BestLoQuad = -1;
6604 unsigned MaxQuad = 1;
6605 for (unsigned i = 0; i < 4; ++i) {
6606 if (LoQuad[i] > MaxQuad) {
6608 MaxQuad = LoQuad[i];
6612 int BestHiQuad = -1;
6614 for (unsigned i = 0; i < 4; ++i) {
6615 if (HiQuad[i] > MaxQuad) {
6617 MaxQuad = HiQuad[i];
6621 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6622 // of the two input vectors, shuffle them into one input vector so only a
6623 // single pshufb instruction is necessary. If there are more than 2 input
6624 // quads, disable the next transformation since it does not help SSSE3.
6625 bool V1Used = InputQuads[0] || InputQuads[1];
6626 bool V2Used = InputQuads[2] || InputQuads[3];
6627 if (Subtarget->hasSSSE3()) {
6628 if (InputQuads.count() == 2 && V1Used && V2Used) {
6629 BestLoQuad = InputQuads[0] ? 0 : 1;
6630 BestHiQuad = InputQuads[2] ? 2 : 3;
6632 if (InputQuads.count() > 2) {
6638 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6639 // the shuffle mask. If a quad is scored as -1, that means that it contains
6640 // words from all 4 input quadwords.
6642 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6644 BestLoQuad < 0 ? 0 : BestLoQuad,
6645 BestHiQuad < 0 ? 1 : BestHiQuad
6647 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6648 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6649 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6650 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6652 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6653 // source words for the shuffle, to aid later transformations.
6654 bool AllWordsInNewV = true;
6655 bool InOrder[2] = { true, true };
6656 for (unsigned i = 0; i != 8; ++i) {
6657 int idx = MaskVals[i];
6659 InOrder[i/4] = false;
6660 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6662 AllWordsInNewV = false;
6666 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6667 if (AllWordsInNewV) {
6668 for (int i = 0; i != 8; ++i) {
6669 int idx = MaskVals[i];
6672 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6673 if ((idx != i) && idx < 4)
6675 if ((idx != i) && idx > 3)
6684 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6685 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6686 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6687 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6688 unsigned TargetMask = 0;
6689 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6690 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6691 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6692 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6693 getShufflePSHUFLWImmediate(SVOp);
6694 V1 = NewV.getOperand(0);
6695 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6699 // Promote splats to a larger type which usually leads to more efficient code.
6700 // FIXME: Is this true if pshufb is available?
6701 if (SVOp->isSplat())
6702 return PromoteSplat(SVOp, DAG);
6704 // If we have SSSE3, and all words of the result are from 1 input vector,
6705 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6706 // is present, fall back to case 4.
6707 if (Subtarget->hasSSSE3()) {
6708 SmallVector<SDValue,16> pshufbMask;
6710 // If we have elements from both input vectors, set the high bit of the
6711 // shuffle mask element to zero out elements that come from V2 in the V1
6712 // mask, and elements that come from V1 in the V2 mask, so that the two
6713 // results can be OR'd together.
6714 bool TwoInputs = V1Used && V2Used;
6715 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6717 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6719 // Calculate the shuffle mask for the second input, shuffle it, and
6720 // OR it with the first shuffled input.
6721 CommuteVectorShuffleMask(MaskVals, 8);
6722 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6723 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6724 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6727 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6728 // and update MaskVals with new element order.
6729 std::bitset<8> InOrder;
6730 if (BestLoQuad >= 0) {
6731 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6732 for (int i = 0; i != 4; ++i) {
6733 int idx = MaskVals[i];
6736 } else if ((idx / 4) == BestLoQuad) {
6741 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6744 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6745 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6746 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6748 getShufflePSHUFLWImmediate(SVOp), DAG);
6752 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6753 // and update MaskVals with the new element order.
6754 if (BestHiQuad >= 0) {
6755 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6756 for (unsigned i = 4; i != 8; ++i) {
6757 int idx = MaskVals[i];
6760 } else if ((idx / 4) == BestHiQuad) {
6761 MaskV[i] = (idx & 3) + 4;
6765 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6768 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6769 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6770 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6772 getShufflePSHUFHWImmediate(SVOp), DAG);
6776 // In case BestHi & BestLo were both -1, which means each quadword has a word
6777 // from each of the four input quadwords, calculate the InOrder bitvector now
6778 // before falling through to the insert/extract cleanup.
6779 if (BestLoQuad == -1 && BestHiQuad == -1) {
6781 for (int i = 0; i != 8; ++i)
6782 if (MaskVals[i] < 0 || MaskVals[i] == i)
6786 // The other elements are put in the right place using pextrw and pinsrw.
6787 for (unsigned i = 0; i != 8; ++i) {
6790 int EltIdx = MaskVals[i];
6793 SDValue ExtOp = (EltIdx < 8) ?
6794 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6795 DAG.getIntPtrConstant(EltIdx)) :
6796 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6797 DAG.getIntPtrConstant(EltIdx - 8));
6798 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6799 DAG.getIntPtrConstant(i));
6804 /// \brief v16i16 shuffles
6806 /// FIXME: We only support generation of a single pshufb currently. We can
6807 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6808 /// well (e.g 2 x pshufb + 1 x por).
6810 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6811 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6812 SDValue V1 = SVOp->getOperand(0);
6813 SDValue V2 = SVOp->getOperand(1);
6816 if (V2.getOpcode() != ISD::UNDEF)
6819 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6820 return getPSHUFB(MaskVals, V1, dl, DAG);
6823 // v16i8 shuffles - Prefer shuffles in the following order:
6824 // 1. [ssse3] 1 x pshufb
6825 // 2. [ssse3] 2 x pshufb + 1 x por
6826 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6827 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6828 const X86Subtarget* Subtarget,
6829 SelectionDAG &DAG) {
6830 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6831 SDValue V1 = SVOp->getOperand(0);
6832 SDValue V2 = SVOp->getOperand(1);
6834 ArrayRef<int> MaskVals = SVOp->getMask();
6836 // Promote splats to a larger type which usually leads to more efficient code.
6837 // FIXME: Is this true if pshufb is available?
6838 if (SVOp->isSplat())
6839 return PromoteSplat(SVOp, DAG);
6841 // If we have SSSE3, case 1 is generated when all result bytes come from
6842 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6843 // present, fall back to case 3.
6845 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6846 if (Subtarget->hasSSSE3()) {
6847 SmallVector<SDValue,16> pshufbMask;
6849 // If all result elements are from one input vector, then only translate
6850 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6852 // Otherwise, we have elements from both input vectors, and must zero out
6853 // elements that come from V2 in the first mask, and V1 in the second mask
6854 // so that we can OR them together.
6855 for (unsigned i = 0; i != 16; ++i) {
6856 int EltIdx = MaskVals[i];
6857 if (EltIdx < 0 || EltIdx >= 16)
6859 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6861 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6862 DAG.getNode(ISD::BUILD_VECTOR, dl,
6863 MVT::v16i8, pshufbMask));
6865 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6866 // the 2nd operand if it's undefined or zero.
6867 if (V2.getOpcode() == ISD::UNDEF ||
6868 ISD::isBuildVectorAllZeros(V2.getNode()))
6871 // Calculate the shuffle mask for the second input, shuffle it, and
6872 // OR it with the first shuffled input.
6874 for (unsigned i = 0; i != 16; ++i) {
6875 int EltIdx = MaskVals[i];
6876 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6877 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6879 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6880 DAG.getNode(ISD::BUILD_VECTOR, dl,
6881 MVT::v16i8, pshufbMask));
6882 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6885 // No SSSE3 - Calculate in place words and then fix all out of place words
6886 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6887 // the 16 different words that comprise the two doublequadword input vectors.
6888 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6889 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6891 for (int i = 0; i != 8; ++i) {
6892 int Elt0 = MaskVals[i*2];
6893 int Elt1 = MaskVals[i*2+1];
6895 // This word of the result is all undef, skip it.
6896 if (Elt0 < 0 && Elt1 < 0)
6899 // This word of the result is already in the correct place, skip it.
6900 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6903 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6904 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6907 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6908 // using a single extract together, load it and store it.
6909 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6910 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6911 DAG.getIntPtrConstant(Elt1 / 2));
6912 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6913 DAG.getIntPtrConstant(i));
6917 // If Elt1 is defined, extract it from the appropriate source. If the
6918 // source byte is not also odd, shift the extracted word left 8 bits
6919 // otherwise clear the bottom 8 bits if we need to do an or.
6921 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6922 DAG.getIntPtrConstant(Elt1 / 2));
6923 if ((Elt1 & 1) == 0)
6924 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6926 TLI.getShiftAmountTy(InsElt.getValueType())));
6928 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6929 DAG.getConstant(0xFF00, MVT::i16));
6931 // If Elt0 is defined, extract it from the appropriate source. If the
6932 // source byte is not also even, shift the extracted word right 8 bits. If
6933 // Elt1 was also defined, OR the extracted values together before
6934 // inserting them in the result.
6936 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6937 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6938 if ((Elt0 & 1) != 0)
6939 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6941 TLI.getShiftAmountTy(InsElt0.getValueType())));
6943 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6944 DAG.getConstant(0x00FF, MVT::i16));
6945 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6948 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6949 DAG.getIntPtrConstant(i));
6951 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6954 // v32i8 shuffles - Translate to VPSHUFB if possible.
6956 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6957 const X86Subtarget *Subtarget,
6958 SelectionDAG &DAG) {
6959 MVT VT = SVOp->getSimpleValueType(0);
6960 SDValue V1 = SVOp->getOperand(0);
6961 SDValue V2 = SVOp->getOperand(1);
6963 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6965 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6966 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6967 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6969 // VPSHUFB may be generated if
6970 // (1) one of input vector is undefined or zeroinitializer.
6971 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6972 // And (2) the mask indexes don't cross the 128-bit lane.
6973 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6974 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6977 if (V1IsAllZero && !V2IsAllZero) {
6978 CommuteVectorShuffleMask(MaskVals, 32);
6981 return getPSHUFB(MaskVals, V1, dl, DAG);
6984 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6985 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6986 /// done when every pair / quad of shuffle mask elements point to elements in
6987 /// the right sequence. e.g.
6988 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6990 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6991 SelectionDAG &DAG) {
6992 MVT VT = SVOp->getSimpleValueType(0);
6994 unsigned NumElems = VT.getVectorNumElements();
6997 switch (VT.SimpleTy) {
6998 default: llvm_unreachable("Unexpected!");
7001 return SDValue(SVOp, 0);
7002 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
7003 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
7004 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
7005 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
7006 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7007 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
7010 SmallVector<int, 8> MaskVec;
7011 for (unsigned i = 0; i != NumElems; i += Scale) {
7013 for (unsigned j = 0; j != Scale; ++j) {
7014 int EltIdx = SVOp->getMaskElt(i+j);
7018 StartIdx = (EltIdx / Scale);
7019 if (EltIdx != (int)(StartIdx*Scale + j))
7022 MaskVec.push_back(StartIdx);
7025 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7026 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7027 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7030 /// getVZextMovL - Return a zero-extending vector move low node.
7032 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7033 SDValue SrcOp, SelectionDAG &DAG,
7034 const X86Subtarget *Subtarget, SDLoc dl) {
7035 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7036 LoadSDNode *LD = nullptr;
7037 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7038 LD = dyn_cast<LoadSDNode>(SrcOp);
7040 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7042 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7043 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7044 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7045 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7046 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7048 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7049 return DAG.getNode(ISD::BITCAST, dl, VT,
7050 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7051 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7059 return DAG.getNode(ISD::BITCAST, dl, VT,
7060 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7061 DAG.getNode(ISD::BITCAST, dl,
7065 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7066 /// which could not be matched by any known target speficic shuffle
7068 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7070 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7071 if (NewOp.getNode())
7074 MVT VT = SVOp->getSimpleValueType(0);
7076 unsigned NumElems = VT.getVectorNumElements();
7077 unsigned NumLaneElems = NumElems / 2;
7080 MVT EltVT = VT.getVectorElementType();
7081 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7084 SmallVector<int, 16> Mask;
7085 for (unsigned l = 0; l < 2; ++l) {
7086 // Build a shuffle mask for the output, discovering on the fly which
7087 // input vectors to use as shuffle operands (recorded in InputUsed).
7088 // If building a suitable shuffle vector proves too hard, then bail
7089 // out with UseBuildVector set.
7090 bool UseBuildVector = false;
7091 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7092 unsigned LaneStart = l * NumLaneElems;
7093 for (unsigned i = 0; i != NumLaneElems; ++i) {
7094 // The mask element. This indexes into the input.
7095 int Idx = SVOp->getMaskElt(i+LaneStart);
7097 // the mask element does not index into any input vector.
7102 // The input vector this mask element indexes into.
7103 int Input = Idx / NumLaneElems;
7105 // Turn the index into an offset from the start of the input vector.
7106 Idx -= Input * NumLaneElems;
7108 // Find or create a shuffle vector operand to hold this input.
7110 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7111 if (InputUsed[OpNo] == Input)
7112 // This input vector is already an operand.
7114 if (InputUsed[OpNo] < 0) {
7115 // Create a new operand for this input vector.
7116 InputUsed[OpNo] = Input;
7121 if (OpNo >= array_lengthof(InputUsed)) {
7122 // More than two input vectors used! Give up on trying to create a
7123 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7124 UseBuildVector = true;
7128 // Add the mask index for the new shuffle vector.
7129 Mask.push_back(Idx + OpNo * NumLaneElems);
7132 if (UseBuildVector) {
7133 SmallVector<SDValue, 16> SVOps;
7134 for (unsigned i = 0; i != NumLaneElems; ++i) {
7135 // The mask element. This indexes into the input.
7136 int Idx = SVOp->getMaskElt(i+LaneStart);
7138 SVOps.push_back(DAG.getUNDEF(EltVT));
7142 // The input vector this mask element indexes into.
7143 int Input = Idx / NumElems;
7145 // Turn the index into an offset from the start of the input vector.
7146 Idx -= Input * NumElems;
7148 // Extract the vector element by hand.
7149 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7150 SVOp->getOperand(Input),
7151 DAG.getIntPtrConstant(Idx)));
7154 // Construct the output using a BUILD_VECTOR.
7155 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7156 } else if (InputUsed[0] < 0) {
7157 // No input vectors were used! The result is undefined.
7158 Output[l] = DAG.getUNDEF(NVT);
7160 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7161 (InputUsed[0] % 2) * NumLaneElems,
7163 // If only one input was used, use an undefined vector for the other.
7164 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7165 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7166 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7167 // At least one input vector was used. Create a new shuffle vector.
7168 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7174 // Concatenate the result back
7175 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7178 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7179 /// 4 elements, and match them with several different shuffle types.
7181 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7182 SDValue V1 = SVOp->getOperand(0);
7183 SDValue V2 = SVOp->getOperand(1);
7185 MVT VT = SVOp->getSimpleValueType(0);
7187 assert(VT.is128BitVector() && "Unsupported vector size");
7189 std::pair<int, int> Locs[4];
7190 int Mask1[] = { -1, -1, -1, -1 };
7191 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7195 for (unsigned i = 0; i != 4; ++i) {
7196 int Idx = PermMask[i];
7198 Locs[i] = std::make_pair(-1, -1);
7200 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7202 Locs[i] = std::make_pair(0, NumLo);
7206 Locs[i] = std::make_pair(1, NumHi);
7208 Mask1[2+NumHi] = Idx;
7214 if (NumLo <= 2 && NumHi <= 2) {
7215 // If no more than two elements come from either vector. This can be
7216 // implemented with two shuffles. First shuffle gather the elements.
7217 // The second shuffle, which takes the first shuffle as both of its
7218 // vector operands, put the elements into the right order.
7219 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7221 int Mask2[] = { -1, -1, -1, -1 };
7223 for (unsigned i = 0; i != 4; ++i)
7224 if (Locs[i].first != -1) {
7225 unsigned Idx = (i < 2) ? 0 : 4;
7226 Idx += Locs[i].first * 2 + Locs[i].second;
7230 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7233 if (NumLo == 3 || NumHi == 3) {
7234 // Otherwise, we must have three elements from one vector, call it X, and
7235 // one element from the other, call it Y. First, use a shufps to build an
7236 // intermediate vector with the one element from Y and the element from X
7237 // that will be in the same half in the final destination (the indexes don't
7238 // matter). Then, use a shufps to build the final vector, taking the half
7239 // containing the element from Y from the intermediate, and the other half
7242 // Normalize it so the 3 elements come from V1.
7243 CommuteVectorShuffleMask(PermMask, 4);
7247 // Find the element from V2.
7249 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7250 int Val = PermMask[HiIndex];
7257 Mask1[0] = PermMask[HiIndex];
7259 Mask1[2] = PermMask[HiIndex^1];
7261 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7264 Mask1[0] = PermMask[0];
7265 Mask1[1] = PermMask[1];
7266 Mask1[2] = HiIndex & 1 ? 6 : 4;
7267 Mask1[3] = HiIndex & 1 ? 4 : 6;
7268 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7271 Mask1[0] = HiIndex & 1 ? 2 : 0;
7272 Mask1[1] = HiIndex & 1 ? 0 : 2;
7273 Mask1[2] = PermMask[2];
7274 Mask1[3] = PermMask[3];
7279 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7282 // Break it into (shuffle shuffle_hi, shuffle_lo).
7283 int LoMask[] = { -1, -1, -1, -1 };
7284 int HiMask[] = { -1, -1, -1, -1 };
7286 int *MaskPtr = LoMask;
7287 unsigned MaskIdx = 0;
7290 for (unsigned i = 0; i != 4; ++i) {
7297 int Idx = PermMask[i];
7299 Locs[i] = std::make_pair(-1, -1);
7300 } else if (Idx < 4) {
7301 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7302 MaskPtr[LoIdx] = Idx;
7305 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7306 MaskPtr[HiIdx] = Idx;
7311 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7312 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7313 int MaskOps[] = { -1, -1, -1, -1 };
7314 for (unsigned i = 0; i != 4; ++i)
7315 if (Locs[i].first != -1)
7316 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7317 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7320 static bool MayFoldVectorLoad(SDValue V) {
7321 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7322 V = V.getOperand(0);
7324 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7325 V = V.getOperand(0);
7326 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7327 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7328 // BUILD_VECTOR (load), undef
7329 V = V.getOperand(0);
7331 return MayFoldLoad(V);
7335 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7336 MVT VT = Op.getSimpleValueType();
7338 // Canonizalize to v2f64.
7339 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7340 return DAG.getNode(ISD::BITCAST, dl, VT,
7341 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7346 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7348 SDValue V1 = Op.getOperand(0);
7349 SDValue V2 = Op.getOperand(1);
7350 MVT VT = Op.getSimpleValueType();
7352 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7354 if (HasSSE2 && VT == MVT::v2f64)
7355 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7357 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7358 return DAG.getNode(ISD::BITCAST, dl, VT,
7359 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7360 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7361 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7365 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7366 SDValue V1 = Op.getOperand(0);
7367 SDValue V2 = Op.getOperand(1);
7368 MVT VT = Op.getSimpleValueType();
7370 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7371 "unsupported shuffle type");
7373 if (V2.getOpcode() == ISD::UNDEF)
7377 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7381 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7382 SDValue V1 = Op.getOperand(0);
7383 SDValue V2 = Op.getOperand(1);
7384 MVT VT = Op.getSimpleValueType();
7385 unsigned NumElems = VT.getVectorNumElements();
7387 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7388 // operand of these instructions is only memory, so check if there's a
7389 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7391 bool CanFoldLoad = false;
7393 // Trivial case, when V2 comes from a load.
7394 if (MayFoldVectorLoad(V2))
7397 // When V1 is a load, it can be folded later into a store in isel, example:
7398 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7400 // (MOVLPSmr addr:$src1, VR128:$src2)
7401 // So, recognize this potential and also use MOVLPS or MOVLPD
7402 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7405 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7407 if (HasSSE2 && NumElems == 2)
7408 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7411 // If we don't care about the second element, proceed to use movss.
7412 if (SVOp->getMaskElt(1) != -1)
7413 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7416 // movl and movlp will both match v2i64, but v2i64 is never matched by
7417 // movl earlier because we make it strict to avoid messing with the movlp load
7418 // folding logic (see the code above getMOVLP call). Match it here then,
7419 // this is horrible, but will stay like this until we move all shuffle
7420 // matching to x86 specific nodes. Note that for the 1st condition all
7421 // types are matched with movsd.
7423 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7424 // as to remove this logic from here, as much as possible
7425 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7426 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7427 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7430 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7432 // Invert the operand order and use SHUFPS to match it.
7433 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7434 getShuffleSHUFImmediate(SVOp), DAG);
7437 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7438 SelectionDAG &DAG) {
7440 MVT VT = Load->getSimpleValueType(0);
7441 MVT EVT = VT.getVectorElementType();
7442 SDValue Addr = Load->getOperand(1);
7443 SDValue NewAddr = DAG.getNode(
7444 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7445 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7448 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7449 DAG.getMachineFunction().getMachineMemOperand(
7450 Load->getMemOperand(), 0, EVT.getStoreSize()));
7454 // It is only safe to call this function if isINSERTPSMask is true for
7455 // this shufflevector mask.
7456 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7457 SelectionDAG &DAG) {
7458 // Generate an insertps instruction when inserting an f32 from memory onto a
7459 // v4f32 or when copying a member from one v4f32 to another.
7460 // We also use it for transferring i32 from one register to another,
7461 // since it simply copies the same bits.
7462 // If we're transferring an i32 from memory to a specific element in a
7463 // register, we output a generic DAG that will match the PINSRD
7465 MVT VT = SVOp->getSimpleValueType(0);
7466 MVT EVT = VT.getVectorElementType();
7467 SDValue V1 = SVOp->getOperand(0);
7468 SDValue V2 = SVOp->getOperand(1);
7469 auto Mask = SVOp->getMask();
7470 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7471 "unsupported vector type for insertps/pinsrd");
7473 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7474 auto FromV2Predicate = [](const int &i) { return i >= 4; };
7475 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7483 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7486 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7487 "More than one element from V1 and from V2, or no elements from one "
7488 "of the vectors. This case should not have returned true from "
7493 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7496 if (MayFoldLoad(From)) {
7497 // Trivial case, when From comes from a load and is only used by the
7498 // shuffle. Make it use insertps from the vector that we need from that
7501 NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7502 if (!NewLoad.getNode())
7505 if (EVT == MVT::f32) {
7506 // Create this as a scalar to vector to match the instruction pattern.
7507 SDValue LoadScalarToVector =
7508 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7509 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7510 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7512 } else { // EVT == MVT::i32
7513 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7514 // instruction, to match the PINSRD instruction, which loads an i32 to a
7515 // certain vector element.
7516 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7517 DAG.getConstant(DestIndex, MVT::i32));
7521 // Vector-element-to-vector
7522 unsigned SrcIndex = Mask[DestIndex] % 4;
7523 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7524 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7527 // Reduce a vector shuffle to zext.
7528 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7529 SelectionDAG &DAG) {
7530 // PMOVZX is only available from SSE41.
7531 if (!Subtarget->hasSSE41())
7534 MVT VT = Op.getSimpleValueType();
7536 // Only AVX2 support 256-bit vector integer extending.
7537 if (!Subtarget->hasInt256() && VT.is256BitVector())
7540 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7542 SDValue V1 = Op.getOperand(0);
7543 SDValue V2 = Op.getOperand(1);
7544 unsigned NumElems = VT.getVectorNumElements();
7546 // Extending is an unary operation and the element type of the source vector
7547 // won't be equal to or larger than i64.
7548 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7549 VT.getVectorElementType() == MVT::i64)
7552 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7553 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7554 while ((1U << Shift) < NumElems) {
7555 if (SVOp->getMaskElt(1U << Shift) == 1)
7558 // The maximal ratio is 8, i.e. from i8 to i64.
7563 // Check the shuffle mask.
7564 unsigned Mask = (1U << Shift) - 1;
7565 for (unsigned i = 0; i != NumElems; ++i) {
7566 int EltIdx = SVOp->getMaskElt(i);
7567 if ((i & Mask) != 0 && EltIdx != -1)
7569 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7573 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7574 MVT NeVT = MVT::getIntegerVT(NBits);
7575 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7577 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7580 // Simplify the operand as it's prepared to be fed into shuffle.
7581 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7582 if (V1.getOpcode() == ISD::BITCAST &&
7583 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7584 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7585 V1.getOperand(0).getOperand(0)
7586 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7587 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7588 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7589 ConstantSDNode *CIdx =
7590 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7591 // If it's foldable, i.e. normal load with single use, we will let code
7592 // selection to fold it. Otherwise, we will short the conversion sequence.
7593 if (CIdx && CIdx->getZExtValue() == 0 &&
7594 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7595 MVT FullVT = V.getSimpleValueType();
7596 MVT V1VT = V1.getSimpleValueType();
7597 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7598 // The "ext_vec_elt" node is wider than the result node.
7599 // In this case we should extract subvector from V.
7600 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7601 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7602 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7603 FullVT.getVectorNumElements()/Ratio);
7604 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7605 DAG.getIntPtrConstant(0));
7607 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7611 return DAG.getNode(ISD::BITCAST, DL, VT,
7612 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7615 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7616 SelectionDAG &DAG) {
7617 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7618 MVT VT = Op.getSimpleValueType();
7620 SDValue V1 = Op.getOperand(0);
7621 SDValue V2 = Op.getOperand(1);
7623 if (isZeroShuffle(SVOp))
7624 return getZeroVector(VT, Subtarget, DAG, dl);
7626 // Handle splat operations
7627 if (SVOp->isSplat()) {
7628 // Use vbroadcast whenever the splat comes from a foldable load
7629 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7630 if (Broadcast.getNode())
7634 // Check integer expanding shuffles.
7635 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7636 if (NewOp.getNode())
7639 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7641 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7643 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7644 if (NewOp.getNode())
7645 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7646 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7647 // FIXME: Figure out a cleaner way to do this.
7648 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7649 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7650 if (NewOp.getNode()) {
7651 MVT NewVT = NewOp.getSimpleValueType();
7652 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7653 NewVT, true, false))
7654 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7657 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7658 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7659 if (NewOp.getNode()) {
7660 MVT NewVT = NewOp.getSimpleValueType();
7661 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7662 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7671 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7672 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7673 SDValue V1 = Op.getOperand(0);
7674 SDValue V2 = Op.getOperand(1);
7675 MVT VT = Op.getSimpleValueType();
7677 unsigned NumElems = VT.getVectorNumElements();
7678 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7679 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7680 bool V1IsSplat = false;
7681 bool V2IsSplat = false;
7682 bool HasSSE2 = Subtarget->hasSSE2();
7683 bool HasFp256 = Subtarget->hasFp256();
7684 bool HasInt256 = Subtarget->hasInt256();
7685 MachineFunction &MF = DAG.getMachineFunction();
7686 bool OptForSize = MF.getFunction()->getAttributes().
7687 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7689 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7691 if (V1IsUndef && V2IsUndef)
7692 return DAG.getUNDEF(VT);
7694 // When we create a shuffle node we put the UNDEF node to second operand,
7695 // but in some cases the first operand may be transformed to UNDEF.
7696 // In this case we should just commute the node.
7698 return CommuteVectorShuffle(SVOp, DAG);
7700 // Vector shuffle lowering takes 3 steps:
7702 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7703 // narrowing and commutation of operands should be handled.
7704 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7706 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7707 // so the shuffle can be broken into other shuffles and the legalizer can
7708 // try the lowering again.
7710 // The general idea is that no vector_shuffle operation should be left to
7711 // be matched during isel, all of them must be converted to a target specific
7714 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7715 // narrowing and commutation of operands should be handled. The actual code
7716 // doesn't include all of those, work in progress...
7717 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7718 if (NewOp.getNode())
7721 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7723 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7724 // unpckh_undef). Only use pshufd if speed is more important than size.
7725 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7726 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7727 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7728 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7730 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7731 V2IsUndef && MayFoldVectorLoad(V1))
7732 return getMOVDDup(Op, dl, V1, DAG);
7734 if (isMOVHLPS_v_undef_Mask(M, VT))
7735 return getMOVHighToLow(Op, dl, DAG);
7737 // Use to match splats
7738 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7739 (VT == MVT::v2f64 || VT == MVT::v2i64))
7740 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7742 if (isPSHUFDMask(M, VT)) {
7743 // The actual implementation will match the mask in the if above and then
7744 // during isel it can match several different instructions, not only pshufd
7745 // as its name says, sad but true, emulate the behavior for now...
7746 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7747 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7749 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7751 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7752 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7754 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7755 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7758 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7762 if (isPALIGNRMask(M, VT, Subtarget))
7763 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7764 getShufflePALIGNRImmediate(SVOp),
7767 // Check if this can be converted into a logical shift.
7768 bool isLeft = false;
7771 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7772 if (isShift && ShVal.hasOneUse()) {
7773 // If the shifted value has multiple uses, it may be cheaper to use
7774 // v_set0 + movlhps or movhlps, etc.
7775 MVT EltVT = VT.getVectorElementType();
7776 ShAmt *= EltVT.getSizeInBits();
7777 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7780 if (isMOVLMask(M, VT)) {
7781 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7782 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7783 if (!isMOVLPMask(M, VT)) {
7784 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7785 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7787 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7788 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7792 // FIXME: fold these into legal mask.
7793 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7794 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7796 if (isMOVHLPSMask(M, VT))
7797 return getMOVHighToLow(Op, dl, DAG);
7799 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7800 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7802 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7803 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7805 if (isMOVLPMask(M, VT))
7806 return getMOVLP(Op, dl, DAG, HasSSE2);
7808 if (ShouldXformToMOVHLPS(M, VT) ||
7809 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7810 return CommuteVectorShuffle(SVOp, DAG);
7813 // No better options. Use a vshldq / vsrldq.
7814 MVT EltVT = VT.getVectorElementType();
7815 ShAmt *= EltVT.getSizeInBits();
7816 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7819 bool Commuted = false;
7820 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7821 // 1,1,1,1 -> v8i16 though.
7822 V1IsSplat = isSplatVector(V1.getNode());
7823 V2IsSplat = isSplatVector(V2.getNode());
7825 // Canonicalize the splat or undef, if present, to be on the RHS.
7826 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7827 CommuteVectorShuffleMask(M, NumElems);
7829 std::swap(V1IsSplat, V2IsSplat);
7833 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7834 // Shuffling low element of v1 into undef, just return v1.
7837 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7838 // the instruction selector will not match, so get a canonical MOVL with
7839 // swapped operands to undo the commute.
7840 return getMOVL(DAG, dl, VT, V2, V1);
7843 if (isUNPCKLMask(M, VT, HasInt256))
7844 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7846 if (isUNPCKHMask(M, VT, HasInt256))
7847 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7850 // Normalize mask so all entries that point to V2 points to its first
7851 // element then try to match unpck{h|l} again. If match, return a
7852 // new vector_shuffle with the corrected mask.p
7853 SmallVector<int, 8> NewMask(M.begin(), M.end());
7854 NormalizeMask(NewMask, NumElems);
7855 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7856 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7857 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7858 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7862 // Commute is back and try unpck* again.
7863 // FIXME: this seems wrong.
7864 CommuteVectorShuffleMask(M, NumElems);
7866 std::swap(V1IsSplat, V2IsSplat);
7868 if (isUNPCKLMask(M, VT, HasInt256))
7869 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7871 if (isUNPCKHMask(M, VT, HasInt256))
7872 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7875 // Normalize the node to match x86 shuffle ops if needed
7876 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7877 return CommuteVectorShuffle(SVOp, DAG);
7879 // The checks below are all present in isShuffleMaskLegal, but they are
7880 // inlined here right now to enable us to directly emit target specific
7881 // nodes, and remove one by one until they don't return Op anymore.
7883 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7884 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7885 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7886 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7889 if (isPSHUFHWMask(M, VT, HasInt256))
7890 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7891 getShufflePSHUFHWImmediate(SVOp),
7894 if (isPSHUFLWMask(M, VT, HasInt256))
7895 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7896 getShufflePSHUFLWImmediate(SVOp),
7899 if (isSHUFPMask(M, VT))
7900 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7901 getShuffleSHUFImmediate(SVOp), DAG);
7903 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7904 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7905 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7906 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7908 //===--------------------------------------------------------------------===//
7909 // Generate target specific nodes for 128 or 256-bit shuffles only
7910 // supported in the AVX instruction set.
7913 // Handle VMOVDDUPY permutations
7914 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7915 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7917 // Handle VPERMILPS/D* permutations
7918 if (isVPERMILPMask(M, VT)) {
7919 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7920 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7921 getShuffleSHUFImmediate(SVOp), DAG);
7922 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7923 getShuffleSHUFImmediate(SVOp), DAG);
7927 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7928 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7929 Idx*(NumElems/2), DAG, dl);
7931 // Handle VPERM2F128/VPERM2I128 permutations
7932 if (isVPERM2X128Mask(M, VT, HasFp256))
7933 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7934 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7937 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
7939 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
7941 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7942 return getINSERTPS(SVOp, dl, DAG);
7945 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7946 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7948 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7949 VT.is512BitVector()) {
7950 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7951 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7952 SmallVector<SDValue, 16> permclMask;
7953 for (unsigned i = 0; i != NumElems; ++i) {
7954 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7957 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7959 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7960 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7961 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7962 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7963 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7966 //===--------------------------------------------------------------------===//
7967 // Since no target specific shuffle was selected for this generic one,
7968 // lower it into other known shuffles. FIXME: this isn't true yet, but
7969 // this is the plan.
7972 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7973 if (VT == MVT::v8i16) {
7974 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7975 if (NewOp.getNode())
7979 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7980 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7981 if (NewOp.getNode())
7985 if (VT == MVT::v16i8) {
7986 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7987 if (NewOp.getNode())
7991 if (VT == MVT::v32i8) {
7992 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7993 if (NewOp.getNode())
7997 // Handle all 128-bit wide vectors with 4 elements, and match them with
7998 // several different shuffle types.
7999 if (NumElems == 4 && VT.is128BitVector())
8000 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8002 // Handle general 256-bit shuffles
8003 if (VT.is256BitVector())
8004 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8009 // This function assumes its argument is a BUILD_VECTOR of constants or
8010 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8012 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8013 unsigned &MaskValue) {
8015 unsigned NumElems = BuildVector->getNumOperands();
8016 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8017 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8018 unsigned NumElemsInLane = NumElems / NumLanes;
8020 // Blend for v16i16 should be symetric for the both lanes.
8021 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8022 SDValue EltCond = BuildVector->getOperand(i);
8023 SDValue SndLaneEltCond =
8024 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8026 int Lane1Cond = -1, Lane2Cond = -1;
8027 if (isa<ConstantSDNode>(EltCond))
8028 Lane1Cond = !isZero(EltCond);
8029 if (isa<ConstantSDNode>(SndLaneEltCond))
8030 Lane2Cond = !isZero(SndLaneEltCond);
8032 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8033 // Lane1Cond != 0, means we want the first argument.
8034 // Lane1Cond == 0, means we want the second argument.
8035 // The encoding of this argument is 0 for the first argument, 1
8036 // for the second. Therefore, invert the condition.
8037 MaskValue |= !Lane1Cond << i;
8038 else if (Lane1Cond < 0)
8039 MaskValue |= !Lane2Cond << i;
8046 // Try to lower a vselect node into a simple blend instruction.
8047 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8048 SelectionDAG &DAG) {
8049 SDValue Cond = Op.getOperand(0);
8050 SDValue LHS = Op.getOperand(1);
8051 SDValue RHS = Op.getOperand(2);
8053 MVT VT = Op.getSimpleValueType();
8054 MVT EltVT = VT.getVectorElementType();
8055 unsigned NumElems = VT.getVectorNumElements();
8057 // There is no blend with immediate in AVX-512.
8058 if (VT.is512BitVector())
8061 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8063 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8066 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8069 // Check the mask for BLEND and build the value.
8070 unsigned MaskValue = 0;
8071 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8074 // Convert i32 vectors to floating point if it is not AVX2.
8075 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8077 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8078 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8080 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8081 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8084 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8085 DAG.getConstant(MaskValue, MVT::i32));
8086 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8089 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8090 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8091 if (BlendOp.getNode())
8094 // Some types for vselect were previously set to Expand, not Legal or
8095 // Custom. Return an empty SDValue so we fall-through to Expand, after
8096 // the Custom lowering phase.
8097 MVT VT = Op.getSimpleValueType();
8098 switch (VT.SimpleTy) {
8106 // We couldn't create a "Blend with immediate" node.
8107 // This node should still be legal, but we'll have to emit a blendv*
8112 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8113 MVT VT = Op.getSimpleValueType();
8116 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8119 if (VT.getSizeInBits() == 8) {
8120 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8121 Op.getOperand(0), Op.getOperand(1));
8122 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8123 DAG.getValueType(VT));
8124 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8127 if (VT.getSizeInBits() == 16) {
8128 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8129 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8131 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8132 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8133 DAG.getNode(ISD::BITCAST, dl,
8137 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8138 Op.getOperand(0), Op.getOperand(1));
8139 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8140 DAG.getValueType(VT));
8141 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8144 if (VT == MVT::f32) {
8145 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8146 // the result back to FR32 register. It's only worth matching if the
8147 // result has a single use which is a store or a bitcast to i32. And in
8148 // the case of a store, it's not worth it if the index is a constant 0,
8149 // because a MOVSSmr can be used instead, which is smaller and faster.
8150 if (!Op.hasOneUse())
8152 SDNode *User = *Op.getNode()->use_begin();
8153 if ((User->getOpcode() != ISD::STORE ||
8154 (isa<ConstantSDNode>(Op.getOperand(1)) &&
8155 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8156 (User->getOpcode() != ISD::BITCAST ||
8157 User->getValueType(0) != MVT::i32))
8159 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8160 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8163 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8166 if (VT == MVT::i32 || VT == MVT::i64) {
8167 // ExtractPS/pextrq works with constant index.
8168 if (isa<ConstantSDNode>(Op.getOperand(1)))
8174 /// Extract one bit from mask vector, like v16i1 or v8i1.
8175 /// AVX-512 feature.
8177 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8178 SDValue Vec = Op.getOperand(0);
8180 MVT VecVT = Vec.getSimpleValueType();
8181 SDValue Idx = Op.getOperand(1);
8182 MVT EltVT = Op.getSimpleValueType();
8184 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8186 // variable index can't be handled in mask registers,
8187 // extend vector to VR512
8188 if (!isa<ConstantSDNode>(Idx)) {
8189 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8190 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8191 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8192 ExtVT.getVectorElementType(), Ext, Idx);
8193 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8196 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8197 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8198 unsigned MaxSift = rc->getSize()*8 - 1;
8199 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8200 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8201 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8202 DAG.getConstant(MaxSift, MVT::i8));
8203 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8204 DAG.getIntPtrConstant(0));
8208 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8209 SelectionDAG &DAG) const {
8211 SDValue Vec = Op.getOperand(0);
8212 MVT VecVT = Vec.getSimpleValueType();
8213 SDValue Idx = Op.getOperand(1);
8215 if (Op.getSimpleValueType() == MVT::i1)
8216 return ExtractBitFromMaskVector(Op, DAG);
8218 if (!isa<ConstantSDNode>(Idx)) {
8219 if (VecVT.is512BitVector() ||
8220 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8221 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8224 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8225 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8226 MaskEltVT.getSizeInBits());
8228 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8229 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8230 getZeroVector(MaskVT, Subtarget, DAG, dl),
8231 Idx, DAG.getConstant(0, getPointerTy()));
8232 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8233 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8234 Perm, DAG.getConstant(0, getPointerTy()));
8239 // If this is a 256-bit vector result, first extract the 128-bit vector and
8240 // then extract the element from the 128-bit vector.
8241 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8243 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8244 // Get the 128-bit vector.
8245 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8246 MVT EltVT = VecVT.getVectorElementType();
8248 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8250 //if (IdxVal >= NumElems/2)
8251 // IdxVal -= NumElems/2;
8252 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8253 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8254 DAG.getConstant(IdxVal, MVT::i32));
8257 assert(VecVT.is128BitVector() && "Unexpected vector length");
8259 if (Subtarget->hasSSE41()) {
8260 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8265 MVT VT = Op.getSimpleValueType();
8266 // TODO: handle v16i8.
8267 if (VT.getSizeInBits() == 16) {
8268 SDValue Vec = Op.getOperand(0);
8269 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8271 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8272 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8273 DAG.getNode(ISD::BITCAST, dl,
8276 // Transform it so it match pextrw which produces a 32-bit result.
8277 MVT EltVT = MVT::i32;
8278 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8279 Op.getOperand(0), Op.getOperand(1));
8280 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8281 DAG.getValueType(VT));
8282 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8285 if (VT.getSizeInBits() == 32) {
8286 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8290 // SHUFPS the element to the lowest double word, then movss.
8291 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8292 MVT VVT = Op.getOperand(0).getSimpleValueType();
8293 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8294 DAG.getUNDEF(VVT), Mask);
8295 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8296 DAG.getIntPtrConstant(0));
8299 if (VT.getSizeInBits() == 64) {
8300 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8301 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8302 // to match extract_elt for f64.
8303 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8307 // UNPCKHPD the element to the lowest double word, then movsd.
8308 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8309 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8310 int Mask[2] = { 1, -1 };
8311 MVT VVT = Op.getOperand(0).getSimpleValueType();
8312 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8313 DAG.getUNDEF(VVT), Mask);
8314 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8315 DAG.getIntPtrConstant(0));
8321 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8322 MVT VT = Op.getSimpleValueType();
8323 MVT EltVT = VT.getVectorElementType();
8326 SDValue N0 = Op.getOperand(0);
8327 SDValue N1 = Op.getOperand(1);
8328 SDValue N2 = Op.getOperand(2);
8330 if (!VT.is128BitVector())
8333 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8334 isa<ConstantSDNode>(N2)) {
8336 if (VT == MVT::v8i16)
8337 Opc = X86ISD::PINSRW;
8338 else if (VT == MVT::v16i8)
8339 Opc = X86ISD::PINSRB;
8341 Opc = X86ISD::PINSRB;
8343 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8345 if (N1.getValueType() != MVT::i32)
8346 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8347 if (N2.getValueType() != MVT::i32)
8348 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8349 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8352 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8353 // Bits [7:6] of the constant are the source select. This will always be
8354 // zero here. The DAG Combiner may combine an extract_elt index into these
8355 // bits. For example (insert (extract, 3), 2) could be matched by putting
8356 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8357 // Bits [5:4] of the constant are the destination select. This is the
8358 // value of the incoming immediate.
8359 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8360 // combine either bitwise AND or insert of float 0.0 to set these bits.
8361 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8362 // Create this as a scalar to vector..
8363 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8364 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8367 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8368 // PINSR* works with constant index.
8374 /// Insert one bit to mask vector, like v16i1 or v8i1.
8375 /// AVX-512 feature.
8377 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8379 SDValue Vec = Op.getOperand(0);
8380 SDValue Elt = Op.getOperand(1);
8381 SDValue Idx = Op.getOperand(2);
8382 MVT VecVT = Vec.getSimpleValueType();
8384 if (!isa<ConstantSDNode>(Idx)) {
8385 // Non constant index. Extend source and destination,
8386 // insert element and then truncate the result.
8387 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8388 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8389 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8390 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8391 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8392 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8395 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8396 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8397 if (Vec.getOpcode() == ISD::UNDEF)
8398 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8399 DAG.getConstant(IdxVal, MVT::i8));
8400 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8401 unsigned MaxSift = rc->getSize()*8 - 1;
8402 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8403 DAG.getConstant(MaxSift, MVT::i8));
8404 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8405 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8406 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8409 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8410 MVT VT = Op.getSimpleValueType();
8411 MVT EltVT = VT.getVectorElementType();
8413 if (EltVT == MVT::i1)
8414 return InsertBitToMaskVector(Op, DAG);
8417 SDValue N0 = Op.getOperand(0);
8418 SDValue N1 = Op.getOperand(1);
8419 SDValue N2 = Op.getOperand(2);
8421 // If this is a 256-bit vector result, first extract the 128-bit vector,
8422 // insert the element into the extracted half and then place it back.
8423 if (VT.is256BitVector() || VT.is512BitVector()) {
8424 if (!isa<ConstantSDNode>(N2))
8427 // Get the desired 128-bit vector half.
8428 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8429 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8431 // Insert the element into the desired half.
8432 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8433 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8435 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8436 DAG.getConstant(IdxIn128, MVT::i32));
8438 // Insert the changed part back to the 256-bit vector
8439 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8442 if (Subtarget->hasSSE41())
8443 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8445 if (EltVT == MVT::i8)
8448 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8449 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8450 // as its second argument.
8451 if (N1.getValueType() != MVT::i32)
8452 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8453 if (N2.getValueType() != MVT::i32)
8454 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8455 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8460 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8462 MVT OpVT = Op.getSimpleValueType();
8464 // If this is a 256-bit vector result, first insert into a 128-bit
8465 // vector and then insert into the 256-bit vector.
8466 if (!OpVT.is128BitVector()) {
8467 // Insert into a 128-bit vector.
8468 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8469 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8470 OpVT.getVectorNumElements() / SizeFactor);
8472 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8474 // Insert the 128-bit vector.
8475 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8478 if (OpVT == MVT::v1i64 &&
8479 Op.getOperand(0).getValueType() == MVT::i64)
8480 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8482 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8483 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8484 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8485 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8488 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8489 // a simple subregister reference or explicit instructions to grab
8490 // upper bits of a vector.
8491 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8492 SelectionDAG &DAG) {
8494 SDValue In = Op.getOperand(0);
8495 SDValue Idx = Op.getOperand(1);
8496 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8497 MVT ResVT = Op.getSimpleValueType();
8498 MVT InVT = In.getSimpleValueType();
8500 if (Subtarget->hasFp256()) {
8501 if (ResVT.is128BitVector() &&
8502 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8503 isa<ConstantSDNode>(Idx)) {
8504 return Extract128BitVector(In, IdxVal, DAG, dl);
8506 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8507 isa<ConstantSDNode>(Idx)) {
8508 return Extract256BitVector(In, IdxVal, DAG, dl);
8514 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8515 // simple superregister reference or explicit instructions to insert
8516 // the upper bits of a vector.
8517 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8518 SelectionDAG &DAG) {
8519 if (Subtarget->hasFp256()) {
8520 SDLoc dl(Op.getNode());
8521 SDValue Vec = Op.getNode()->getOperand(0);
8522 SDValue SubVec = Op.getNode()->getOperand(1);
8523 SDValue Idx = Op.getNode()->getOperand(2);
8525 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8526 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8527 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8528 isa<ConstantSDNode>(Idx)) {
8529 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8530 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8533 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8534 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8535 isa<ConstantSDNode>(Idx)) {
8536 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8537 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8543 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8544 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8545 // one of the above mentioned nodes. It has to be wrapped because otherwise
8546 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8547 // be used to form addressing mode. These wrapped nodes will be selected
8550 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8551 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8553 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8555 unsigned char OpFlag = 0;
8556 unsigned WrapperKind = X86ISD::Wrapper;
8557 CodeModel::Model M = getTargetMachine().getCodeModel();
8559 if (Subtarget->isPICStyleRIPRel() &&
8560 (M == CodeModel::Small || M == CodeModel::Kernel))
8561 WrapperKind = X86ISD::WrapperRIP;
8562 else if (Subtarget->isPICStyleGOT())
8563 OpFlag = X86II::MO_GOTOFF;
8564 else if (Subtarget->isPICStyleStubPIC())
8565 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8567 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8569 CP->getOffset(), OpFlag);
8571 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8572 // With PIC, the address is actually $g + Offset.
8574 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8575 DAG.getNode(X86ISD::GlobalBaseReg,
8576 SDLoc(), getPointerTy()),
8583 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8584 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8586 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8588 unsigned char OpFlag = 0;
8589 unsigned WrapperKind = X86ISD::Wrapper;
8590 CodeModel::Model M = getTargetMachine().getCodeModel();
8592 if (Subtarget->isPICStyleRIPRel() &&
8593 (M == CodeModel::Small || M == CodeModel::Kernel))
8594 WrapperKind = X86ISD::WrapperRIP;
8595 else if (Subtarget->isPICStyleGOT())
8596 OpFlag = X86II::MO_GOTOFF;
8597 else if (Subtarget->isPICStyleStubPIC())
8598 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8600 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8603 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8605 // With PIC, the address is actually $g + Offset.
8607 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8608 DAG.getNode(X86ISD::GlobalBaseReg,
8609 SDLoc(), getPointerTy()),
8616 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8617 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8619 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8621 unsigned char OpFlag = 0;
8622 unsigned WrapperKind = X86ISD::Wrapper;
8623 CodeModel::Model M = getTargetMachine().getCodeModel();
8625 if (Subtarget->isPICStyleRIPRel() &&
8626 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8627 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8628 OpFlag = X86II::MO_GOTPCREL;
8629 WrapperKind = X86ISD::WrapperRIP;
8630 } else if (Subtarget->isPICStyleGOT()) {
8631 OpFlag = X86II::MO_GOT;
8632 } else if (Subtarget->isPICStyleStubPIC()) {
8633 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8634 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8635 OpFlag = X86II::MO_DARWIN_NONLAZY;
8638 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8641 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8643 // With PIC, the address is actually $g + Offset.
8644 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8645 !Subtarget->is64Bit()) {
8646 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8647 DAG.getNode(X86ISD::GlobalBaseReg,
8648 SDLoc(), getPointerTy()),
8652 // For symbols that require a load from a stub to get the address, emit the
8654 if (isGlobalStubReference(OpFlag))
8655 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8656 MachinePointerInfo::getGOT(), false, false, false, 0);
8662 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8663 // Create the TargetBlockAddressAddress node.
8664 unsigned char OpFlags =
8665 Subtarget->ClassifyBlockAddressReference();
8666 CodeModel::Model M = getTargetMachine().getCodeModel();
8667 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8668 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8670 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8673 if (Subtarget->isPICStyleRIPRel() &&
8674 (M == CodeModel::Small || M == CodeModel::Kernel))
8675 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8677 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8679 // With PIC, the address is actually $g + Offset.
8680 if (isGlobalRelativeToPICBase(OpFlags)) {
8681 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8682 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8690 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8691 int64_t Offset, SelectionDAG &DAG) const {
8692 // Create the TargetGlobalAddress node, folding in the constant
8693 // offset if it is legal.
8694 unsigned char OpFlags =
8695 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8696 CodeModel::Model M = getTargetMachine().getCodeModel();
8698 if (OpFlags == X86II::MO_NO_FLAG &&
8699 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8700 // A direct static reference to a global.
8701 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8704 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8707 if (Subtarget->isPICStyleRIPRel() &&
8708 (M == CodeModel::Small || M == CodeModel::Kernel))
8709 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8711 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8713 // With PIC, the address is actually $g + Offset.
8714 if (isGlobalRelativeToPICBase(OpFlags)) {
8715 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8716 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8720 // For globals that require a load from a stub to get the address, emit the
8722 if (isGlobalStubReference(OpFlags))
8723 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8724 MachinePointerInfo::getGOT(), false, false, false, 0);
8726 // If there was a non-zero offset that we didn't fold, create an explicit
8729 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8730 DAG.getConstant(Offset, getPointerTy()));
8736 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8737 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8738 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8739 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8743 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8744 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8745 unsigned char OperandFlags, bool LocalDynamic = false) {
8746 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8747 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8749 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8750 GA->getValueType(0),
8754 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8758 SDValue Ops[] = { Chain, TGA, *InFlag };
8759 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8761 SDValue Ops[] = { Chain, TGA };
8762 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8765 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8766 MFI->setAdjustsStack(true);
8768 SDValue Flag = Chain.getValue(1);
8769 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8772 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8774 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8777 SDLoc dl(GA); // ? function entry point might be better
8778 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8779 DAG.getNode(X86ISD::GlobalBaseReg,
8780 SDLoc(), PtrVT), InFlag);
8781 InFlag = Chain.getValue(1);
8783 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8786 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8788 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8790 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8791 X86::RAX, X86II::MO_TLSGD);
8794 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8800 // Get the start address of the TLS block for this module.
8801 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8802 .getInfo<X86MachineFunctionInfo>();
8803 MFI->incNumLocalDynamicTLSAccesses();
8807 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8808 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8811 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8812 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8813 InFlag = Chain.getValue(1);
8814 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8815 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8818 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8822 unsigned char OperandFlags = X86II::MO_DTPOFF;
8823 unsigned WrapperKind = X86ISD::Wrapper;
8824 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8825 GA->getValueType(0),
8826 GA->getOffset(), OperandFlags);
8827 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8829 // Add x@dtpoff with the base.
8830 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8833 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8834 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8835 const EVT PtrVT, TLSModel::Model model,
8836 bool is64Bit, bool isPIC) {
8839 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8840 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8841 is64Bit ? 257 : 256));
8843 SDValue ThreadPointer =
8844 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8845 MachinePointerInfo(Ptr), false, false, false, 0);
8847 unsigned char OperandFlags = 0;
8848 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8850 unsigned WrapperKind = X86ISD::Wrapper;
8851 if (model == TLSModel::LocalExec) {
8852 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8853 } else if (model == TLSModel::InitialExec) {
8855 OperandFlags = X86II::MO_GOTTPOFF;
8856 WrapperKind = X86ISD::WrapperRIP;
8858 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8861 llvm_unreachable("Unexpected model");
8864 // emit "addl x@ntpoff,%eax" (local exec)
8865 // or "addl x@indntpoff,%eax" (initial exec)
8866 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8868 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8869 GA->getOffset(), OperandFlags);
8870 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8872 if (model == TLSModel::InitialExec) {
8873 if (isPIC && !is64Bit) {
8874 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8875 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8879 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8880 MachinePointerInfo::getGOT(), false, false, false, 0);
8883 // The address of the thread local variable is the add of the thread
8884 // pointer with the offset of the variable.
8885 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8889 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8891 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8892 const GlobalValue *GV = GA->getGlobal();
8894 if (Subtarget->isTargetELF()) {
8895 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8898 case TLSModel::GeneralDynamic:
8899 if (Subtarget->is64Bit())
8900 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8901 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8902 case TLSModel::LocalDynamic:
8903 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8904 Subtarget->is64Bit());
8905 case TLSModel::InitialExec:
8906 case TLSModel::LocalExec:
8907 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8908 Subtarget->is64Bit(),
8909 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8911 llvm_unreachable("Unknown TLS model.");
8914 if (Subtarget->isTargetDarwin()) {
8915 // Darwin only has one model of TLS. Lower to that.
8916 unsigned char OpFlag = 0;
8917 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8918 X86ISD::WrapperRIP : X86ISD::Wrapper;
8920 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8922 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8923 !Subtarget->is64Bit();
8925 OpFlag = X86II::MO_TLVP_PIC_BASE;
8927 OpFlag = X86II::MO_TLVP;
8929 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8930 GA->getValueType(0),
8931 GA->getOffset(), OpFlag);
8932 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8934 // With PIC32, the address is actually $g + Offset.
8936 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8937 DAG.getNode(X86ISD::GlobalBaseReg,
8938 SDLoc(), getPointerTy()),
8941 // Lowering the machine isd will make sure everything is in the right
8943 SDValue Chain = DAG.getEntryNode();
8944 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8945 SDValue Args[] = { Chain, Offset };
8946 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8948 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8949 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8950 MFI->setAdjustsStack(true);
8952 // And our return value (tls address) is in the standard call return value
8954 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8955 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8959 if (Subtarget->isTargetKnownWindowsMSVC() ||
8960 Subtarget->isTargetWindowsGNU()) {
8961 // Just use the implicit TLS architecture
8962 // Need to generate someting similar to:
8963 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8965 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8966 // mov rcx, qword [rdx+rcx*8]
8967 // mov eax, .tls$:tlsvar
8968 // [rax+rcx] contains the address
8969 // Windows 64bit: gs:0x58
8970 // Windows 32bit: fs:__tls_array
8973 SDValue Chain = DAG.getEntryNode();
8975 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8976 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8977 // use its literal value of 0x2C.
8978 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8979 ? Type::getInt8PtrTy(*DAG.getContext(),
8981 : Type::getInt32PtrTy(*DAG.getContext(),
8985 Subtarget->is64Bit()
8986 ? DAG.getIntPtrConstant(0x58)
8987 : (Subtarget->isTargetWindowsGNU()
8988 ? DAG.getIntPtrConstant(0x2C)
8989 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8991 SDValue ThreadPointer =
8992 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8993 MachinePointerInfo(Ptr), false, false, false, 0);
8995 // Load the _tls_index variable
8996 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8997 if (Subtarget->is64Bit())
8998 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8999 IDX, MachinePointerInfo(), MVT::i32,
9002 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9003 false, false, false, 0);
9005 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9007 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9009 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9010 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9011 false, false, false, 0);
9013 // Get the offset of start of .tls section
9014 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9015 GA->getValueType(0),
9016 GA->getOffset(), X86II::MO_SECREL);
9017 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9019 // The address of the thread local variable is the add of the thread
9020 // pointer with the offset of the variable.
9021 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9024 llvm_unreachable("TLS not implemented for this target.");
9027 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9028 /// and take a 2 x i32 value to shift plus a shift amount.
9029 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9030 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9031 MVT VT = Op.getSimpleValueType();
9032 unsigned VTBits = VT.getSizeInBits();
9034 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9035 SDValue ShOpLo = Op.getOperand(0);
9036 SDValue ShOpHi = Op.getOperand(1);
9037 SDValue ShAmt = Op.getOperand(2);
9038 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9039 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9041 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9042 DAG.getConstant(VTBits - 1, MVT::i8));
9043 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9044 DAG.getConstant(VTBits - 1, MVT::i8))
9045 : DAG.getConstant(0, VT);
9048 if (Op.getOpcode() == ISD::SHL_PARTS) {
9049 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9050 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9052 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9053 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9056 // If the shift amount is larger or equal than the width of a part we can't
9057 // rely on the results of shld/shrd. Insert a test and select the appropriate
9058 // values for large shift amounts.
9059 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9060 DAG.getConstant(VTBits, MVT::i8));
9061 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9062 AndNode, DAG.getConstant(0, MVT::i8));
9065 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9066 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9067 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9069 if (Op.getOpcode() == ISD::SHL_PARTS) {
9070 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9071 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9073 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9074 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9077 SDValue Ops[2] = { Lo, Hi };
9078 return DAG.getMergeValues(Ops, dl);
9081 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9082 SelectionDAG &DAG) const {
9083 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9085 if (SrcVT.isVector())
9088 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9089 "Unknown SINT_TO_FP to lower!");
9091 // These are really Legal; return the operand so the caller accepts it as
9093 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9095 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9096 Subtarget->is64Bit()) {
9101 unsigned Size = SrcVT.getSizeInBits()/8;
9102 MachineFunction &MF = DAG.getMachineFunction();
9103 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9104 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9105 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9107 MachinePointerInfo::getFixedStack(SSFI),
9109 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9112 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9114 SelectionDAG &DAG) const {
9118 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9120 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9122 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9124 unsigned ByteSize = SrcVT.getSizeInBits()/8;
9126 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9127 MachineMemOperand *MMO;
9129 int SSFI = FI->getIndex();
9131 DAG.getMachineFunction()
9132 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9133 MachineMemOperand::MOLoad, ByteSize, ByteSize);
9135 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9136 StackSlot = StackSlot.getOperand(1);
9138 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9139 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9141 Tys, Ops, SrcVT, MMO);
9144 Chain = Result.getValue(1);
9145 SDValue InFlag = Result.getValue(2);
9147 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9148 // shouldn't be necessary except that RFP cannot be live across
9149 // multiple blocks. When stackifier is fixed, they can be uncoupled.
9150 MachineFunction &MF = DAG.getMachineFunction();
9151 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9152 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9153 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9154 Tys = DAG.getVTList(MVT::Other);
9156 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9158 MachineMemOperand *MMO =
9159 DAG.getMachineFunction()
9160 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9161 MachineMemOperand::MOStore, SSFISize, SSFISize);
9163 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9164 Ops, Op.getValueType(), MMO);
9165 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9166 MachinePointerInfo::getFixedStack(SSFI),
9167 false, false, false, 0);
9173 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9174 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9175 SelectionDAG &DAG) const {
9176 // This algorithm is not obvious. Here it is what we're trying to output:
9179 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9180 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9184 pshufd $0x4e, %xmm0, %xmm1
9190 LLVMContext *Context = DAG.getContext();
9192 // Build some magic constants.
9193 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9194 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9195 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9197 SmallVector<Constant*,2> CV1;
9199 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9200 APInt(64, 0x4330000000000000ULL))));
9202 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9203 APInt(64, 0x4530000000000000ULL))));
9204 Constant *C1 = ConstantVector::get(CV1);
9205 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9207 // Load the 64-bit value into an XMM register.
9208 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9210 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9211 MachinePointerInfo::getConstantPool(),
9212 false, false, false, 16);
9213 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9214 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9217 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9218 MachinePointerInfo::getConstantPool(),
9219 false, false, false, 16);
9220 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9221 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9224 if (Subtarget->hasSSE3()) {
9225 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9226 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9228 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9229 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9231 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9232 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9236 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9237 DAG.getIntPtrConstant(0));
9240 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9241 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9242 SelectionDAG &DAG) const {
9244 // FP constant to bias correct the final result.
9245 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9248 // Load the 32-bit value into an XMM register.
9249 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9252 // Zero out the upper parts of the register.
9253 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9255 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9256 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9257 DAG.getIntPtrConstant(0));
9259 // Or the load with the bias.
9260 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9261 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9262 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9264 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9265 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9266 MVT::v2f64, Bias)));
9267 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9268 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9269 DAG.getIntPtrConstant(0));
9271 // Subtract the bias.
9272 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9274 // Handle final rounding.
9275 EVT DestVT = Op.getValueType();
9277 if (DestVT.bitsLT(MVT::f64))
9278 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9279 DAG.getIntPtrConstant(0));
9280 if (DestVT.bitsGT(MVT::f64))
9281 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9283 // Handle final rounding.
9287 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9288 SelectionDAG &DAG) const {
9289 SDValue N0 = Op.getOperand(0);
9290 MVT SVT = N0.getSimpleValueType();
9293 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9294 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9295 "Custom UINT_TO_FP is not supported!");
9297 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9298 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9299 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9302 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9303 SelectionDAG &DAG) const {
9304 SDValue N0 = Op.getOperand(0);
9307 if (Op.getValueType().isVector())
9308 return lowerUINT_TO_FP_vec(Op, DAG);
9310 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9311 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9312 // the optimization here.
9313 if (DAG.SignBitIsZero(N0))
9314 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9316 MVT SrcVT = N0.getSimpleValueType();
9317 MVT DstVT = Op.getSimpleValueType();
9318 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9319 return LowerUINT_TO_FP_i64(Op, DAG);
9320 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9321 return LowerUINT_TO_FP_i32(Op, DAG);
9322 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9325 // Make a 64-bit buffer, and use it to build an FILD.
9326 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9327 if (SrcVT == MVT::i32) {
9328 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9329 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9330 getPointerTy(), StackSlot, WordOff);
9331 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9332 StackSlot, MachinePointerInfo(),
9334 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9335 OffsetSlot, MachinePointerInfo(),
9337 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9341 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9342 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9343 StackSlot, MachinePointerInfo(),
9345 // For i64 source, we need to add the appropriate power of 2 if the input
9346 // was negative. This is the same as the optimization in
9347 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9348 // we must be careful to do the computation in x87 extended precision, not
9349 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9350 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9351 MachineMemOperand *MMO =
9352 DAG.getMachineFunction()
9353 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9354 MachineMemOperand::MOLoad, 8, 8);
9356 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9357 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9358 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9361 APInt FF(32, 0x5F800000ULL);
9363 // Check whether the sign bit is set.
9364 SDValue SignSet = DAG.getSetCC(dl,
9365 getSetCCResultType(*DAG.getContext(), MVT::i64),
9366 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9369 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9370 SDValue FudgePtr = DAG.getConstantPool(
9371 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9374 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9375 SDValue Zero = DAG.getIntPtrConstant(0);
9376 SDValue Four = DAG.getIntPtrConstant(4);
9377 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9379 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9381 // Load the value out, extending it from f32 to f80.
9382 // FIXME: Avoid the extend by constructing the right constant pool?
9383 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9384 FudgePtr, MachinePointerInfo::getConstantPool(),
9385 MVT::f32, false, false, 4);
9386 // Extend everything to 80 bits to force it to be done on x87.
9387 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9388 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9391 std::pair<SDValue,SDValue>
9392 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9393 bool IsSigned, bool IsReplace) const {
9396 EVT DstTy = Op.getValueType();
9398 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9399 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9403 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9404 DstTy.getSimpleVT() >= MVT::i16 &&
9405 "Unknown FP_TO_INT to lower!");
9407 // These are really Legal.
9408 if (DstTy == MVT::i32 &&
9409 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9410 return std::make_pair(SDValue(), SDValue());
9411 if (Subtarget->is64Bit() &&
9412 DstTy == MVT::i64 &&
9413 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9414 return std::make_pair(SDValue(), SDValue());
9416 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9417 // stack slot, or into the FTOL runtime function.
9418 MachineFunction &MF = DAG.getMachineFunction();
9419 unsigned MemSize = DstTy.getSizeInBits()/8;
9420 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9421 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9424 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9425 Opc = X86ISD::WIN_FTOL;
9427 switch (DstTy.getSimpleVT().SimpleTy) {
9428 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9429 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9430 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9431 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9434 SDValue Chain = DAG.getEntryNode();
9435 SDValue Value = Op.getOperand(0);
9436 EVT TheVT = Op.getOperand(0).getValueType();
9437 // FIXME This causes a redundant load/store if the SSE-class value is already
9438 // in memory, such as if it is on the callstack.
9439 if (isScalarFPTypeInSSEReg(TheVT)) {
9440 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9441 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9442 MachinePointerInfo::getFixedStack(SSFI),
9444 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9446 Chain, StackSlot, DAG.getValueType(TheVT)
9449 MachineMemOperand *MMO =
9450 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9451 MachineMemOperand::MOLoad, MemSize, MemSize);
9452 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9453 Chain = Value.getValue(1);
9454 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9455 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9458 MachineMemOperand *MMO =
9459 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9460 MachineMemOperand::MOStore, MemSize, MemSize);
9462 if (Opc != X86ISD::WIN_FTOL) {
9463 // Build the FP_TO_INT*_IN_MEM
9464 SDValue Ops[] = { Chain, Value, StackSlot };
9465 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9467 return std::make_pair(FIST, StackSlot);
9469 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9470 DAG.getVTList(MVT::Other, MVT::Glue),
9472 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9473 MVT::i32, ftol.getValue(1));
9474 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9475 MVT::i32, eax.getValue(2));
9476 SDValue Ops[] = { eax, edx };
9477 SDValue pair = IsReplace
9478 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9479 : DAG.getMergeValues(Ops, DL);
9480 return std::make_pair(pair, SDValue());
9484 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9485 const X86Subtarget *Subtarget) {
9486 MVT VT = Op->getSimpleValueType(0);
9487 SDValue In = Op->getOperand(0);
9488 MVT InVT = In.getSimpleValueType();
9491 // Optimize vectors in AVX mode:
9494 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9495 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9496 // Concat upper and lower parts.
9499 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9500 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9501 // Concat upper and lower parts.
9504 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9505 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9506 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9509 if (Subtarget->hasInt256())
9510 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9512 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9513 SDValue Undef = DAG.getUNDEF(InVT);
9514 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9515 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9516 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9518 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9519 VT.getVectorNumElements()/2);
9521 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9522 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9524 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9527 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9528 SelectionDAG &DAG) {
9529 MVT VT = Op->getSimpleValueType(0);
9530 SDValue In = Op->getOperand(0);
9531 MVT InVT = In.getSimpleValueType();
9533 unsigned int NumElts = VT.getVectorNumElements();
9534 if (NumElts != 8 && NumElts != 16)
9537 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9538 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9540 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9541 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9542 // Now we have only mask extension
9543 assert(InVT.getVectorElementType() == MVT::i1);
9544 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9545 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9546 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9547 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9548 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9549 MachinePointerInfo::getConstantPool(),
9550 false, false, false, Alignment);
9552 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9553 if (VT.is512BitVector())
9555 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9558 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9559 SelectionDAG &DAG) {
9560 if (Subtarget->hasFp256()) {
9561 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9569 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9570 SelectionDAG &DAG) {
9572 MVT VT = Op.getSimpleValueType();
9573 SDValue In = Op.getOperand(0);
9574 MVT SVT = In.getSimpleValueType();
9576 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9577 return LowerZERO_EXTEND_AVX512(Op, DAG);
9579 if (Subtarget->hasFp256()) {
9580 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9585 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9586 VT.getVectorNumElements() != SVT.getVectorNumElements());
9590 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9592 MVT VT = Op.getSimpleValueType();
9593 SDValue In = Op.getOperand(0);
9594 MVT InVT = In.getSimpleValueType();
9596 if (VT == MVT::i1) {
9597 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9598 "Invalid scalar TRUNCATE operation");
9599 if (InVT == MVT::i32)
9601 if (InVT.getSizeInBits() == 64)
9602 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9603 else if (InVT.getSizeInBits() < 32)
9604 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9605 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9607 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9608 "Invalid TRUNCATE operation");
9610 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9611 if (VT.getVectorElementType().getSizeInBits() >=8)
9612 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9614 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9615 unsigned NumElts = InVT.getVectorNumElements();
9616 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9617 if (InVT.getSizeInBits() < 512) {
9618 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9619 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9623 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9624 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9625 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9626 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9627 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9628 MachinePointerInfo::getConstantPool(),
9629 false, false, false, Alignment);
9630 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9631 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9632 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9635 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9636 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9637 if (Subtarget->hasInt256()) {
9638 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9639 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9640 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9642 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9643 DAG.getIntPtrConstant(0));
9646 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9647 DAG.getIntPtrConstant(0));
9648 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9649 DAG.getIntPtrConstant(2));
9650 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9651 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9652 static const int ShufMask[] = {0, 2, 4, 6};
9653 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9656 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9657 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9658 if (Subtarget->hasInt256()) {
9659 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9661 SmallVector<SDValue,32> pshufbMask;
9662 for (unsigned i = 0; i < 2; ++i) {
9663 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9664 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9665 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9666 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9667 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9668 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9669 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9670 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9671 for (unsigned j = 0; j < 8; ++j)
9672 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9674 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9675 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9676 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9678 static const int ShufMask[] = {0, 2, -1, -1};
9679 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9681 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9682 DAG.getIntPtrConstant(0));
9683 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9686 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9687 DAG.getIntPtrConstant(0));
9689 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9690 DAG.getIntPtrConstant(4));
9692 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9693 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9696 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9697 -1, -1, -1, -1, -1, -1, -1, -1};
9699 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9700 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9701 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9703 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9704 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9706 // The MOVLHPS Mask:
9707 static const int ShufMask2[] = {0, 1, 4, 5};
9708 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9709 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9712 // Handle truncation of V256 to V128 using shuffles.
9713 if (!VT.is128BitVector() || !InVT.is256BitVector())
9716 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9718 unsigned NumElems = VT.getVectorNumElements();
9719 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9721 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9722 // Prepare truncation shuffle mask
9723 for (unsigned i = 0; i != NumElems; ++i)
9725 SDValue V = DAG.getVectorShuffle(NVT, DL,
9726 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9727 DAG.getUNDEF(NVT), &MaskVec[0]);
9728 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9729 DAG.getIntPtrConstant(0));
9732 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9733 SelectionDAG &DAG) const {
9734 assert(!Op.getSimpleValueType().isVector());
9736 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9737 /*IsSigned=*/ true, /*IsReplace=*/ false);
9738 SDValue FIST = Vals.first, StackSlot = Vals.second;
9739 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9740 if (!FIST.getNode()) return Op;
9742 if (StackSlot.getNode())
9744 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9745 FIST, StackSlot, MachinePointerInfo(),
9746 false, false, false, 0);
9748 // The node is the result.
9752 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9753 SelectionDAG &DAG) const {
9754 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9755 /*IsSigned=*/ false, /*IsReplace=*/ false);
9756 SDValue FIST = Vals.first, StackSlot = Vals.second;
9757 assert(FIST.getNode() && "Unexpected failure");
9759 if (StackSlot.getNode())
9761 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9762 FIST, StackSlot, MachinePointerInfo(),
9763 false, false, false, 0);
9765 // The node is the result.
9769 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9771 MVT VT = Op.getSimpleValueType();
9772 SDValue In = Op.getOperand(0);
9773 MVT SVT = In.getSimpleValueType();
9775 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9777 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9778 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9779 In, DAG.getUNDEF(SVT)));
9782 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9783 LLVMContext *Context = DAG.getContext();
9785 MVT VT = Op.getSimpleValueType();
9787 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9788 if (VT.isVector()) {
9789 EltVT = VT.getVectorElementType();
9790 NumElts = VT.getVectorNumElements();
9793 if (EltVT == MVT::f64)
9794 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9795 APInt(64, ~(1ULL << 63))));
9797 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9798 APInt(32, ~(1U << 31))));
9799 C = ConstantVector::getSplat(NumElts, C);
9800 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9801 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9802 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9803 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9804 MachinePointerInfo::getConstantPool(),
9805 false, false, false, Alignment);
9806 if (VT.isVector()) {
9807 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9808 return DAG.getNode(ISD::BITCAST, dl, VT,
9809 DAG.getNode(ISD::AND, dl, ANDVT,
9810 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9812 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9814 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9817 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9818 LLVMContext *Context = DAG.getContext();
9820 MVT VT = Op.getSimpleValueType();
9822 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9823 if (VT.isVector()) {
9824 EltVT = VT.getVectorElementType();
9825 NumElts = VT.getVectorNumElements();
9828 if (EltVT == MVT::f64)
9829 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9830 APInt(64, 1ULL << 63)));
9832 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9833 APInt(32, 1U << 31)));
9834 C = ConstantVector::getSplat(NumElts, C);
9835 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9836 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9837 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9838 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9839 MachinePointerInfo::getConstantPool(),
9840 false, false, false, Alignment);
9841 if (VT.isVector()) {
9842 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9843 return DAG.getNode(ISD::BITCAST, dl, VT,
9844 DAG.getNode(ISD::XOR, dl, XORVT,
9845 DAG.getNode(ISD::BITCAST, dl, XORVT,
9847 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9850 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9853 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9854 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9855 LLVMContext *Context = DAG.getContext();
9856 SDValue Op0 = Op.getOperand(0);
9857 SDValue Op1 = Op.getOperand(1);
9859 MVT VT = Op.getSimpleValueType();
9860 MVT SrcVT = Op1.getSimpleValueType();
9862 // If second operand is smaller, extend it first.
9863 if (SrcVT.bitsLT(VT)) {
9864 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9867 // And if it is bigger, shrink it first.
9868 if (SrcVT.bitsGT(VT)) {
9869 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9873 // At this point the operands and the result should have the same
9874 // type, and that won't be f80 since that is not custom lowered.
9876 // First get the sign bit of second operand.
9877 SmallVector<Constant*,4> CV;
9878 if (SrcVT == MVT::f64) {
9879 const fltSemantics &Sem = APFloat::IEEEdouble;
9880 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9881 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9883 const fltSemantics &Sem = APFloat::IEEEsingle;
9884 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9885 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9886 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9887 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9889 Constant *C = ConstantVector::get(CV);
9890 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9891 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9892 MachinePointerInfo::getConstantPool(),
9893 false, false, false, 16);
9894 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9896 // Shift sign bit right or left if the two operands have different types.
9897 if (SrcVT.bitsGT(VT)) {
9898 // Op0 is MVT::f32, Op1 is MVT::f64.
9899 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9900 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9901 DAG.getConstant(32, MVT::i32));
9902 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9903 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9904 DAG.getIntPtrConstant(0));
9907 // Clear first operand sign bit.
9909 if (VT == MVT::f64) {
9910 const fltSemantics &Sem = APFloat::IEEEdouble;
9911 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9912 APInt(64, ~(1ULL << 63)))));
9913 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9915 const fltSemantics &Sem = APFloat::IEEEsingle;
9916 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9917 APInt(32, ~(1U << 31)))));
9918 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9919 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9920 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9922 C = ConstantVector::get(CV);
9923 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9924 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9925 MachinePointerInfo::getConstantPool(),
9926 false, false, false, 16);
9927 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9929 // Or the value with the sign bit.
9930 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9933 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9934 SDValue N0 = Op.getOperand(0);
9936 MVT VT = Op.getSimpleValueType();
9938 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9939 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9940 DAG.getConstant(1, VT));
9941 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9944 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9946 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9947 SelectionDAG &DAG) {
9948 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9950 if (!Subtarget->hasSSE41())
9953 if (!Op->hasOneUse())
9956 SDNode *N = Op.getNode();
9959 SmallVector<SDValue, 8> Opnds;
9960 DenseMap<SDValue, unsigned> VecInMap;
9961 SmallVector<SDValue, 8> VecIns;
9962 EVT VT = MVT::Other;
9964 // Recognize a special case where a vector is casted into wide integer to
9966 Opnds.push_back(N->getOperand(0));
9967 Opnds.push_back(N->getOperand(1));
9969 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9970 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9971 // BFS traverse all OR'd operands.
9972 if (I->getOpcode() == ISD::OR) {
9973 Opnds.push_back(I->getOperand(0));
9974 Opnds.push_back(I->getOperand(1));
9975 // Re-evaluate the number of nodes to be traversed.
9976 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9980 // Quit if a non-EXTRACT_VECTOR_ELT
9981 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9984 // Quit if without a constant index.
9985 SDValue Idx = I->getOperand(1);
9986 if (!isa<ConstantSDNode>(Idx))
9989 SDValue ExtractedFromVec = I->getOperand(0);
9990 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9991 if (M == VecInMap.end()) {
9992 VT = ExtractedFromVec.getValueType();
9993 // Quit if not 128/256-bit vector.
9994 if (!VT.is128BitVector() && !VT.is256BitVector())
9996 // Quit if not the same type.
9997 if (VecInMap.begin() != VecInMap.end() &&
9998 VT != VecInMap.begin()->first.getValueType())
10000 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10001 VecIns.push_back(ExtractedFromVec);
10003 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10006 assert((VT.is128BitVector() || VT.is256BitVector()) &&
10007 "Not extracted from 128-/256-bit vector.");
10009 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10011 for (DenseMap<SDValue, unsigned>::const_iterator
10012 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10013 // Quit if not all elements are used.
10014 if (I->second != FullMask)
10018 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10020 // Cast all vectors into TestVT for PTEST.
10021 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10022 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10024 // If more than one full vectors are evaluated, OR them first before PTEST.
10025 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10026 // Each iteration will OR 2 nodes and append the result until there is only
10027 // 1 node left, i.e. the final OR'd value of all vectors.
10028 SDValue LHS = VecIns[Slot];
10029 SDValue RHS = VecIns[Slot + 1];
10030 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10033 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10034 VecIns.back(), VecIns.back());
10037 /// \brief return true if \c Op has a use that doesn't just read flags.
10038 static bool hasNonFlagsUse(SDValue Op) {
10039 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10041 SDNode *User = *UI;
10042 unsigned UOpNo = UI.getOperandNo();
10043 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10044 // Look pass truncate.
10045 UOpNo = User->use_begin().getOperandNo();
10046 User = *User->use_begin();
10049 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10050 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10056 /// Emit nodes that will be selected as "test Op0,Op0", or something
10058 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10059 SelectionDAG &DAG) const {
10060 if (Op.getValueType() == MVT::i1)
10061 // KORTEST instruction should be selected
10062 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10063 DAG.getConstant(0, Op.getValueType()));
10065 // CF and OF aren't always set the way we want. Determine which
10066 // of these we need.
10067 bool NeedCF = false;
10068 bool NeedOF = false;
10071 case X86::COND_A: case X86::COND_AE:
10072 case X86::COND_B: case X86::COND_BE:
10075 case X86::COND_G: case X86::COND_GE:
10076 case X86::COND_L: case X86::COND_LE:
10077 case X86::COND_O: case X86::COND_NO: {
10078 // Check if we really need to set the
10079 // Overflow flag. If NoSignedWrap is present
10080 // that is not actually needed.
10081 switch (Op->getOpcode()) {
10086 const BinaryWithFlagsSDNode *BinNode =
10087 cast<BinaryWithFlagsSDNode>(Op.getNode());
10088 if (BinNode->hasNoSignedWrap())
10098 // See if we can use the EFLAGS value from the operand instead of
10099 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10100 // we prove that the arithmetic won't overflow, we can't use OF or CF.
10101 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10102 // Emit a CMP with 0, which is the TEST pattern.
10103 //if (Op.getValueType() == MVT::i1)
10104 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10105 // DAG.getConstant(0, MVT::i1));
10106 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10107 DAG.getConstant(0, Op.getValueType()));
10109 unsigned Opcode = 0;
10110 unsigned NumOperands = 0;
10112 // Truncate operations may prevent the merge of the SETCC instruction
10113 // and the arithmetic instruction before it. Attempt to truncate the operands
10114 // of the arithmetic instruction and use a reduced bit-width instruction.
10115 bool NeedTruncation = false;
10116 SDValue ArithOp = Op;
10117 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10118 SDValue Arith = Op->getOperand(0);
10119 // Both the trunc and the arithmetic op need to have one user each.
10120 if (Arith->hasOneUse())
10121 switch (Arith.getOpcode()) {
10128 NeedTruncation = true;
10134 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10135 // which may be the result of a CAST. We use the variable 'Op', which is the
10136 // non-casted variable when we check for possible users.
10137 switch (ArithOp.getOpcode()) {
10139 // Due to an isel shortcoming, be conservative if this add is likely to be
10140 // selected as part of a load-modify-store instruction. When the root node
10141 // in a match is a store, isel doesn't know how to remap non-chain non-flag
10142 // uses of other nodes in the match, such as the ADD in this case. This
10143 // leads to the ADD being left around and reselected, with the result being
10144 // two adds in the output. Alas, even if none our users are stores, that
10145 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
10146 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
10147 // climbing the DAG back to the root, and it doesn't seem to be worth the
10149 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10150 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10151 if (UI->getOpcode() != ISD::CopyToReg &&
10152 UI->getOpcode() != ISD::SETCC &&
10153 UI->getOpcode() != ISD::STORE)
10156 if (ConstantSDNode *C =
10157 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10158 // An add of one will be selected as an INC.
10159 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10160 Opcode = X86ISD::INC;
10165 // An add of negative one (subtract of one) will be selected as a DEC.
10166 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10167 Opcode = X86ISD::DEC;
10173 // Otherwise use a regular EFLAGS-setting add.
10174 Opcode = X86ISD::ADD;
10179 // If we have a constant logical shift that's only used in a comparison
10180 // against zero turn it into an equivalent AND. This allows turning it into
10181 // a TEST instruction later.
10182 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10183 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10184 EVT VT = Op.getValueType();
10185 unsigned BitWidth = VT.getSizeInBits();
10186 unsigned ShAmt = Op->getConstantOperandVal(1);
10187 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10189 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10190 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10191 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10192 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10194 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10195 DAG.getConstant(Mask, VT));
10196 DAG.ReplaceAllUsesWith(Op, New);
10202 // If the primary and result isn't used, don't bother using X86ISD::AND,
10203 // because a TEST instruction will be better.
10204 if (!hasNonFlagsUse(Op))
10210 // Due to the ISEL shortcoming noted above, be conservative if this op is
10211 // likely to be selected as part of a load-modify-store instruction.
10212 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10213 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10214 if (UI->getOpcode() == ISD::STORE)
10217 // Otherwise use a regular EFLAGS-setting instruction.
10218 switch (ArithOp.getOpcode()) {
10219 default: llvm_unreachable("unexpected operator!");
10220 case ISD::SUB: Opcode = X86ISD::SUB; break;
10221 case ISD::XOR: Opcode = X86ISD::XOR; break;
10222 case ISD::AND: Opcode = X86ISD::AND; break;
10224 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10225 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10226 if (EFLAGS.getNode())
10229 Opcode = X86ISD::OR;
10243 return SDValue(Op.getNode(), 1);
10249 // If we found that truncation is beneficial, perform the truncation and
10251 if (NeedTruncation) {
10252 EVT VT = Op.getValueType();
10253 SDValue WideVal = Op->getOperand(0);
10254 EVT WideVT = WideVal.getValueType();
10255 unsigned ConvertedOp = 0;
10256 // Use a target machine opcode to prevent further DAGCombine
10257 // optimizations that may separate the arithmetic operations
10258 // from the setcc node.
10259 switch (WideVal.getOpcode()) {
10261 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10262 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10263 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10264 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10265 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10269 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10270 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10271 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10272 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10273 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10279 // Emit a CMP with 0, which is the TEST pattern.
10280 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10281 DAG.getConstant(0, Op.getValueType()));
10283 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10284 SmallVector<SDValue, 4> Ops;
10285 for (unsigned i = 0; i != NumOperands; ++i)
10286 Ops.push_back(Op.getOperand(i));
10288 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10289 DAG.ReplaceAllUsesWith(Op, New);
10290 return SDValue(New.getNode(), 1);
10293 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10295 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10296 SDLoc dl, SelectionDAG &DAG) const {
10297 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10298 if (C->getAPIntValue() == 0)
10299 return EmitTest(Op0, X86CC, dl, DAG);
10301 if (Op0.getValueType() == MVT::i1)
10302 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10305 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10306 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10307 // Do the comparison at i32 if it's smaller, besides the Atom case.
10308 // This avoids subregister aliasing issues. Keep the smaller reference
10309 // if we're optimizing for size, however, as that'll allow better folding
10310 // of memory operations.
10311 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10312 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10313 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10314 !Subtarget->isAtom()) {
10315 unsigned ExtendOp =
10316 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10317 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10318 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10320 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10321 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10322 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10324 return SDValue(Sub.getNode(), 1);
10326 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10329 /// Convert a comparison if required by the subtarget.
10330 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10331 SelectionDAG &DAG) const {
10332 // If the subtarget does not support the FUCOMI instruction, floating-point
10333 // comparisons have to be converted.
10334 if (Subtarget->hasCMov() ||
10335 Cmp.getOpcode() != X86ISD::CMP ||
10336 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10337 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10340 // The instruction selector will select an FUCOM instruction instead of
10341 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10342 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10343 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10345 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10346 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10347 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10348 DAG.getConstant(8, MVT::i8));
10349 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10350 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10353 static bool isAllOnes(SDValue V) {
10354 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10355 return C && C->isAllOnesValue();
10358 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10359 /// if it's possible.
10360 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10361 SDLoc dl, SelectionDAG &DAG) const {
10362 SDValue Op0 = And.getOperand(0);
10363 SDValue Op1 = And.getOperand(1);
10364 if (Op0.getOpcode() == ISD::TRUNCATE)
10365 Op0 = Op0.getOperand(0);
10366 if (Op1.getOpcode() == ISD::TRUNCATE)
10367 Op1 = Op1.getOperand(0);
10370 if (Op1.getOpcode() == ISD::SHL)
10371 std::swap(Op0, Op1);
10372 if (Op0.getOpcode() == ISD::SHL) {
10373 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10374 if (And00C->getZExtValue() == 1) {
10375 // If we looked past a truncate, check that it's only truncating away
10377 unsigned BitWidth = Op0.getValueSizeInBits();
10378 unsigned AndBitWidth = And.getValueSizeInBits();
10379 if (BitWidth > AndBitWidth) {
10381 DAG.computeKnownBits(Op0, Zeros, Ones);
10382 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10386 RHS = Op0.getOperand(1);
10388 } else if (Op1.getOpcode() == ISD::Constant) {
10389 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10390 uint64_t AndRHSVal = AndRHS->getZExtValue();
10391 SDValue AndLHS = Op0;
10393 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10394 LHS = AndLHS.getOperand(0);
10395 RHS = AndLHS.getOperand(1);
10398 // Use BT if the immediate can't be encoded in a TEST instruction.
10399 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10401 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10405 if (LHS.getNode()) {
10406 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10407 // instruction. Since the shift amount is in-range-or-undefined, we know
10408 // that doing a bittest on the i32 value is ok. We extend to i32 because
10409 // the encoding for the i16 version is larger than the i32 version.
10410 // Also promote i16 to i32 for performance / code size reason.
10411 if (LHS.getValueType() == MVT::i8 ||
10412 LHS.getValueType() == MVT::i16)
10413 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10415 // If the operand types disagree, extend the shift amount to match. Since
10416 // BT ignores high bits (like shifts) we can use anyextend.
10417 if (LHS.getValueType() != RHS.getValueType())
10418 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10420 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10421 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10422 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10423 DAG.getConstant(Cond, MVT::i8), BT);
10429 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10431 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10436 // SSE Condition code mapping:
10445 switch (SetCCOpcode) {
10446 default: llvm_unreachable("Unexpected SETCC condition");
10448 case ISD::SETEQ: SSECC = 0; break;
10450 case ISD::SETGT: Swap = true; // Fallthrough
10452 case ISD::SETOLT: SSECC = 1; break;
10454 case ISD::SETGE: Swap = true; // Fallthrough
10456 case ISD::SETOLE: SSECC = 2; break;
10457 case ISD::SETUO: SSECC = 3; break;
10459 case ISD::SETNE: SSECC = 4; break;
10460 case ISD::SETULE: Swap = true; // Fallthrough
10461 case ISD::SETUGE: SSECC = 5; break;
10462 case ISD::SETULT: Swap = true; // Fallthrough
10463 case ISD::SETUGT: SSECC = 6; break;
10464 case ISD::SETO: SSECC = 7; break;
10466 case ISD::SETONE: SSECC = 8; break;
10469 std::swap(Op0, Op1);
10474 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10475 // ones, and then concatenate the result back.
10476 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10477 MVT VT = Op.getSimpleValueType();
10479 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10480 "Unsupported value type for operation");
10482 unsigned NumElems = VT.getVectorNumElements();
10484 SDValue CC = Op.getOperand(2);
10486 // Extract the LHS vectors
10487 SDValue LHS = Op.getOperand(0);
10488 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10489 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10491 // Extract the RHS vectors
10492 SDValue RHS = Op.getOperand(1);
10493 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10494 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10496 // Issue the operation on the smaller types and concatenate the result back
10497 MVT EltVT = VT.getVectorElementType();
10498 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10499 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10500 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10501 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10504 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10505 const X86Subtarget *Subtarget) {
10506 SDValue Op0 = Op.getOperand(0);
10507 SDValue Op1 = Op.getOperand(1);
10508 SDValue CC = Op.getOperand(2);
10509 MVT VT = Op.getSimpleValueType();
10512 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10513 Op.getValueType().getScalarType() == MVT::i1 &&
10514 "Cannot set masked compare for this operation");
10516 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10518 bool Unsigned = false;
10521 switch (SetCCOpcode) {
10522 default: llvm_unreachable("Unexpected SETCC condition");
10523 case ISD::SETNE: SSECC = 4; break;
10524 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10525 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10526 case ISD::SETLT: Swap = true; //fall-through
10527 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10528 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10529 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10530 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10531 case ISD::SETULE: Unsigned = true; //fall-through
10532 case ISD::SETLE: SSECC = 2; break;
10536 std::swap(Op0, Op1);
10538 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10539 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10540 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10541 DAG.getConstant(SSECC, MVT::i8));
10544 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10545 /// operand \p Op1. If non-trivial (for example because it's not constant)
10546 /// return an empty value.
10547 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10549 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10553 MVT VT = Op1.getSimpleValueType();
10554 MVT EVT = VT.getVectorElementType();
10555 unsigned n = VT.getVectorNumElements();
10556 SmallVector<SDValue, 8> ULTOp1;
10558 for (unsigned i = 0; i < n; ++i) {
10559 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10560 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10563 // Avoid underflow.
10564 APInt Val = Elt->getAPIntValue();
10568 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10571 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10574 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10575 SelectionDAG &DAG) {
10576 SDValue Op0 = Op.getOperand(0);
10577 SDValue Op1 = Op.getOperand(1);
10578 SDValue CC = Op.getOperand(2);
10579 MVT VT = Op.getSimpleValueType();
10580 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10581 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10586 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10587 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10590 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10591 unsigned Opc = X86ISD::CMPP;
10592 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10593 assert(VT.getVectorNumElements() <= 16);
10594 Opc = X86ISD::CMPM;
10596 // In the two special cases we can't handle, emit two comparisons.
10599 unsigned CombineOpc;
10600 if (SetCCOpcode == ISD::SETUEQ) {
10601 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10603 assert(SetCCOpcode == ISD::SETONE);
10604 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10607 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10608 DAG.getConstant(CC0, MVT::i8));
10609 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10610 DAG.getConstant(CC1, MVT::i8));
10611 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10613 // Handle all other FP comparisons here.
10614 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10615 DAG.getConstant(SSECC, MVT::i8));
10618 // Break 256-bit integer vector compare into smaller ones.
10619 if (VT.is256BitVector() && !Subtarget->hasInt256())
10620 return Lower256IntVSETCC(Op, DAG);
10622 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10623 EVT OpVT = Op1.getValueType();
10624 if (Subtarget->hasAVX512()) {
10625 if (Op1.getValueType().is512BitVector() ||
10626 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10627 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10629 // In AVX-512 architecture setcc returns mask with i1 elements,
10630 // But there is no compare instruction for i8 and i16 elements.
10631 // We are not talking about 512-bit operands in this case, these
10632 // types are illegal.
10634 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10635 OpVT.getVectorElementType().getSizeInBits() >= 8))
10636 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10637 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10640 // We are handling one of the integer comparisons here. Since SSE only has
10641 // GT and EQ comparisons for integer, swapping operands and multiple
10642 // operations may be required for some comparisons.
10644 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10645 bool Subus = false;
10647 switch (SetCCOpcode) {
10648 default: llvm_unreachable("Unexpected SETCC condition");
10649 case ISD::SETNE: Invert = true;
10650 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10651 case ISD::SETLT: Swap = true;
10652 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10653 case ISD::SETGE: Swap = true;
10654 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10655 Invert = true; break;
10656 case ISD::SETULT: Swap = true;
10657 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10658 FlipSigns = true; break;
10659 case ISD::SETUGE: Swap = true;
10660 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10661 FlipSigns = true; Invert = true; break;
10664 // Special case: Use min/max operations for SETULE/SETUGE
10665 MVT VET = VT.getVectorElementType();
10667 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10668 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10671 switch (SetCCOpcode) {
10673 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10674 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10677 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10680 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10681 if (!MinMax && hasSubus) {
10682 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10684 // t = psubus Op0, Op1
10685 // pcmpeq t, <0..0>
10686 switch (SetCCOpcode) {
10688 case ISD::SETULT: {
10689 // If the comparison is against a constant we can turn this into a
10690 // setule. With psubus, setule does not require a swap. This is
10691 // beneficial because the constant in the register is no longer
10692 // destructed as the destination so it can be hoisted out of a loop.
10693 // Only do this pre-AVX since vpcmp* is no longer destructive.
10694 if (Subtarget->hasAVX())
10696 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10697 if (ULEOp1.getNode()) {
10699 Subus = true; Invert = false; Swap = false;
10703 // Psubus is better than flip-sign because it requires no inversion.
10704 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10705 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10709 Opc = X86ISD::SUBUS;
10715 std::swap(Op0, Op1);
10717 // Check that the operation in question is available (most are plain SSE2,
10718 // but PCMPGTQ and PCMPEQQ have different requirements).
10719 if (VT == MVT::v2i64) {
10720 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10721 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10723 // First cast everything to the right type.
10724 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10725 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10727 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10728 // bits of the inputs before performing those operations. The lower
10729 // compare is always unsigned.
10732 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10734 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10735 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10736 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10737 Sign, Zero, Sign, Zero);
10739 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10740 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10742 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10743 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10744 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10746 // Create masks for only the low parts/high parts of the 64 bit integers.
10747 static const int MaskHi[] = { 1, 1, 3, 3 };
10748 static const int MaskLo[] = { 0, 0, 2, 2 };
10749 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10750 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10751 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10753 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10754 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10757 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10759 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10762 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10763 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10764 // pcmpeqd + pshufd + pand.
10765 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10767 // First cast everything to the right type.
10768 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10769 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10772 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10774 // Make sure the lower and upper halves are both all-ones.
10775 static const int Mask[] = { 1, 0, 3, 2 };
10776 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10777 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10780 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10782 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10786 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10787 // bits of the inputs before performing those operations.
10789 EVT EltVT = VT.getVectorElementType();
10790 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10791 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10792 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10795 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10797 // If the logical-not of the result is required, perform that now.
10799 Result = DAG.getNOT(dl, Result, VT);
10802 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10805 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10806 getZeroVector(VT, Subtarget, DAG, dl));
10811 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10813 MVT VT = Op.getSimpleValueType();
10815 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10817 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10818 && "SetCC type must be 8-bit or 1-bit integer");
10819 SDValue Op0 = Op.getOperand(0);
10820 SDValue Op1 = Op.getOperand(1);
10822 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10824 // Optimize to BT if possible.
10825 // Lower (X & (1 << N)) == 0 to BT(X, N).
10826 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10827 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10828 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10829 Op1.getOpcode() == ISD::Constant &&
10830 cast<ConstantSDNode>(Op1)->isNullValue() &&
10831 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10832 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10833 if (NewSetCC.getNode())
10837 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10839 if (Op1.getOpcode() == ISD::Constant &&
10840 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10841 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10842 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10844 // If the input is a setcc, then reuse the input setcc or use a new one with
10845 // the inverted condition.
10846 if (Op0.getOpcode() == X86ISD::SETCC) {
10847 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10848 bool Invert = (CC == ISD::SETNE) ^
10849 cast<ConstantSDNode>(Op1)->isNullValue();
10853 CCode = X86::GetOppositeBranchCondition(CCode);
10854 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10855 DAG.getConstant(CCode, MVT::i8),
10856 Op0.getOperand(1));
10858 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10862 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10863 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10864 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10866 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10867 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10870 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10871 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10872 if (X86CC == X86::COND_INVALID)
10875 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10876 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10877 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10878 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10880 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10884 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10885 static bool isX86LogicalCmp(SDValue Op) {
10886 unsigned Opc = Op.getNode()->getOpcode();
10887 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10888 Opc == X86ISD::SAHF)
10890 if (Op.getResNo() == 1 &&
10891 (Opc == X86ISD::ADD ||
10892 Opc == X86ISD::SUB ||
10893 Opc == X86ISD::ADC ||
10894 Opc == X86ISD::SBB ||
10895 Opc == X86ISD::SMUL ||
10896 Opc == X86ISD::UMUL ||
10897 Opc == X86ISD::INC ||
10898 Opc == X86ISD::DEC ||
10899 Opc == X86ISD::OR ||
10900 Opc == X86ISD::XOR ||
10901 Opc == X86ISD::AND))
10904 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10910 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10911 if (V.getOpcode() != ISD::TRUNCATE)
10914 SDValue VOp0 = V.getOperand(0);
10915 unsigned InBits = VOp0.getValueSizeInBits();
10916 unsigned Bits = V.getValueSizeInBits();
10917 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10920 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10921 bool addTest = true;
10922 SDValue Cond = Op.getOperand(0);
10923 SDValue Op1 = Op.getOperand(1);
10924 SDValue Op2 = Op.getOperand(2);
10926 EVT VT = Op1.getValueType();
10929 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10930 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10931 // sequence later on.
10932 if (Cond.getOpcode() == ISD::SETCC &&
10933 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10934 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10935 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10936 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10937 int SSECC = translateX86FSETCC(
10938 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10941 if (Subtarget->hasAVX512()) {
10942 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10943 DAG.getConstant(SSECC, MVT::i8));
10944 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10946 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10947 DAG.getConstant(SSECC, MVT::i8));
10948 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10949 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10950 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10954 if (Cond.getOpcode() == ISD::SETCC) {
10955 SDValue NewCond = LowerSETCC(Cond, DAG);
10956 if (NewCond.getNode())
10960 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10961 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10962 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10963 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10964 if (Cond.getOpcode() == X86ISD::SETCC &&
10965 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10966 isZero(Cond.getOperand(1).getOperand(1))) {
10967 SDValue Cmp = Cond.getOperand(1);
10969 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10971 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10972 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10973 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10975 SDValue CmpOp0 = Cmp.getOperand(0);
10976 // Apply further optimizations for special cases
10977 // (select (x != 0), -1, 0) -> neg & sbb
10978 // (select (x == 0), 0, -1) -> neg & sbb
10979 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10980 if (YC->isNullValue() &&
10981 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10982 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10983 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10984 DAG.getConstant(0, CmpOp0.getValueType()),
10986 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10987 DAG.getConstant(X86::COND_B, MVT::i8),
10988 SDValue(Neg.getNode(), 1));
10992 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10993 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10994 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10996 SDValue Res = // Res = 0 or -1.
10997 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10998 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11000 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11001 Res = DAG.getNOT(DL, Res, Res.getValueType());
11003 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11004 if (!N2C || !N2C->isNullValue())
11005 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11010 // Look past (and (setcc_carry (cmp ...)), 1).
11011 if (Cond.getOpcode() == ISD::AND &&
11012 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11013 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11014 if (C && C->getAPIntValue() == 1)
11015 Cond = Cond.getOperand(0);
11018 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11019 // setting operand in place of the X86ISD::SETCC.
11020 unsigned CondOpcode = Cond.getOpcode();
11021 if (CondOpcode == X86ISD::SETCC ||
11022 CondOpcode == X86ISD::SETCC_CARRY) {
11023 CC = Cond.getOperand(0);
11025 SDValue Cmp = Cond.getOperand(1);
11026 unsigned Opc = Cmp.getOpcode();
11027 MVT VT = Op.getSimpleValueType();
11029 bool IllegalFPCMov = false;
11030 if (VT.isFloatingPoint() && !VT.isVector() &&
11031 !isScalarFPTypeInSSEReg(VT)) // FPStack?
11032 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11034 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11035 Opc == X86ISD::BT) { // FIXME
11039 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11040 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11041 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11042 Cond.getOperand(0).getValueType() != MVT::i8)) {
11043 SDValue LHS = Cond.getOperand(0);
11044 SDValue RHS = Cond.getOperand(1);
11045 unsigned X86Opcode;
11048 switch (CondOpcode) {
11049 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11050 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11051 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11052 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11053 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11054 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11055 default: llvm_unreachable("unexpected overflowing operator");
11057 if (CondOpcode == ISD::UMULO)
11058 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11061 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11063 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11065 if (CondOpcode == ISD::UMULO)
11066 Cond = X86Op.getValue(2);
11068 Cond = X86Op.getValue(1);
11070 CC = DAG.getConstant(X86Cond, MVT::i8);
11075 // Look pass the truncate if the high bits are known zero.
11076 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11077 Cond = Cond.getOperand(0);
11079 // We know the result of AND is compared against zero. Try to match
11081 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11082 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11083 if (NewSetCC.getNode()) {
11084 CC = NewSetCC.getOperand(0);
11085 Cond = NewSetCC.getOperand(1);
11092 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11093 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11096 // a < b ? -1 : 0 -> RES = ~setcc_carry
11097 // a < b ? 0 : -1 -> RES = setcc_carry
11098 // a >= b ? -1 : 0 -> RES = setcc_carry
11099 // a >= b ? 0 : -1 -> RES = ~setcc_carry
11100 if (Cond.getOpcode() == X86ISD::SUB) {
11101 Cond = ConvertCmpIfNecessary(Cond, DAG);
11102 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11104 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11105 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11106 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11107 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11108 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11109 return DAG.getNOT(DL, Res, Res.getValueType());
11114 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11115 // widen the cmov and push the truncate through. This avoids introducing a new
11116 // branch during isel and doesn't add any extensions.
11117 if (Op.getValueType() == MVT::i8 &&
11118 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11119 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11120 if (T1.getValueType() == T2.getValueType() &&
11121 // Blacklist CopyFromReg to avoid partial register stalls.
11122 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11123 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11124 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11125 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11129 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11130 // condition is true.
11131 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11132 SDValue Ops[] = { Op2, Op1, CC, Cond };
11133 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11136 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11137 MVT VT = Op->getSimpleValueType(0);
11138 SDValue In = Op->getOperand(0);
11139 MVT InVT = In.getSimpleValueType();
11142 unsigned int NumElts = VT.getVectorNumElements();
11143 if (NumElts != 8 && NumElts != 16)
11146 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11147 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11149 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11150 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11152 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11153 Constant *C = ConstantInt::get(*DAG.getContext(),
11154 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11156 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11157 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11158 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11159 MachinePointerInfo::getConstantPool(),
11160 false, false, false, Alignment);
11161 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11162 if (VT.is512BitVector())
11164 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11167 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11168 SelectionDAG &DAG) {
11169 MVT VT = Op->getSimpleValueType(0);
11170 SDValue In = Op->getOperand(0);
11171 MVT InVT = In.getSimpleValueType();
11174 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11175 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11177 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11178 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11179 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11182 if (Subtarget->hasInt256())
11183 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11185 // Optimize vectors in AVX mode
11186 // Sign extend v8i16 to v8i32 and
11189 // Divide input vector into two parts
11190 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11191 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11192 // concat the vectors to original VT
11194 unsigned NumElems = InVT.getVectorNumElements();
11195 SDValue Undef = DAG.getUNDEF(InVT);
11197 SmallVector<int,8> ShufMask1(NumElems, -1);
11198 for (unsigned i = 0; i != NumElems/2; ++i)
11201 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11203 SmallVector<int,8> ShufMask2(NumElems, -1);
11204 for (unsigned i = 0; i != NumElems/2; ++i)
11205 ShufMask2[i] = i + NumElems/2;
11207 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11209 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11210 VT.getVectorNumElements()/2);
11212 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11213 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11215 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11218 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11219 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11220 // from the AND / OR.
11221 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11222 Opc = Op.getOpcode();
11223 if (Opc != ISD::OR && Opc != ISD::AND)
11225 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11226 Op.getOperand(0).hasOneUse() &&
11227 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11228 Op.getOperand(1).hasOneUse());
11231 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11232 // 1 and that the SETCC node has a single use.
11233 static bool isXor1OfSetCC(SDValue Op) {
11234 if (Op.getOpcode() != ISD::XOR)
11236 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11237 if (N1C && N1C->getAPIntValue() == 1) {
11238 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11239 Op.getOperand(0).hasOneUse();
11244 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11245 bool addTest = true;
11246 SDValue Chain = Op.getOperand(0);
11247 SDValue Cond = Op.getOperand(1);
11248 SDValue Dest = Op.getOperand(2);
11251 bool Inverted = false;
11253 if (Cond.getOpcode() == ISD::SETCC) {
11254 // Check for setcc([su]{add,sub,mul}o == 0).
11255 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11256 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11257 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11258 Cond.getOperand(0).getResNo() == 1 &&
11259 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11260 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11261 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11262 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11263 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11264 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11266 Cond = Cond.getOperand(0);
11268 SDValue NewCond = LowerSETCC(Cond, DAG);
11269 if (NewCond.getNode())
11274 // FIXME: LowerXALUO doesn't handle these!!
11275 else if (Cond.getOpcode() == X86ISD::ADD ||
11276 Cond.getOpcode() == X86ISD::SUB ||
11277 Cond.getOpcode() == X86ISD::SMUL ||
11278 Cond.getOpcode() == X86ISD::UMUL)
11279 Cond = LowerXALUO(Cond, DAG);
11282 // Look pass (and (setcc_carry (cmp ...)), 1).
11283 if (Cond.getOpcode() == ISD::AND &&
11284 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11285 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11286 if (C && C->getAPIntValue() == 1)
11287 Cond = Cond.getOperand(0);
11290 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11291 // setting operand in place of the X86ISD::SETCC.
11292 unsigned CondOpcode = Cond.getOpcode();
11293 if (CondOpcode == X86ISD::SETCC ||
11294 CondOpcode == X86ISD::SETCC_CARRY) {
11295 CC = Cond.getOperand(0);
11297 SDValue Cmp = Cond.getOperand(1);
11298 unsigned Opc = Cmp.getOpcode();
11299 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11300 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11304 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11308 // These can only come from an arithmetic instruction with overflow,
11309 // e.g. SADDO, UADDO.
11310 Cond = Cond.getNode()->getOperand(1);
11316 CondOpcode = Cond.getOpcode();
11317 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11318 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11319 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11320 Cond.getOperand(0).getValueType() != MVT::i8)) {
11321 SDValue LHS = Cond.getOperand(0);
11322 SDValue RHS = Cond.getOperand(1);
11323 unsigned X86Opcode;
11326 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11327 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11329 switch (CondOpcode) {
11330 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11332 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11334 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11337 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11338 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11340 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11342 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11345 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11346 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11347 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11348 default: llvm_unreachable("unexpected overflowing operator");
11351 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11352 if (CondOpcode == ISD::UMULO)
11353 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11356 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11358 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11360 if (CondOpcode == ISD::UMULO)
11361 Cond = X86Op.getValue(2);
11363 Cond = X86Op.getValue(1);
11365 CC = DAG.getConstant(X86Cond, MVT::i8);
11369 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11370 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11371 if (CondOpc == ISD::OR) {
11372 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11373 // two branches instead of an explicit OR instruction with a
11375 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11376 isX86LogicalCmp(Cmp)) {
11377 CC = Cond.getOperand(0).getOperand(0);
11378 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11379 Chain, Dest, CC, Cmp);
11380 CC = Cond.getOperand(1).getOperand(0);
11384 } else { // ISD::AND
11385 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11386 // two branches instead of an explicit AND instruction with a
11387 // separate test. However, we only do this if this block doesn't
11388 // have a fall-through edge, because this requires an explicit
11389 // jmp when the condition is false.
11390 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11391 isX86LogicalCmp(Cmp) &&
11392 Op.getNode()->hasOneUse()) {
11393 X86::CondCode CCode =
11394 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11395 CCode = X86::GetOppositeBranchCondition(CCode);
11396 CC = DAG.getConstant(CCode, MVT::i8);
11397 SDNode *User = *Op.getNode()->use_begin();
11398 // Look for an unconditional branch following this conditional branch.
11399 // We need this because we need to reverse the successors in order
11400 // to implement FCMP_OEQ.
11401 if (User->getOpcode() == ISD::BR) {
11402 SDValue FalseBB = User->getOperand(1);
11404 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11405 assert(NewBR == User);
11409 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11410 Chain, Dest, CC, Cmp);
11411 X86::CondCode CCode =
11412 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11413 CCode = X86::GetOppositeBranchCondition(CCode);
11414 CC = DAG.getConstant(CCode, MVT::i8);
11420 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11421 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11422 // It should be transformed during dag combiner except when the condition
11423 // is set by a arithmetics with overflow node.
11424 X86::CondCode CCode =
11425 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11426 CCode = X86::GetOppositeBranchCondition(CCode);
11427 CC = DAG.getConstant(CCode, MVT::i8);
11428 Cond = Cond.getOperand(0).getOperand(1);
11430 } else if (Cond.getOpcode() == ISD::SETCC &&
11431 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11432 // For FCMP_OEQ, we can emit
11433 // two branches instead of an explicit AND instruction with a
11434 // separate test. However, we only do this if this block doesn't
11435 // have a fall-through edge, because this requires an explicit
11436 // jmp when the condition is false.
11437 if (Op.getNode()->hasOneUse()) {
11438 SDNode *User = *Op.getNode()->use_begin();
11439 // Look for an unconditional branch following this conditional branch.
11440 // We need this because we need to reverse the successors in order
11441 // to implement FCMP_OEQ.
11442 if (User->getOpcode() == ISD::BR) {
11443 SDValue FalseBB = User->getOperand(1);
11445 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11446 assert(NewBR == User);
11450 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11451 Cond.getOperand(0), Cond.getOperand(1));
11452 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11453 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11454 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11455 Chain, Dest, CC, Cmp);
11456 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11461 } else if (Cond.getOpcode() == ISD::SETCC &&
11462 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11463 // For FCMP_UNE, we can emit
11464 // two branches instead of an explicit AND instruction with a
11465 // separate test. However, we only do this if this block doesn't
11466 // have a fall-through edge, because this requires an explicit
11467 // jmp when the condition is false.
11468 if (Op.getNode()->hasOneUse()) {
11469 SDNode *User = *Op.getNode()->use_begin();
11470 // Look for an unconditional branch following this conditional branch.
11471 // We need this because we need to reverse the successors in order
11472 // to implement FCMP_UNE.
11473 if (User->getOpcode() == ISD::BR) {
11474 SDValue FalseBB = User->getOperand(1);
11476 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11477 assert(NewBR == User);
11480 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11481 Cond.getOperand(0), Cond.getOperand(1));
11482 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11483 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11484 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11485 Chain, Dest, CC, Cmp);
11486 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11496 // Look pass the truncate if the high bits are known zero.
11497 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11498 Cond = Cond.getOperand(0);
11500 // We know the result of AND is compared against zero. Try to match
11502 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11503 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11504 if (NewSetCC.getNode()) {
11505 CC = NewSetCC.getOperand(0);
11506 Cond = NewSetCC.getOperand(1);
11513 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11514 CC = DAG.getConstant(X86Cond, MVT::i8);
11515 Cond = EmitTest(Cond, X86Cond, dl, DAG);
11517 Cond = ConvertCmpIfNecessary(Cond, DAG);
11518 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11519 Chain, Dest, CC, Cond);
11522 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11523 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11524 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11525 // that the guard pages used by the OS virtual memory manager are allocated in
11526 // correct sequence.
11528 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11529 SelectionDAG &DAG) const {
11530 MachineFunction &MF = DAG.getMachineFunction();
11531 bool SplitStack = MF.shouldSplitStack();
11532 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11537 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11538 SDNode* Node = Op.getNode();
11540 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11541 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11542 " not tell us which reg is the stack pointer!");
11543 EVT VT = Node->getValueType(0);
11544 SDValue Tmp1 = SDValue(Node, 0);
11545 SDValue Tmp2 = SDValue(Node, 1);
11546 SDValue Tmp3 = Node->getOperand(2);
11547 SDValue Chain = Tmp1.getOperand(0);
11549 // Chain the dynamic stack allocation so that it doesn't modify the stack
11550 // pointer when other instructions are using the stack.
11551 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11554 SDValue Size = Tmp2.getOperand(1);
11555 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11556 Chain = SP.getValue(1);
11557 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11558 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11559 unsigned StackAlign = TFI.getStackAlignment();
11560 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11561 if (Align > StackAlign)
11562 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11563 DAG.getConstant(-(uint64_t)Align, VT));
11564 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11566 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11567 DAG.getIntPtrConstant(0, true), SDValue(),
11570 SDValue Ops[2] = { Tmp1, Tmp2 };
11571 return DAG.getMergeValues(Ops, dl);
11575 SDValue Chain = Op.getOperand(0);
11576 SDValue Size = Op.getOperand(1);
11577 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11578 EVT VT = Op.getNode()->getValueType(0);
11580 bool Is64Bit = Subtarget->is64Bit();
11581 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11584 MachineRegisterInfo &MRI = MF.getRegInfo();
11587 // The 64 bit implementation of segmented stacks needs to clobber both r10
11588 // r11. This makes it impossible to use it along with nested parameters.
11589 const Function *F = MF.getFunction();
11591 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11593 if (I->hasNestAttr())
11594 report_fatal_error("Cannot use segmented stacks with functions that "
11595 "have nested arguments.");
11598 const TargetRegisterClass *AddrRegClass =
11599 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11600 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11601 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11602 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11603 DAG.getRegister(Vreg, SPTy));
11604 SDValue Ops1[2] = { Value, Chain };
11605 return DAG.getMergeValues(Ops1, dl);
11608 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11610 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11611 Flag = Chain.getValue(1);
11612 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11614 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11616 const X86RegisterInfo *RegInfo =
11617 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11618 unsigned SPReg = RegInfo->getStackRegister();
11619 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11620 Chain = SP.getValue(1);
11623 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11624 DAG.getConstant(-(uint64_t)Align, VT));
11625 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11628 SDValue Ops1[2] = { SP, Chain };
11629 return DAG.getMergeValues(Ops1, dl);
11633 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11634 MachineFunction &MF = DAG.getMachineFunction();
11635 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11637 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11640 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11641 // vastart just stores the address of the VarArgsFrameIndex slot into the
11642 // memory location argument.
11643 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11645 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11646 MachinePointerInfo(SV), false, false, 0);
11650 // gp_offset (0 - 6 * 8)
11651 // fp_offset (48 - 48 + 8 * 16)
11652 // overflow_arg_area (point to parameters coming in memory).
11654 SmallVector<SDValue, 8> MemOps;
11655 SDValue FIN = Op.getOperand(1);
11657 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11658 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11660 FIN, MachinePointerInfo(SV), false, false, 0);
11661 MemOps.push_back(Store);
11664 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11665 FIN, DAG.getIntPtrConstant(4));
11666 Store = DAG.getStore(Op.getOperand(0), DL,
11667 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11669 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11670 MemOps.push_back(Store);
11672 // Store ptr to overflow_arg_area
11673 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11674 FIN, DAG.getIntPtrConstant(4));
11675 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11677 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11678 MachinePointerInfo(SV, 8),
11680 MemOps.push_back(Store);
11682 // Store ptr to reg_save_area.
11683 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11684 FIN, DAG.getIntPtrConstant(8));
11685 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11687 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11688 MachinePointerInfo(SV, 16), false, false, 0);
11689 MemOps.push_back(Store);
11690 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11693 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11694 assert(Subtarget->is64Bit() &&
11695 "LowerVAARG only handles 64-bit va_arg!");
11696 assert((Subtarget->isTargetLinux() ||
11697 Subtarget->isTargetDarwin()) &&
11698 "Unhandled target in LowerVAARG");
11699 assert(Op.getNode()->getNumOperands() == 4);
11700 SDValue Chain = Op.getOperand(0);
11701 SDValue SrcPtr = Op.getOperand(1);
11702 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11703 unsigned Align = Op.getConstantOperandVal(3);
11706 EVT ArgVT = Op.getNode()->getValueType(0);
11707 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11708 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11711 // Decide which area this value should be read from.
11712 // TODO: Implement the AMD64 ABI in its entirety. This simple
11713 // selection mechanism works only for the basic types.
11714 if (ArgVT == MVT::f80) {
11715 llvm_unreachable("va_arg for f80 not yet implemented");
11716 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11717 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11718 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11719 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11721 llvm_unreachable("Unhandled argument type in LowerVAARG");
11724 if (ArgMode == 2) {
11725 // Sanity Check: Make sure using fp_offset makes sense.
11726 assert(!getTargetMachine().Options.UseSoftFloat &&
11727 !(DAG.getMachineFunction()
11728 .getFunction()->getAttributes()
11729 .hasAttribute(AttributeSet::FunctionIndex,
11730 Attribute::NoImplicitFloat)) &&
11731 Subtarget->hasSSE1());
11734 // Insert VAARG_64 node into the DAG
11735 // VAARG_64 returns two values: Variable Argument Address, Chain
11736 SmallVector<SDValue, 11> InstOps;
11737 InstOps.push_back(Chain);
11738 InstOps.push_back(SrcPtr);
11739 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11740 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11741 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11742 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11743 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11744 VTs, InstOps, MVT::i64,
11745 MachinePointerInfo(SV),
11747 /*Volatile=*/false,
11749 /*WriteMem=*/true);
11750 Chain = VAARG.getValue(1);
11752 // Load the next argument and return it
11753 return DAG.getLoad(ArgVT, dl,
11756 MachinePointerInfo(),
11757 false, false, false, 0);
11760 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11761 SelectionDAG &DAG) {
11762 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11763 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11764 SDValue Chain = Op.getOperand(0);
11765 SDValue DstPtr = Op.getOperand(1);
11766 SDValue SrcPtr = Op.getOperand(2);
11767 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11768 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11771 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11772 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11774 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11777 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11778 // amount is a constant. Takes immediate version of shift as input.
11779 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11780 SDValue SrcOp, uint64_t ShiftAmt,
11781 SelectionDAG &DAG) {
11782 MVT ElementType = VT.getVectorElementType();
11784 // Fold this packed shift into its first operand if ShiftAmt is 0.
11788 // Check for ShiftAmt >= element width
11789 if (ShiftAmt >= ElementType.getSizeInBits()) {
11790 if (Opc == X86ISD::VSRAI)
11791 ShiftAmt = ElementType.getSizeInBits() - 1;
11793 return DAG.getConstant(0, VT);
11796 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11797 && "Unknown target vector shift-by-constant node");
11799 // Fold this packed vector shift into a build vector if SrcOp is a
11800 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11801 if (VT == SrcOp.getSimpleValueType() &&
11802 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11803 SmallVector<SDValue, 8> Elts;
11804 unsigned NumElts = SrcOp->getNumOperands();
11805 ConstantSDNode *ND;
11808 default: llvm_unreachable(nullptr);
11809 case X86ISD::VSHLI:
11810 for (unsigned i=0; i!=NumElts; ++i) {
11811 SDValue CurrentOp = SrcOp->getOperand(i);
11812 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11813 Elts.push_back(CurrentOp);
11816 ND = cast<ConstantSDNode>(CurrentOp);
11817 const APInt &C = ND->getAPIntValue();
11818 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11821 case X86ISD::VSRLI:
11822 for (unsigned i=0; i!=NumElts; ++i) {
11823 SDValue CurrentOp = SrcOp->getOperand(i);
11824 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11825 Elts.push_back(CurrentOp);
11828 ND = cast<ConstantSDNode>(CurrentOp);
11829 const APInt &C = ND->getAPIntValue();
11830 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11833 case X86ISD::VSRAI:
11834 for (unsigned i=0; i!=NumElts; ++i) {
11835 SDValue CurrentOp = SrcOp->getOperand(i);
11836 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11837 Elts.push_back(CurrentOp);
11840 ND = cast<ConstantSDNode>(CurrentOp);
11841 const APInt &C = ND->getAPIntValue();
11842 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11847 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11850 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11853 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11854 // may or may not be a constant. Takes immediate version of shift as input.
11855 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11856 SDValue SrcOp, SDValue ShAmt,
11857 SelectionDAG &DAG) {
11858 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11860 // Catch shift-by-constant.
11861 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11862 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11863 CShAmt->getZExtValue(), DAG);
11865 // Change opcode to non-immediate version
11867 default: llvm_unreachable("Unknown target vector shift node");
11868 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11869 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11870 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11873 // Need to build a vector containing shift amount
11874 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11877 ShOps[1] = DAG.getConstant(0, MVT::i32);
11878 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11879 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11881 // The return type has to be a 128-bit type with the same element
11882 // type as the input type.
11883 MVT EltVT = VT.getVectorElementType();
11884 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11886 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11887 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11890 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11892 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11894 default: return SDValue(); // Don't custom lower most intrinsics.
11895 // Comparison intrinsics.
11896 case Intrinsic::x86_sse_comieq_ss:
11897 case Intrinsic::x86_sse_comilt_ss:
11898 case Intrinsic::x86_sse_comile_ss:
11899 case Intrinsic::x86_sse_comigt_ss:
11900 case Intrinsic::x86_sse_comige_ss:
11901 case Intrinsic::x86_sse_comineq_ss:
11902 case Intrinsic::x86_sse_ucomieq_ss:
11903 case Intrinsic::x86_sse_ucomilt_ss:
11904 case Intrinsic::x86_sse_ucomile_ss:
11905 case Intrinsic::x86_sse_ucomigt_ss:
11906 case Intrinsic::x86_sse_ucomige_ss:
11907 case Intrinsic::x86_sse_ucomineq_ss:
11908 case Intrinsic::x86_sse2_comieq_sd:
11909 case Intrinsic::x86_sse2_comilt_sd:
11910 case Intrinsic::x86_sse2_comile_sd:
11911 case Intrinsic::x86_sse2_comigt_sd:
11912 case Intrinsic::x86_sse2_comige_sd:
11913 case Intrinsic::x86_sse2_comineq_sd:
11914 case Intrinsic::x86_sse2_ucomieq_sd:
11915 case Intrinsic::x86_sse2_ucomilt_sd:
11916 case Intrinsic::x86_sse2_ucomile_sd:
11917 case Intrinsic::x86_sse2_ucomigt_sd:
11918 case Intrinsic::x86_sse2_ucomige_sd:
11919 case Intrinsic::x86_sse2_ucomineq_sd: {
11923 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11924 case Intrinsic::x86_sse_comieq_ss:
11925 case Intrinsic::x86_sse2_comieq_sd:
11926 Opc = X86ISD::COMI;
11929 case Intrinsic::x86_sse_comilt_ss:
11930 case Intrinsic::x86_sse2_comilt_sd:
11931 Opc = X86ISD::COMI;
11934 case Intrinsic::x86_sse_comile_ss:
11935 case Intrinsic::x86_sse2_comile_sd:
11936 Opc = X86ISD::COMI;
11939 case Intrinsic::x86_sse_comigt_ss:
11940 case Intrinsic::x86_sse2_comigt_sd:
11941 Opc = X86ISD::COMI;
11944 case Intrinsic::x86_sse_comige_ss:
11945 case Intrinsic::x86_sse2_comige_sd:
11946 Opc = X86ISD::COMI;
11949 case Intrinsic::x86_sse_comineq_ss:
11950 case Intrinsic::x86_sse2_comineq_sd:
11951 Opc = X86ISD::COMI;
11954 case Intrinsic::x86_sse_ucomieq_ss:
11955 case Intrinsic::x86_sse2_ucomieq_sd:
11956 Opc = X86ISD::UCOMI;
11959 case Intrinsic::x86_sse_ucomilt_ss:
11960 case Intrinsic::x86_sse2_ucomilt_sd:
11961 Opc = X86ISD::UCOMI;
11964 case Intrinsic::x86_sse_ucomile_ss:
11965 case Intrinsic::x86_sse2_ucomile_sd:
11966 Opc = X86ISD::UCOMI;
11969 case Intrinsic::x86_sse_ucomigt_ss:
11970 case Intrinsic::x86_sse2_ucomigt_sd:
11971 Opc = X86ISD::UCOMI;
11974 case Intrinsic::x86_sse_ucomige_ss:
11975 case Intrinsic::x86_sse2_ucomige_sd:
11976 Opc = X86ISD::UCOMI;
11979 case Intrinsic::x86_sse_ucomineq_ss:
11980 case Intrinsic::x86_sse2_ucomineq_sd:
11981 Opc = X86ISD::UCOMI;
11986 SDValue LHS = Op.getOperand(1);
11987 SDValue RHS = Op.getOperand(2);
11988 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11989 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11990 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11991 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11992 DAG.getConstant(X86CC, MVT::i8), Cond);
11993 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11996 // Arithmetic intrinsics.
11997 case Intrinsic::x86_sse2_pmulu_dq:
11998 case Intrinsic::x86_avx2_pmulu_dq:
11999 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12000 Op.getOperand(1), Op.getOperand(2));
12002 case Intrinsic::x86_sse41_pmuldq:
12003 case Intrinsic::x86_avx2_pmul_dq:
12004 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12005 Op.getOperand(1), Op.getOperand(2));
12007 case Intrinsic::x86_sse2_pmulhu_w:
12008 case Intrinsic::x86_avx2_pmulhu_w:
12009 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12010 Op.getOperand(1), Op.getOperand(2));
12012 case Intrinsic::x86_sse2_pmulh_w:
12013 case Intrinsic::x86_avx2_pmulh_w:
12014 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12015 Op.getOperand(1), Op.getOperand(2));
12017 // SSE2/AVX2 sub with unsigned saturation intrinsics
12018 case Intrinsic::x86_sse2_psubus_b:
12019 case Intrinsic::x86_sse2_psubus_w:
12020 case Intrinsic::x86_avx2_psubus_b:
12021 case Intrinsic::x86_avx2_psubus_w:
12022 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12023 Op.getOperand(1), Op.getOperand(2));
12025 // SSE3/AVX horizontal add/sub intrinsics
12026 case Intrinsic::x86_sse3_hadd_ps:
12027 case Intrinsic::x86_sse3_hadd_pd:
12028 case Intrinsic::x86_avx_hadd_ps_256:
12029 case Intrinsic::x86_avx_hadd_pd_256:
12030 case Intrinsic::x86_sse3_hsub_ps:
12031 case Intrinsic::x86_sse3_hsub_pd:
12032 case Intrinsic::x86_avx_hsub_ps_256:
12033 case Intrinsic::x86_avx_hsub_pd_256:
12034 case Intrinsic::x86_ssse3_phadd_w_128:
12035 case Intrinsic::x86_ssse3_phadd_d_128:
12036 case Intrinsic::x86_avx2_phadd_w:
12037 case Intrinsic::x86_avx2_phadd_d:
12038 case Intrinsic::x86_ssse3_phsub_w_128:
12039 case Intrinsic::x86_ssse3_phsub_d_128:
12040 case Intrinsic::x86_avx2_phsub_w:
12041 case Intrinsic::x86_avx2_phsub_d: {
12044 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12045 case Intrinsic::x86_sse3_hadd_ps:
12046 case Intrinsic::x86_sse3_hadd_pd:
12047 case Intrinsic::x86_avx_hadd_ps_256:
12048 case Intrinsic::x86_avx_hadd_pd_256:
12049 Opcode = X86ISD::FHADD;
12051 case Intrinsic::x86_sse3_hsub_ps:
12052 case Intrinsic::x86_sse3_hsub_pd:
12053 case Intrinsic::x86_avx_hsub_ps_256:
12054 case Intrinsic::x86_avx_hsub_pd_256:
12055 Opcode = X86ISD::FHSUB;
12057 case Intrinsic::x86_ssse3_phadd_w_128:
12058 case Intrinsic::x86_ssse3_phadd_d_128:
12059 case Intrinsic::x86_avx2_phadd_w:
12060 case Intrinsic::x86_avx2_phadd_d:
12061 Opcode = X86ISD::HADD;
12063 case Intrinsic::x86_ssse3_phsub_w_128:
12064 case Intrinsic::x86_ssse3_phsub_d_128:
12065 case Intrinsic::x86_avx2_phsub_w:
12066 case Intrinsic::x86_avx2_phsub_d:
12067 Opcode = X86ISD::HSUB;
12070 return DAG.getNode(Opcode, dl, Op.getValueType(),
12071 Op.getOperand(1), Op.getOperand(2));
12074 // SSE2/SSE41/AVX2 integer max/min intrinsics.
12075 case Intrinsic::x86_sse2_pmaxu_b:
12076 case Intrinsic::x86_sse41_pmaxuw:
12077 case Intrinsic::x86_sse41_pmaxud:
12078 case Intrinsic::x86_avx2_pmaxu_b:
12079 case Intrinsic::x86_avx2_pmaxu_w:
12080 case Intrinsic::x86_avx2_pmaxu_d:
12081 case Intrinsic::x86_sse2_pminu_b:
12082 case Intrinsic::x86_sse41_pminuw:
12083 case Intrinsic::x86_sse41_pminud:
12084 case Intrinsic::x86_avx2_pminu_b:
12085 case Intrinsic::x86_avx2_pminu_w:
12086 case Intrinsic::x86_avx2_pminu_d:
12087 case Intrinsic::x86_sse41_pmaxsb:
12088 case Intrinsic::x86_sse2_pmaxs_w:
12089 case Intrinsic::x86_sse41_pmaxsd:
12090 case Intrinsic::x86_avx2_pmaxs_b:
12091 case Intrinsic::x86_avx2_pmaxs_w:
12092 case Intrinsic::x86_avx2_pmaxs_d:
12093 case Intrinsic::x86_sse41_pminsb:
12094 case Intrinsic::x86_sse2_pmins_w:
12095 case Intrinsic::x86_sse41_pminsd:
12096 case Intrinsic::x86_avx2_pmins_b:
12097 case Intrinsic::x86_avx2_pmins_w:
12098 case Intrinsic::x86_avx2_pmins_d: {
12101 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12102 case Intrinsic::x86_sse2_pmaxu_b:
12103 case Intrinsic::x86_sse41_pmaxuw:
12104 case Intrinsic::x86_sse41_pmaxud:
12105 case Intrinsic::x86_avx2_pmaxu_b:
12106 case Intrinsic::x86_avx2_pmaxu_w:
12107 case Intrinsic::x86_avx2_pmaxu_d:
12108 Opcode = X86ISD::UMAX;
12110 case Intrinsic::x86_sse2_pminu_b:
12111 case Intrinsic::x86_sse41_pminuw:
12112 case Intrinsic::x86_sse41_pminud:
12113 case Intrinsic::x86_avx2_pminu_b:
12114 case Intrinsic::x86_avx2_pminu_w:
12115 case Intrinsic::x86_avx2_pminu_d:
12116 Opcode = X86ISD::UMIN;
12118 case Intrinsic::x86_sse41_pmaxsb:
12119 case Intrinsic::x86_sse2_pmaxs_w:
12120 case Intrinsic::x86_sse41_pmaxsd:
12121 case Intrinsic::x86_avx2_pmaxs_b:
12122 case Intrinsic::x86_avx2_pmaxs_w:
12123 case Intrinsic::x86_avx2_pmaxs_d:
12124 Opcode = X86ISD::SMAX;
12126 case Intrinsic::x86_sse41_pminsb:
12127 case Intrinsic::x86_sse2_pmins_w:
12128 case Intrinsic::x86_sse41_pminsd:
12129 case Intrinsic::x86_avx2_pmins_b:
12130 case Intrinsic::x86_avx2_pmins_w:
12131 case Intrinsic::x86_avx2_pmins_d:
12132 Opcode = X86ISD::SMIN;
12135 return DAG.getNode(Opcode, dl, Op.getValueType(),
12136 Op.getOperand(1), Op.getOperand(2));
12139 // SSE/SSE2/AVX floating point max/min intrinsics.
12140 case Intrinsic::x86_sse_max_ps:
12141 case Intrinsic::x86_sse2_max_pd:
12142 case Intrinsic::x86_avx_max_ps_256:
12143 case Intrinsic::x86_avx_max_pd_256:
12144 case Intrinsic::x86_sse_min_ps:
12145 case Intrinsic::x86_sse2_min_pd:
12146 case Intrinsic::x86_avx_min_ps_256:
12147 case Intrinsic::x86_avx_min_pd_256: {
12150 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12151 case Intrinsic::x86_sse_max_ps:
12152 case Intrinsic::x86_sse2_max_pd:
12153 case Intrinsic::x86_avx_max_ps_256:
12154 case Intrinsic::x86_avx_max_pd_256:
12155 Opcode = X86ISD::FMAX;
12157 case Intrinsic::x86_sse_min_ps:
12158 case Intrinsic::x86_sse2_min_pd:
12159 case Intrinsic::x86_avx_min_ps_256:
12160 case Intrinsic::x86_avx_min_pd_256:
12161 Opcode = X86ISD::FMIN;
12164 return DAG.getNode(Opcode, dl, Op.getValueType(),
12165 Op.getOperand(1), Op.getOperand(2));
12168 // AVX2 variable shift intrinsics
12169 case Intrinsic::x86_avx2_psllv_d:
12170 case Intrinsic::x86_avx2_psllv_q:
12171 case Intrinsic::x86_avx2_psllv_d_256:
12172 case Intrinsic::x86_avx2_psllv_q_256:
12173 case Intrinsic::x86_avx2_psrlv_d:
12174 case Intrinsic::x86_avx2_psrlv_q:
12175 case Intrinsic::x86_avx2_psrlv_d_256:
12176 case Intrinsic::x86_avx2_psrlv_q_256:
12177 case Intrinsic::x86_avx2_psrav_d:
12178 case Intrinsic::x86_avx2_psrav_d_256: {
12181 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12182 case Intrinsic::x86_avx2_psllv_d:
12183 case Intrinsic::x86_avx2_psllv_q:
12184 case Intrinsic::x86_avx2_psllv_d_256:
12185 case Intrinsic::x86_avx2_psllv_q_256:
12188 case Intrinsic::x86_avx2_psrlv_d:
12189 case Intrinsic::x86_avx2_psrlv_q:
12190 case Intrinsic::x86_avx2_psrlv_d_256:
12191 case Intrinsic::x86_avx2_psrlv_q_256:
12194 case Intrinsic::x86_avx2_psrav_d:
12195 case Intrinsic::x86_avx2_psrav_d_256:
12199 return DAG.getNode(Opcode, dl, Op.getValueType(),
12200 Op.getOperand(1), Op.getOperand(2));
12203 case Intrinsic::x86_ssse3_pshuf_b_128:
12204 case Intrinsic::x86_avx2_pshuf_b:
12205 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12206 Op.getOperand(1), Op.getOperand(2));
12208 case Intrinsic::x86_ssse3_psign_b_128:
12209 case Intrinsic::x86_ssse3_psign_w_128:
12210 case Intrinsic::x86_ssse3_psign_d_128:
12211 case Intrinsic::x86_avx2_psign_b:
12212 case Intrinsic::x86_avx2_psign_w:
12213 case Intrinsic::x86_avx2_psign_d:
12214 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12215 Op.getOperand(1), Op.getOperand(2));
12217 case Intrinsic::x86_sse41_insertps:
12218 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12219 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12221 case Intrinsic::x86_avx_vperm2f128_ps_256:
12222 case Intrinsic::x86_avx_vperm2f128_pd_256:
12223 case Intrinsic::x86_avx_vperm2f128_si_256:
12224 case Intrinsic::x86_avx2_vperm2i128:
12225 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12226 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12228 case Intrinsic::x86_avx2_permd:
12229 case Intrinsic::x86_avx2_permps:
12230 // Operands intentionally swapped. Mask is last operand to intrinsic,
12231 // but second operand for node/instruction.
12232 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12233 Op.getOperand(2), Op.getOperand(1));
12235 case Intrinsic::x86_sse_sqrt_ps:
12236 case Intrinsic::x86_sse2_sqrt_pd:
12237 case Intrinsic::x86_avx_sqrt_ps_256:
12238 case Intrinsic::x86_avx_sqrt_pd_256:
12239 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12241 // ptest and testp intrinsics. The intrinsic these come from are designed to
12242 // return an integer value, not just an instruction so lower it to the ptest
12243 // or testp pattern and a setcc for the result.
12244 case Intrinsic::x86_sse41_ptestz:
12245 case Intrinsic::x86_sse41_ptestc:
12246 case Intrinsic::x86_sse41_ptestnzc:
12247 case Intrinsic::x86_avx_ptestz_256:
12248 case Intrinsic::x86_avx_ptestc_256:
12249 case Intrinsic::x86_avx_ptestnzc_256:
12250 case Intrinsic::x86_avx_vtestz_ps:
12251 case Intrinsic::x86_avx_vtestc_ps:
12252 case Intrinsic::x86_avx_vtestnzc_ps:
12253 case Intrinsic::x86_avx_vtestz_pd:
12254 case Intrinsic::x86_avx_vtestc_pd:
12255 case Intrinsic::x86_avx_vtestnzc_pd:
12256 case Intrinsic::x86_avx_vtestz_ps_256:
12257 case Intrinsic::x86_avx_vtestc_ps_256:
12258 case Intrinsic::x86_avx_vtestnzc_ps_256:
12259 case Intrinsic::x86_avx_vtestz_pd_256:
12260 case Intrinsic::x86_avx_vtestc_pd_256:
12261 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12262 bool IsTestPacked = false;
12265 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12266 case Intrinsic::x86_avx_vtestz_ps:
12267 case Intrinsic::x86_avx_vtestz_pd:
12268 case Intrinsic::x86_avx_vtestz_ps_256:
12269 case Intrinsic::x86_avx_vtestz_pd_256:
12270 IsTestPacked = true; // Fallthrough
12271 case Intrinsic::x86_sse41_ptestz:
12272 case Intrinsic::x86_avx_ptestz_256:
12274 X86CC = X86::COND_E;
12276 case Intrinsic::x86_avx_vtestc_ps:
12277 case Intrinsic::x86_avx_vtestc_pd:
12278 case Intrinsic::x86_avx_vtestc_ps_256:
12279 case Intrinsic::x86_avx_vtestc_pd_256:
12280 IsTestPacked = true; // Fallthrough
12281 case Intrinsic::x86_sse41_ptestc:
12282 case Intrinsic::x86_avx_ptestc_256:
12284 X86CC = X86::COND_B;
12286 case Intrinsic::x86_avx_vtestnzc_ps:
12287 case Intrinsic::x86_avx_vtestnzc_pd:
12288 case Intrinsic::x86_avx_vtestnzc_ps_256:
12289 case Intrinsic::x86_avx_vtestnzc_pd_256:
12290 IsTestPacked = true; // Fallthrough
12291 case Intrinsic::x86_sse41_ptestnzc:
12292 case Intrinsic::x86_avx_ptestnzc_256:
12294 X86CC = X86::COND_A;
12298 SDValue LHS = Op.getOperand(1);
12299 SDValue RHS = Op.getOperand(2);
12300 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12301 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12302 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12303 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12304 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12306 case Intrinsic::x86_avx512_kortestz_w:
12307 case Intrinsic::x86_avx512_kortestc_w: {
12308 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12309 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12310 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12311 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12312 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12313 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12314 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12317 // SSE/AVX shift intrinsics
12318 case Intrinsic::x86_sse2_psll_w:
12319 case Intrinsic::x86_sse2_psll_d:
12320 case Intrinsic::x86_sse2_psll_q:
12321 case Intrinsic::x86_avx2_psll_w:
12322 case Intrinsic::x86_avx2_psll_d:
12323 case Intrinsic::x86_avx2_psll_q:
12324 case Intrinsic::x86_sse2_psrl_w:
12325 case Intrinsic::x86_sse2_psrl_d:
12326 case Intrinsic::x86_sse2_psrl_q:
12327 case Intrinsic::x86_avx2_psrl_w:
12328 case Intrinsic::x86_avx2_psrl_d:
12329 case Intrinsic::x86_avx2_psrl_q:
12330 case Intrinsic::x86_sse2_psra_w:
12331 case Intrinsic::x86_sse2_psra_d:
12332 case Intrinsic::x86_avx2_psra_w:
12333 case Intrinsic::x86_avx2_psra_d: {
12336 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12337 case Intrinsic::x86_sse2_psll_w:
12338 case Intrinsic::x86_sse2_psll_d:
12339 case Intrinsic::x86_sse2_psll_q:
12340 case Intrinsic::x86_avx2_psll_w:
12341 case Intrinsic::x86_avx2_psll_d:
12342 case Intrinsic::x86_avx2_psll_q:
12343 Opcode = X86ISD::VSHL;
12345 case Intrinsic::x86_sse2_psrl_w:
12346 case Intrinsic::x86_sse2_psrl_d:
12347 case Intrinsic::x86_sse2_psrl_q:
12348 case Intrinsic::x86_avx2_psrl_w:
12349 case Intrinsic::x86_avx2_psrl_d:
12350 case Intrinsic::x86_avx2_psrl_q:
12351 Opcode = X86ISD::VSRL;
12353 case Intrinsic::x86_sse2_psra_w:
12354 case Intrinsic::x86_sse2_psra_d:
12355 case Intrinsic::x86_avx2_psra_w:
12356 case Intrinsic::x86_avx2_psra_d:
12357 Opcode = X86ISD::VSRA;
12360 return DAG.getNode(Opcode, dl, Op.getValueType(),
12361 Op.getOperand(1), Op.getOperand(2));
12364 // SSE/AVX immediate shift intrinsics
12365 case Intrinsic::x86_sse2_pslli_w:
12366 case Intrinsic::x86_sse2_pslli_d:
12367 case Intrinsic::x86_sse2_pslli_q:
12368 case Intrinsic::x86_avx2_pslli_w:
12369 case Intrinsic::x86_avx2_pslli_d:
12370 case Intrinsic::x86_avx2_pslli_q:
12371 case Intrinsic::x86_sse2_psrli_w:
12372 case Intrinsic::x86_sse2_psrli_d:
12373 case Intrinsic::x86_sse2_psrli_q:
12374 case Intrinsic::x86_avx2_psrli_w:
12375 case Intrinsic::x86_avx2_psrli_d:
12376 case Intrinsic::x86_avx2_psrli_q:
12377 case Intrinsic::x86_sse2_psrai_w:
12378 case Intrinsic::x86_sse2_psrai_d:
12379 case Intrinsic::x86_avx2_psrai_w:
12380 case Intrinsic::x86_avx2_psrai_d: {
12383 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12384 case Intrinsic::x86_sse2_pslli_w:
12385 case Intrinsic::x86_sse2_pslli_d:
12386 case Intrinsic::x86_sse2_pslli_q:
12387 case Intrinsic::x86_avx2_pslli_w:
12388 case Intrinsic::x86_avx2_pslli_d:
12389 case Intrinsic::x86_avx2_pslli_q:
12390 Opcode = X86ISD::VSHLI;
12392 case Intrinsic::x86_sse2_psrli_w:
12393 case Intrinsic::x86_sse2_psrli_d:
12394 case Intrinsic::x86_sse2_psrli_q:
12395 case Intrinsic::x86_avx2_psrli_w:
12396 case Intrinsic::x86_avx2_psrli_d:
12397 case Intrinsic::x86_avx2_psrli_q:
12398 Opcode = X86ISD::VSRLI;
12400 case Intrinsic::x86_sse2_psrai_w:
12401 case Intrinsic::x86_sse2_psrai_d:
12402 case Intrinsic::x86_avx2_psrai_w:
12403 case Intrinsic::x86_avx2_psrai_d:
12404 Opcode = X86ISD::VSRAI;
12407 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12408 Op.getOperand(1), Op.getOperand(2), DAG);
12411 case Intrinsic::x86_sse42_pcmpistria128:
12412 case Intrinsic::x86_sse42_pcmpestria128:
12413 case Intrinsic::x86_sse42_pcmpistric128:
12414 case Intrinsic::x86_sse42_pcmpestric128:
12415 case Intrinsic::x86_sse42_pcmpistrio128:
12416 case Intrinsic::x86_sse42_pcmpestrio128:
12417 case Intrinsic::x86_sse42_pcmpistris128:
12418 case Intrinsic::x86_sse42_pcmpestris128:
12419 case Intrinsic::x86_sse42_pcmpistriz128:
12420 case Intrinsic::x86_sse42_pcmpestriz128: {
12424 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12425 case Intrinsic::x86_sse42_pcmpistria128:
12426 Opcode = X86ISD::PCMPISTRI;
12427 X86CC = X86::COND_A;
12429 case Intrinsic::x86_sse42_pcmpestria128:
12430 Opcode = X86ISD::PCMPESTRI;
12431 X86CC = X86::COND_A;
12433 case Intrinsic::x86_sse42_pcmpistric128:
12434 Opcode = X86ISD::PCMPISTRI;
12435 X86CC = X86::COND_B;
12437 case Intrinsic::x86_sse42_pcmpestric128:
12438 Opcode = X86ISD::PCMPESTRI;
12439 X86CC = X86::COND_B;
12441 case Intrinsic::x86_sse42_pcmpistrio128:
12442 Opcode = X86ISD::PCMPISTRI;
12443 X86CC = X86::COND_O;
12445 case Intrinsic::x86_sse42_pcmpestrio128:
12446 Opcode = X86ISD::PCMPESTRI;
12447 X86CC = X86::COND_O;
12449 case Intrinsic::x86_sse42_pcmpistris128:
12450 Opcode = X86ISD::PCMPISTRI;
12451 X86CC = X86::COND_S;
12453 case Intrinsic::x86_sse42_pcmpestris128:
12454 Opcode = X86ISD::PCMPESTRI;
12455 X86CC = X86::COND_S;
12457 case Intrinsic::x86_sse42_pcmpistriz128:
12458 Opcode = X86ISD::PCMPISTRI;
12459 X86CC = X86::COND_E;
12461 case Intrinsic::x86_sse42_pcmpestriz128:
12462 Opcode = X86ISD::PCMPESTRI;
12463 X86CC = X86::COND_E;
12466 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12467 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12468 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12469 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12470 DAG.getConstant(X86CC, MVT::i8),
12471 SDValue(PCMP.getNode(), 1));
12472 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12475 case Intrinsic::x86_sse42_pcmpistri128:
12476 case Intrinsic::x86_sse42_pcmpestri128: {
12478 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12479 Opcode = X86ISD::PCMPISTRI;
12481 Opcode = X86ISD::PCMPESTRI;
12483 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12484 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12485 return DAG.getNode(Opcode, dl, VTs, NewOps);
12487 case Intrinsic::x86_fma_vfmadd_ps:
12488 case Intrinsic::x86_fma_vfmadd_pd:
12489 case Intrinsic::x86_fma_vfmsub_ps:
12490 case Intrinsic::x86_fma_vfmsub_pd:
12491 case Intrinsic::x86_fma_vfnmadd_ps:
12492 case Intrinsic::x86_fma_vfnmadd_pd:
12493 case Intrinsic::x86_fma_vfnmsub_ps:
12494 case Intrinsic::x86_fma_vfnmsub_pd:
12495 case Intrinsic::x86_fma_vfmaddsub_ps:
12496 case Intrinsic::x86_fma_vfmaddsub_pd:
12497 case Intrinsic::x86_fma_vfmsubadd_ps:
12498 case Intrinsic::x86_fma_vfmsubadd_pd:
12499 case Intrinsic::x86_fma_vfmadd_ps_256:
12500 case Intrinsic::x86_fma_vfmadd_pd_256:
12501 case Intrinsic::x86_fma_vfmsub_ps_256:
12502 case Intrinsic::x86_fma_vfmsub_pd_256:
12503 case Intrinsic::x86_fma_vfnmadd_ps_256:
12504 case Intrinsic::x86_fma_vfnmadd_pd_256:
12505 case Intrinsic::x86_fma_vfnmsub_ps_256:
12506 case Intrinsic::x86_fma_vfnmsub_pd_256:
12507 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12508 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12509 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12510 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12511 case Intrinsic::x86_fma_vfmadd_ps_512:
12512 case Intrinsic::x86_fma_vfmadd_pd_512:
12513 case Intrinsic::x86_fma_vfmsub_ps_512:
12514 case Intrinsic::x86_fma_vfmsub_pd_512:
12515 case Intrinsic::x86_fma_vfnmadd_ps_512:
12516 case Intrinsic::x86_fma_vfnmadd_pd_512:
12517 case Intrinsic::x86_fma_vfnmsub_ps_512:
12518 case Intrinsic::x86_fma_vfnmsub_pd_512:
12519 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12520 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12521 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12522 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12525 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12526 case Intrinsic::x86_fma_vfmadd_ps:
12527 case Intrinsic::x86_fma_vfmadd_pd:
12528 case Intrinsic::x86_fma_vfmadd_ps_256:
12529 case Intrinsic::x86_fma_vfmadd_pd_256:
12530 case Intrinsic::x86_fma_vfmadd_ps_512:
12531 case Intrinsic::x86_fma_vfmadd_pd_512:
12532 Opc = X86ISD::FMADD;
12534 case Intrinsic::x86_fma_vfmsub_ps:
12535 case Intrinsic::x86_fma_vfmsub_pd:
12536 case Intrinsic::x86_fma_vfmsub_ps_256:
12537 case Intrinsic::x86_fma_vfmsub_pd_256:
12538 case Intrinsic::x86_fma_vfmsub_ps_512:
12539 case Intrinsic::x86_fma_vfmsub_pd_512:
12540 Opc = X86ISD::FMSUB;
12542 case Intrinsic::x86_fma_vfnmadd_ps:
12543 case Intrinsic::x86_fma_vfnmadd_pd:
12544 case Intrinsic::x86_fma_vfnmadd_ps_256:
12545 case Intrinsic::x86_fma_vfnmadd_pd_256:
12546 case Intrinsic::x86_fma_vfnmadd_ps_512:
12547 case Intrinsic::x86_fma_vfnmadd_pd_512:
12548 Opc = X86ISD::FNMADD;
12550 case Intrinsic::x86_fma_vfnmsub_ps:
12551 case Intrinsic::x86_fma_vfnmsub_pd:
12552 case Intrinsic::x86_fma_vfnmsub_ps_256:
12553 case Intrinsic::x86_fma_vfnmsub_pd_256:
12554 case Intrinsic::x86_fma_vfnmsub_ps_512:
12555 case Intrinsic::x86_fma_vfnmsub_pd_512:
12556 Opc = X86ISD::FNMSUB;
12558 case Intrinsic::x86_fma_vfmaddsub_ps:
12559 case Intrinsic::x86_fma_vfmaddsub_pd:
12560 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12561 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12562 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12563 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12564 Opc = X86ISD::FMADDSUB;
12566 case Intrinsic::x86_fma_vfmsubadd_ps:
12567 case Intrinsic::x86_fma_vfmsubadd_pd:
12568 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12569 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12570 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12571 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12572 Opc = X86ISD::FMSUBADD;
12576 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12577 Op.getOperand(2), Op.getOperand(3));
12582 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12583 SDValue Src, SDValue Mask, SDValue Base,
12584 SDValue Index, SDValue ScaleOp, SDValue Chain,
12585 const X86Subtarget * Subtarget) {
12587 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12588 assert(C && "Invalid scale type");
12589 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12590 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12591 Index.getSimpleValueType().getVectorNumElements());
12593 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12595 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12597 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12598 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12599 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12600 SDValue Segment = DAG.getRegister(0, MVT::i32);
12601 if (Src.getOpcode() == ISD::UNDEF)
12602 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12603 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12604 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12605 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12606 return DAG.getMergeValues(RetOps, dl);
12609 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12610 SDValue Src, SDValue Mask, SDValue Base,
12611 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12613 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12614 assert(C && "Invalid scale type");
12615 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12616 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12617 SDValue Segment = DAG.getRegister(0, MVT::i32);
12618 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12619 Index.getSimpleValueType().getVectorNumElements());
12621 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12623 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12625 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12626 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12627 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12628 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12629 return SDValue(Res, 1);
12632 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12633 SDValue Mask, SDValue Base, SDValue Index,
12634 SDValue ScaleOp, SDValue Chain) {
12636 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12637 assert(C && "Invalid scale type");
12638 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12639 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12640 SDValue Segment = DAG.getRegister(0, MVT::i32);
12642 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12644 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12646 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12648 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12649 //SDVTList VTs = DAG.getVTList(MVT::Other);
12650 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12651 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12652 return SDValue(Res, 0);
12655 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12656 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12657 // also used to custom lower READCYCLECOUNTER nodes.
12658 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12659 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12660 SmallVectorImpl<SDValue> &Results) {
12661 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12662 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12665 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12666 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12667 // and the EAX register is loaded with the low-order 32 bits.
12668 if (Subtarget->is64Bit()) {
12669 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12670 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12673 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12674 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12677 SDValue Chain = HI.getValue(1);
12679 if (Opcode == X86ISD::RDTSCP_DAG) {
12680 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12682 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12683 // the ECX register. Add 'ecx' explicitly to the chain.
12684 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12686 // Explicitly store the content of ECX at the location passed in input
12687 // to the 'rdtscp' intrinsic.
12688 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12689 MachinePointerInfo(), false, false, 0);
12692 if (Subtarget->is64Bit()) {
12693 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12694 // the EAX register is loaded with the low-order 32 bits.
12695 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12696 DAG.getConstant(32, MVT::i8));
12697 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12698 Results.push_back(Chain);
12702 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12703 SDValue Ops[] = { LO, HI };
12704 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12705 Results.push_back(Pair);
12706 Results.push_back(Chain);
12709 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12710 SelectionDAG &DAG) {
12711 SmallVector<SDValue, 2> Results;
12713 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12715 return DAG.getMergeValues(Results, DL);
12718 enum IntrinsicType {
12719 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12722 struct IntrinsicData {
12723 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12724 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12725 IntrinsicType Type;
12730 std::map < unsigned, IntrinsicData> IntrMap;
12731 static void InitIntinsicsMap() {
12732 static bool Initialized = false;
12735 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12736 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12737 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12738 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12739 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12740 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12741 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12742 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12743 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12744 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12745 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
12746 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12747 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
12748 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12749 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
12750 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12751 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
12752 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12754 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12755 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12756 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
12757 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12758 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
12759 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12760 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
12761 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12762 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
12763 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12764 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
12765 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12766 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
12767 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12768 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
12769 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12771 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
12772 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12773 X86::VGATHERPF1QPSm)));
12774 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
12775 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12776 X86::VGATHERPF1QPDm)));
12777 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
12778 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12779 X86::VGATHERPF1DPDm)));
12780 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
12781 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12782 X86::VGATHERPF1DPSm)));
12783 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
12784 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12785 X86::VSCATTERPF1QPSm)));
12786 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
12787 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12788 X86::VSCATTERPF1QPDm)));
12789 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
12790 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12791 X86::VSCATTERPF1DPDm)));
12792 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
12793 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12794 X86::VSCATTERPF1DPSm)));
12795 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12796 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12797 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12798 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12799 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12800 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12801 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12802 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12803 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12804 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12805 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12806 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12807 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12808 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
12809 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12810 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
12811 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12812 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
12813 Initialized = true;
12816 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12817 SelectionDAG &DAG) {
12818 InitIntinsicsMap();
12819 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12820 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12821 if (itr == IntrMap.end())
12825 IntrinsicData Intr = itr->second;
12826 switch(Intr.Type) {
12829 // Emit the node with the right value type.
12830 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12831 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12833 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12834 // Otherwise return the value from Rand, which is always 0, casted to i32.
12835 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12836 DAG.getConstant(1, Op->getValueType(1)),
12837 DAG.getConstant(X86::COND_B, MVT::i32),
12838 SDValue(Result.getNode(), 1) };
12839 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12840 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12843 // Return { result, isValid, chain }.
12844 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12845 SDValue(Result.getNode(), 2));
12848 //gather(v1, mask, index, base, scale);
12849 SDValue Chain = Op.getOperand(0);
12850 SDValue Src = Op.getOperand(2);
12851 SDValue Base = Op.getOperand(3);
12852 SDValue Index = Op.getOperand(4);
12853 SDValue Mask = Op.getOperand(5);
12854 SDValue Scale = Op.getOperand(6);
12855 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12859 //scatter(base, mask, index, v1, scale);
12860 SDValue Chain = Op.getOperand(0);
12861 SDValue Base = Op.getOperand(2);
12862 SDValue Mask = Op.getOperand(3);
12863 SDValue Index = Op.getOperand(4);
12864 SDValue Src = Op.getOperand(5);
12865 SDValue Scale = Op.getOperand(6);
12866 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12869 SDValue Hint = Op.getOperand(6);
12871 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
12872 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12873 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12874 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12875 SDValue Chain = Op.getOperand(0);
12876 SDValue Mask = Op.getOperand(2);
12877 SDValue Index = Op.getOperand(3);
12878 SDValue Base = Op.getOperand(4);
12879 SDValue Scale = Op.getOperand(5);
12880 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12882 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12884 SmallVector<SDValue, 2> Results;
12885 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12886 return DAG.getMergeValues(Results, dl);
12888 // XTEST intrinsics.
12890 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12891 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12892 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12893 DAG.getConstant(X86::COND_NE, MVT::i8),
12895 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12896 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12897 Ret, SDValue(InTrans.getNode(), 1));
12900 llvm_unreachable("Unknown Intrinsic Type");
12903 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12904 SelectionDAG &DAG) const {
12905 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12906 MFI->setReturnAddressIsTaken(true);
12908 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12911 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12913 EVT PtrVT = getPointerTy();
12916 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12917 const X86RegisterInfo *RegInfo =
12918 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12919 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12920 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12921 DAG.getNode(ISD::ADD, dl, PtrVT,
12922 FrameAddr, Offset),
12923 MachinePointerInfo(), false, false, false, 0);
12926 // Just load the return address.
12927 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12928 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12929 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12932 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12933 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12934 MFI->setFrameAddressIsTaken(true);
12936 EVT VT = Op.getValueType();
12937 SDLoc dl(Op); // FIXME probably not meaningful
12938 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12939 const X86RegisterInfo *RegInfo =
12940 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12941 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12942 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12943 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12944 "Invalid Frame Register!");
12945 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12947 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12948 MachinePointerInfo(),
12949 false, false, false, 0);
12953 // FIXME? Maybe this could be a TableGen attribute on some registers and
12954 // this table could be generated automatically from RegInfo.
12955 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
12957 unsigned Reg = StringSwitch<unsigned>(RegName)
12958 .Case("esp", X86::ESP)
12959 .Case("rsp", X86::RSP)
12963 report_fatal_error("Invalid register name global variable");
12966 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12967 SelectionDAG &DAG) const {
12968 const X86RegisterInfo *RegInfo =
12969 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12970 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12973 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12974 SDValue Chain = Op.getOperand(0);
12975 SDValue Offset = Op.getOperand(1);
12976 SDValue Handler = Op.getOperand(2);
12979 EVT PtrVT = getPointerTy();
12980 const X86RegisterInfo *RegInfo =
12981 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12982 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12983 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12984 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12985 "Invalid Frame Register!");
12986 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12987 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12989 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12990 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12991 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12992 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12994 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12996 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12997 DAG.getRegister(StoreAddrReg, PtrVT));
13000 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13001 SelectionDAG &DAG) const {
13003 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13004 DAG.getVTList(MVT::i32, MVT::Other),
13005 Op.getOperand(0), Op.getOperand(1));
13008 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13009 SelectionDAG &DAG) const {
13011 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13012 Op.getOperand(0), Op.getOperand(1));
13015 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13016 return Op.getOperand(0);
13019 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13020 SelectionDAG &DAG) const {
13021 SDValue Root = Op.getOperand(0);
13022 SDValue Trmp = Op.getOperand(1); // trampoline
13023 SDValue FPtr = Op.getOperand(2); // nested function
13024 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13027 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13028 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13030 if (Subtarget->is64Bit()) {
13031 SDValue OutChains[6];
13033 // Large code-model.
13034 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
13035 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13037 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13038 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13040 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13042 // Load the pointer to the nested function into R11.
13043 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13044 SDValue Addr = Trmp;
13045 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13046 Addr, MachinePointerInfo(TrmpAddr),
13049 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13050 DAG.getConstant(2, MVT::i64));
13051 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13052 MachinePointerInfo(TrmpAddr, 2),
13055 // Load the 'nest' parameter value into R10.
13056 // R10 is specified in X86CallingConv.td
13057 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13058 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13059 DAG.getConstant(10, MVT::i64));
13060 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13061 Addr, MachinePointerInfo(TrmpAddr, 10),
13064 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13065 DAG.getConstant(12, MVT::i64));
13066 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13067 MachinePointerInfo(TrmpAddr, 12),
13070 // Jump to the nested function.
13071 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13072 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13073 DAG.getConstant(20, MVT::i64));
13074 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13075 Addr, MachinePointerInfo(TrmpAddr, 20),
13078 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13079 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13080 DAG.getConstant(22, MVT::i64));
13081 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13082 MachinePointerInfo(TrmpAddr, 22),
13085 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13087 const Function *Func =
13088 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13089 CallingConv::ID CC = Func->getCallingConv();
13094 llvm_unreachable("Unsupported calling convention");
13095 case CallingConv::C:
13096 case CallingConv::X86_StdCall: {
13097 // Pass 'nest' parameter in ECX.
13098 // Must be kept in sync with X86CallingConv.td
13099 NestReg = X86::ECX;
13101 // Check that ECX wasn't needed by an 'inreg' parameter.
13102 FunctionType *FTy = Func->getFunctionType();
13103 const AttributeSet &Attrs = Func->getAttributes();
13105 if (!Attrs.isEmpty() && !Func->isVarArg()) {
13106 unsigned InRegCount = 0;
13109 for (FunctionType::param_iterator I = FTy->param_begin(),
13110 E = FTy->param_end(); I != E; ++I, ++Idx)
13111 if (Attrs.hasAttribute(Idx, Attribute::InReg))
13112 // FIXME: should only count parameters that are lowered to integers.
13113 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13115 if (InRegCount > 2) {
13116 report_fatal_error("Nest register in use - reduce number of inreg"
13122 case CallingConv::X86_FastCall:
13123 case CallingConv::X86_ThisCall:
13124 case CallingConv::Fast:
13125 // Pass 'nest' parameter in EAX.
13126 // Must be kept in sync with X86CallingConv.td
13127 NestReg = X86::EAX;
13131 SDValue OutChains[4];
13132 SDValue Addr, Disp;
13134 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13135 DAG.getConstant(10, MVT::i32));
13136 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13138 // This is storing the opcode for MOV32ri.
13139 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13140 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13141 OutChains[0] = DAG.getStore(Root, dl,
13142 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13143 Trmp, MachinePointerInfo(TrmpAddr),
13146 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13147 DAG.getConstant(1, MVT::i32));
13148 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13149 MachinePointerInfo(TrmpAddr, 1),
13152 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13153 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13154 DAG.getConstant(5, MVT::i32));
13155 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13156 MachinePointerInfo(TrmpAddr, 5),
13159 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13160 DAG.getConstant(6, MVT::i32));
13161 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13162 MachinePointerInfo(TrmpAddr, 6),
13165 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13169 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13170 SelectionDAG &DAG) const {
13172 The rounding mode is in bits 11:10 of FPSR, and has the following
13174 00 Round to nearest
13179 FLT_ROUNDS, on the other hand, expects the following:
13186 To perform the conversion, we do:
13187 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13190 MachineFunction &MF = DAG.getMachineFunction();
13191 const TargetMachine &TM = MF.getTarget();
13192 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13193 unsigned StackAlignment = TFI.getStackAlignment();
13194 MVT VT = Op.getSimpleValueType();
13197 // Save FP Control Word to stack slot
13198 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13199 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13201 MachineMemOperand *MMO =
13202 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13203 MachineMemOperand::MOStore, 2, 2);
13205 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13206 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13207 DAG.getVTList(MVT::Other),
13208 Ops, MVT::i16, MMO);
13210 // Load FP Control Word from stack slot
13211 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13212 MachinePointerInfo(), false, false, false, 0);
13214 // Transform as necessary
13216 DAG.getNode(ISD::SRL, DL, MVT::i16,
13217 DAG.getNode(ISD::AND, DL, MVT::i16,
13218 CWD, DAG.getConstant(0x800, MVT::i16)),
13219 DAG.getConstant(11, MVT::i8));
13221 DAG.getNode(ISD::SRL, DL, MVT::i16,
13222 DAG.getNode(ISD::AND, DL, MVT::i16,
13223 CWD, DAG.getConstant(0x400, MVT::i16)),
13224 DAG.getConstant(9, MVT::i8));
13227 DAG.getNode(ISD::AND, DL, MVT::i16,
13228 DAG.getNode(ISD::ADD, DL, MVT::i16,
13229 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13230 DAG.getConstant(1, MVT::i16)),
13231 DAG.getConstant(3, MVT::i16));
13233 return DAG.getNode((VT.getSizeInBits() < 16 ?
13234 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13237 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13238 MVT VT = Op.getSimpleValueType();
13240 unsigned NumBits = VT.getSizeInBits();
13243 Op = Op.getOperand(0);
13244 if (VT == MVT::i8) {
13245 // Zero extend to i32 since there is not an i8 bsr.
13247 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13250 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13251 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13252 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13254 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13257 DAG.getConstant(NumBits+NumBits-1, OpVT),
13258 DAG.getConstant(X86::COND_E, MVT::i8),
13261 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13263 // Finally xor with NumBits-1.
13264 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13267 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13271 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13272 MVT VT = Op.getSimpleValueType();
13274 unsigned NumBits = VT.getSizeInBits();
13277 Op = Op.getOperand(0);
13278 if (VT == MVT::i8) {
13279 // Zero extend to i32 since there is not an i8 bsr.
13281 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13284 // Issue a bsr (scan bits in reverse).
13285 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13286 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13288 // And xor with NumBits-1.
13289 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13292 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13296 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13297 MVT VT = Op.getSimpleValueType();
13298 unsigned NumBits = VT.getSizeInBits();
13300 Op = Op.getOperand(0);
13302 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13303 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13304 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13306 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13309 DAG.getConstant(NumBits, VT),
13310 DAG.getConstant(X86::COND_E, MVT::i8),
13313 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13316 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13317 // ones, and then concatenate the result back.
13318 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13319 MVT VT = Op.getSimpleValueType();
13321 assert(VT.is256BitVector() && VT.isInteger() &&
13322 "Unsupported value type for operation");
13324 unsigned NumElems = VT.getVectorNumElements();
13327 // Extract the LHS vectors
13328 SDValue LHS = Op.getOperand(0);
13329 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13330 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13332 // Extract the RHS vectors
13333 SDValue RHS = Op.getOperand(1);
13334 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13335 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13337 MVT EltVT = VT.getVectorElementType();
13338 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13340 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13341 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13342 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13345 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13346 assert(Op.getSimpleValueType().is256BitVector() &&
13347 Op.getSimpleValueType().isInteger() &&
13348 "Only handle AVX 256-bit vector integer operation");
13349 return Lower256IntArith(Op, DAG);
13352 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13353 assert(Op.getSimpleValueType().is256BitVector() &&
13354 Op.getSimpleValueType().isInteger() &&
13355 "Only handle AVX 256-bit vector integer operation");
13356 return Lower256IntArith(Op, DAG);
13359 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13360 SelectionDAG &DAG) {
13362 MVT VT = Op.getSimpleValueType();
13364 // Decompose 256-bit ops into smaller 128-bit ops.
13365 if (VT.is256BitVector() && !Subtarget->hasInt256())
13366 return Lower256IntArith(Op, DAG);
13368 SDValue A = Op.getOperand(0);
13369 SDValue B = Op.getOperand(1);
13371 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13372 if (VT == MVT::v4i32) {
13373 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13374 "Should not custom lower when pmuldq is available!");
13376 // Extract the odd parts.
13377 static const int UnpackMask[] = { 1, -1, 3, -1 };
13378 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13379 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13381 // Multiply the even parts.
13382 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13383 // Now multiply odd parts.
13384 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13386 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13387 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13389 // Merge the two vectors back together with a shuffle. This expands into 2
13391 static const int ShufMask[] = { 0, 4, 2, 6 };
13392 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13395 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13396 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13398 // Ahi = psrlqi(a, 32);
13399 // Bhi = psrlqi(b, 32);
13401 // AloBlo = pmuludq(a, b);
13402 // AloBhi = pmuludq(a, Bhi);
13403 // AhiBlo = pmuludq(Ahi, b);
13405 // AloBhi = psllqi(AloBhi, 32);
13406 // AhiBlo = psllqi(AhiBlo, 32);
13407 // return AloBlo + AloBhi + AhiBlo;
13409 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13410 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13412 // Bit cast to 32-bit vectors for MULUDQ
13413 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13414 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13415 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13416 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13417 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13418 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13420 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13421 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13422 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13424 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13425 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13427 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13428 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13431 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13432 assert(Subtarget->isTargetWin64() && "Unexpected target");
13433 EVT VT = Op.getValueType();
13434 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13435 "Unexpected return type for lowering");
13439 switch (Op->getOpcode()) {
13440 default: llvm_unreachable("Unexpected request for libcall!");
13441 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13442 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13443 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13444 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13445 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13446 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13450 SDValue InChain = DAG.getEntryNode();
13452 TargetLowering::ArgListTy Args;
13453 TargetLowering::ArgListEntry Entry;
13454 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13455 EVT ArgVT = Op->getOperand(i).getValueType();
13456 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13457 "Unexpected argument type for lowering");
13458 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13459 Entry.Node = StackPtr;
13460 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13462 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13463 Entry.Ty = PointerType::get(ArgTy,0);
13464 Entry.isSExt = false;
13465 Entry.isZExt = false;
13466 Args.push_back(Entry);
13469 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13472 TargetLowering::CallLoweringInfo CLI(DAG);
13473 CLI.setDebugLoc(dl).setChain(InChain)
13474 .setCallee(getLibcallCallingConv(LC),
13475 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13477 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13479 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13480 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13483 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13484 SelectionDAG &DAG) {
13485 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13486 EVT VT = Op0.getValueType();
13489 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13490 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13492 // Get the high parts.
13493 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13494 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13495 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13497 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13499 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13500 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13502 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13503 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13504 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13505 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13506 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13508 // Shuffle it back into the right order.
13509 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13510 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13511 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13512 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13514 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13515 // unsigned multiply.
13516 if (IsSigned && !Subtarget->hasSSE41()) {
13518 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13519 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13520 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13521 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13522 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13524 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13525 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13528 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13531 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13532 const X86Subtarget *Subtarget) {
13533 MVT VT = Op.getSimpleValueType();
13535 SDValue R = Op.getOperand(0);
13536 SDValue Amt = Op.getOperand(1);
13538 // Optimize shl/srl/sra with constant shift amount.
13539 if (isSplatVector(Amt.getNode())) {
13540 SDValue SclrAmt = Amt->getOperand(0);
13541 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13542 uint64_t ShiftAmt = C->getZExtValue();
13544 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13545 (Subtarget->hasInt256() &&
13546 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13547 (Subtarget->hasAVX512() &&
13548 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13549 if (Op.getOpcode() == ISD::SHL)
13550 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13552 if (Op.getOpcode() == ISD::SRL)
13553 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13555 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13556 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13560 if (VT == MVT::v16i8) {
13561 if (Op.getOpcode() == ISD::SHL) {
13562 // Make a large shift.
13563 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13564 MVT::v8i16, R, ShiftAmt,
13566 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13567 // Zero out the rightmost bits.
13568 SmallVector<SDValue, 16> V(16,
13569 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13571 return DAG.getNode(ISD::AND, dl, VT, SHL,
13572 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13574 if (Op.getOpcode() == ISD::SRL) {
13575 // Make a large shift.
13576 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13577 MVT::v8i16, R, ShiftAmt,
13579 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13580 // Zero out the leftmost bits.
13581 SmallVector<SDValue, 16> V(16,
13582 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13584 return DAG.getNode(ISD::AND, dl, VT, SRL,
13585 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13587 if (Op.getOpcode() == ISD::SRA) {
13588 if (ShiftAmt == 7) {
13589 // R s>> 7 === R s< 0
13590 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13591 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13594 // R s>> a === ((R u>> a) ^ m) - m
13595 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13596 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13598 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13599 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13600 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13603 llvm_unreachable("Unknown shift opcode.");
13606 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13607 if (Op.getOpcode() == ISD::SHL) {
13608 // Make a large shift.
13609 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13610 MVT::v16i16, R, ShiftAmt,
13612 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13613 // Zero out the rightmost bits.
13614 SmallVector<SDValue, 32> V(32,
13615 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13617 return DAG.getNode(ISD::AND, dl, VT, SHL,
13618 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13620 if (Op.getOpcode() == ISD::SRL) {
13621 // Make a large shift.
13622 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13623 MVT::v16i16, R, ShiftAmt,
13625 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13626 // Zero out the leftmost bits.
13627 SmallVector<SDValue, 32> V(32,
13628 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13630 return DAG.getNode(ISD::AND, dl, VT, SRL,
13631 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13633 if (Op.getOpcode() == ISD::SRA) {
13634 if (ShiftAmt == 7) {
13635 // R s>> 7 === R s< 0
13636 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13637 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13640 // R s>> a === ((R u>> a) ^ m) - m
13641 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13642 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13644 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13645 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13646 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13649 llvm_unreachable("Unknown shift opcode.");
13654 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13655 if (!Subtarget->is64Bit() &&
13656 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13657 Amt.getOpcode() == ISD::BITCAST &&
13658 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13659 Amt = Amt.getOperand(0);
13660 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13661 VT.getVectorNumElements();
13662 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13663 uint64_t ShiftAmt = 0;
13664 for (unsigned i = 0; i != Ratio; ++i) {
13665 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13669 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13671 // Check remaining shift amounts.
13672 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13673 uint64_t ShAmt = 0;
13674 for (unsigned j = 0; j != Ratio; ++j) {
13675 ConstantSDNode *C =
13676 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13680 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13682 if (ShAmt != ShiftAmt)
13685 switch (Op.getOpcode()) {
13687 llvm_unreachable("Unknown shift opcode!");
13689 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13692 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13695 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13703 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13704 const X86Subtarget* Subtarget) {
13705 MVT VT = Op.getSimpleValueType();
13707 SDValue R = Op.getOperand(0);
13708 SDValue Amt = Op.getOperand(1);
13710 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13711 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13712 (Subtarget->hasInt256() &&
13713 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13714 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13715 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13717 EVT EltVT = VT.getVectorElementType();
13719 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13720 unsigned NumElts = VT.getVectorNumElements();
13722 for (i = 0; i != NumElts; ++i) {
13723 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13727 for (j = i; j != NumElts; ++j) {
13728 SDValue Arg = Amt.getOperand(j);
13729 if (Arg.getOpcode() == ISD::UNDEF) continue;
13730 if (Arg != Amt.getOperand(i))
13733 if (i != NumElts && j == NumElts)
13734 BaseShAmt = Amt.getOperand(i);
13736 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13737 Amt = Amt.getOperand(0);
13738 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13739 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13740 SDValue InVec = Amt.getOperand(0);
13741 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13742 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13744 for (; i != NumElts; ++i) {
13745 SDValue Arg = InVec.getOperand(i);
13746 if (Arg.getOpcode() == ISD::UNDEF) continue;
13750 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13751 if (ConstantSDNode *C =
13752 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13753 unsigned SplatIdx =
13754 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13755 if (C->getZExtValue() == SplatIdx)
13756 BaseShAmt = InVec.getOperand(1);
13759 if (!BaseShAmt.getNode())
13760 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13761 DAG.getIntPtrConstant(0));
13765 if (BaseShAmt.getNode()) {
13766 if (EltVT.bitsGT(MVT::i32))
13767 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13768 else if (EltVT.bitsLT(MVT::i32))
13769 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13771 switch (Op.getOpcode()) {
13773 llvm_unreachable("Unknown shift opcode!");
13775 switch (VT.SimpleTy) {
13776 default: return SDValue();
13785 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13788 switch (VT.SimpleTy) {
13789 default: return SDValue();
13796 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13799 switch (VT.SimpleTy) {
13800 default: return SDValue();
13809 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13815 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13816 if (!Subtarget->is64Bit() &&
13817 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13818 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13819 Amt.getOpcode() == ISD::BITCAST &&
13820 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13821 Amt = Amt.getOperand(0);
13822 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13823 VT.getVectorNumElements();
13824 std::vector<SDValue> Vals(Ratio);
13825 for (unsigned i = 0; i != Ratio; ++i)
13826 Vals[i] = Amt.getOperand(i);
13827 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13828 for (unsigned j = 0; j != Ratio; ++j)
13829 if (Vals[j] != Amt.getOperand(i + j))
13832 switch (Op.getOpcode()) {
13834 llvm_unreachable("Unknown shift opcode!");
13836 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13838 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13840 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13847 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13848 SelectionDAG &DAG) {
13850 MVT VT = Op.getSimpleValueType();
13852 SDValue R = Op.getOperand(0);
13853 SDValue Amt = Op.getOperand(1);
13856 if (!Subtarget->hasSSE2())
13859 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13863 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13867 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13869 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13870 if (Subtarget->hasInt256()) {
13871 if (Op.getOpcode() == ISD::SRL &&
13872 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13873 VT == MVT::v4i64 || VT == MVT::v8i32))
13875 if (Op.getOpcode() == ISD::SHL &&
13876 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13877 VT == MVT::v4i64 || VT == MVT::v8i32))
13879 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13883 // If possible, lower this packed shift into a vector multiply instead of
13884 // expanding it into a sequence of scalar shifts.
13885 // Do this only if the vector shift count is a constant build_vector.
13886 if (Op.getOpcode() == ISD::SHL &&
13887 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13888 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13889 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13890 SmallVector<SDValue, 8> Elts;
13891 EVT SVT = VT.getScalarType();
13892 unsigned SVTBits = SVT.getSizeInBits();
13893 const APInt &One = APInt(SVTBits, 1);
13894 unsigned NumElems = VT.getVectorNumElements();
13896 for (unsigned i=0; i !=NumElems; ++i) {
13897 SDValue Op = Amt->getOperand(i);
13898 if (Op->getOpcode() == ISD::UNDEF) {
13899 Elts.push_back(Op);
13903 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13904 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13905 uint64_t ShAmt = C.getZExtValue();
13906 if (ShAmt >= SVTBits) {
13907 Elts.push_back(DAG.getUNDEF(SVT));
13910 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13912 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13913 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13916 // Lower SHL with variable shift amount.
13917 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13918 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13920 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13921 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13922 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13923 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13926 // If possible, lower this shift as a sequence of two shifts by
13927 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13929 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13931 // Could be rewritten as:
13932 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13934 // The advantage is that the two shifts from the example would be
13935 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13936 // the vector shift into four scalar shifts plus four pairs of vector
13938 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13939 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13940 unsigned TargetOpcode = X86ISD::MOVSS;
13941 bool CanBeSimplified;
13942 // The splat value for the first packed shift (the 'X' from the example).
13943 SDValue Amt1 = Amt->getOperand(0);
13944 // The splat value for the second packed shift (the 'Y' from the example).
13945 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13946 Amt->getOperand(2);
13948 // See if it is possible to replace this node with a sequence of
13949 // two shifts followed by a MOVSS/MOVSD
13950 if (VT == MVT::v4i32) {
13951 // Check if it is legal to use a MOVSS.
13952 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13953 Amt2 == Amt->getOperand(3);
13954 if (!CanBeSimplified) {
13955 // Otherwise, check if we can still simplify this node using a MOVSD.
13956 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13957 Amt->getOperand(2) == Amt->getOperand(3);
13958 TargetOpcode = X86ISD::MOVSD;
13959 Amt2 = Amt->getOperand(2);
13962 // Do similar checks for the case where the machine value type
13964 CanBeSimplified = Amt1 == Amt->getOperand(1);
13965 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13966 CanBeSimplified = Amt2 == Amt->getOperand(i);
13968 if (!CanBeSimplified) {
13969 TargetOpcode = X86ISD::MOVSD;
13970 CanBeSimplified = true;
13971 Amt2 = Amt->getOperand(4);
13972 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13973 CanBeSimplified = Amt1 == Amt->getOperand(i);
13974 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13975 CanBeSimplified = Amt2 == Amt->getOperand(j);
13979 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13980 isa<ConstantSDNode>(Amt2)) {
13981 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13982 EVT CastVT = MVT::v4i32;
13984 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13985 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13987 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13988 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13989 if (TargetOpcode == X86ISD::MOVSD)
13990 CastVT = MVT::v2i64;
13991 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13992 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13993 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13995 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13999 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14000 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14003 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14004 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14006 // Turn 'a' into a mask suitable for VSELECT
14007 SDValue VSelM = DAG.getConstant(0x80, VT);
14008 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14009 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14011 SDValue CM1 = DAG.getConstant(0x0f, VT);
14012 SDValue CM2 = DAG.getConstant(0x3f, VT);
14014 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14015 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14016 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14017 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14018 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14021 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14022 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14023 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14025 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14026 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14027 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14028 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14029 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14032 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14033 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14034 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14036 // return VSELECT(r, r+r, a);
14037 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14038 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14042 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14043 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14044 // solution better.
14045 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14046 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14048 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14049 R = DAG.getNode(ExtOpc, dl, NewVT, R);
14050 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14051 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14052 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14055 // Decompose 256-bit shifts into smaller 128-bit shifts.
14056 if (VT.is256BitVector()) {
14057 unsigned NumElems = VT.getVectorNumElements();
14058 MVT EltVT = VT.getVectorElementType();
14059 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14061 // Extract the two vectors
14062 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14063 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14065 // Recreate the shift amount vectors
14066 SDValue Amt1, Amt2;
14067 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14068 // Constant shift amount
14069 SmallVector<SDValue, 4> Amt1Csts;
14070 SmallVector<SDValue, 4> Amt2Csts;
14071 for (unsigned i = 0; i != NumElems/2; ++i)
14072 Amt1Csts.push_back(Amt->getOperand(i));
14073 for (unsigned i = NumElems/2; i != NumElems; ++i)
14074 Amt2Csts.push_back(Amt->getOperand(i));
14076 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14077 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14079 // Variable shift amount
14080 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14081 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14084 // Issue new vector shifts for the smaller types
14085 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14086 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14088 // Concatenate the result back
14089 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14095 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14096 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14097 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14098 // looks for this combo and may remove the "setcc" instruction if the "setcc"
14099 // has only one use.
14100 SDNode *N = Op.getNode();
14101 SDValue LHS = N->getOperand(0);
14102 SDValue RHS = N->getOperand(1);
14103 unsigned BaseOp = 0;
14106 switch (Op.getOpcode()) {
14107 default: llvm_unreachable("Unknown ovf instruction!");
14109 // A subtract of one will be selected as a INC. Note that INC doesn't
14110 // set CF, so we can't do this for UADDO.
14111 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14113 BaseOp = X86ISD::INC;
14114 Cond = X86::COND_O;
14117 BaseOp = X86ISD::ADD;
14118 Cond = X86::COND_O;
14121 BaseOp = X86ISD::ADD;
14122 Cond = X86::COND_B;
14125 // A subtract of one will be selected as a DEC. Note that DEC doesn't
14126 // set CF, so we can't do this for USUBO.
14127 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14129 BaseOp = X86ISD::DEC;
14130 Cond = X86::COND_O;
14133 BaseOp = X86ISD::SUB;
14134 Cond = X86::COND_O;
14137 BaseOp = X86ISD::SUB;
14138 Cond = X86::COND_B;
14141 BaseOp = X86ISD::SMUL;
14142 Cond = X86::COND_O;
14144 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14145 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14147 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14150 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14151 DAG.getConstant(X86::COND_O, MVT::i32),
14152 SDValue(Sum.getNode(), 2));
14154 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14158 // Also sets EFLAGS.
14159 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14160 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14163 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14164 DAG.getConstant(Cond, MVT::i32),
14165 SDValue(Sum.getNode(), 1));
14167 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14170 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14171 SelectionDAG &DAG) const {
14173 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14174 MVT VT = Op.getSimpleValueType();
14176 if (!Subtarget->hasSSE2() || !VT.isVector())
14179 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14180 ExtraVT.getScalarType().getSizeInBits();
14182 switch (VT.SimpleTy) {
14183 default: return SDValue();
14186 if (!Subtarget->hasFp256())
14188 if (!Subtarget->hasInt256()) {
14189 // needs to be split
14190 unsigned NumElems = VT.getVectorNumElements();
14192 // Extract the LHS vectors
14193 SDValue LHS = Op.getOperand(0);
14194 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14195 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14197 MVT EltVT = VT.getVectorElementType();
14198 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14200 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14201 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14202 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14204 SDValue Extra = DAG.getValueType(ExtraVT);
14206 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14207 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14209 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14214 SDValue Op0 = Op.getOperand(0);
14215 SDValue Op00 = Op0.getOperand(0);
14217 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14218 if (Op0.getOpcode() == ISD::BITCAST &&
14219 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14220 // (sext (vzext x)) -> (vsext x)
14221 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14222 if (Tmp1.getNode()) {
14223 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14224 // This folding is only valid when the in-reg type is a vector of i8,
14226 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14227 ExtraEltVT == MVT::i32) {
14228 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14229 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14230 "This optimization is invalid without a VZEXT.");
14231 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14237 // If the above didn't work, then just use Shift-Left + Shift-Right.
14238 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14240 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14246 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14247 SelectionDAG &DAG) {
14249 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14250 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14251 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14252 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14254 // The only fence that needs an instruction is a sequentially-consistent
14255 // cross-thread fence.
14256 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14257 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14258 // no-sse2). There isn't any reason to disable it if the target processor
14260 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14261 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14263 SDValue Chain = Op.getOperand(0);
14264 SDValue Zero = DAG.getConstant(0, MVT::i32);
14266 DAG.getRegister(X86::ESP, MVT::i32), // Base
14267 DAG.getTargetConstant(1, MVT::i8), // Scale
14268 DAG.getRegister(0, MVT::i32), // Index
14269 DAG.getTargetConstant(0, MVT::i32), // Disp
14270 DAG.getRegister(0, MVT::i32), // Segment.
14274 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14275 return SDValue(Res, 0);
14278 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14279 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14282 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14283 SelectionDAG &DAG) {
14284 MVT T = Op.getSimpleValueType();
14288 switch(T.SimpleTy) {
14289 default: llvm_unreachable("Invalid value type!");
14290 case MVT::i8: Reg = X86::AL; size = 1; break;
14291 case MVT::i16: Reg = X86::AX; size = 2; break;
14292 case MVT::i32: Reg = X86::EAX; size = 4; break;
14294 assert(Subtarget->is64Bit() && "Node not type legal!");
14295 Reg = X86::RAX; size = 8;
14298 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14299 Op.getOperand(2), SDValue());
14300 SDValue Ops[] = { cpIn.getValue(0),
14303 DAG.getTargetConstant(size, MVT::i8),
14304 cpIn.getValue(1) };
14305 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14306 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14307 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14310 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14314 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14315 SelectionDAG &DAG) {
14316 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14317 MVT DstVT = Op.getSimpleValueType();
14319 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14320 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14321 if (DstVT != MVT::f64)
14322 // This conversion needs to be expanded.
14325 SDValue InVec = Op->getOperand(0);
14327 unsigned NumElts = SrcVT.getVectorNumElements();
14328 EVT SVT = SrcVT.getVectorElementType();
14330 // Widen the vector in input in the case of MVT::v2i32.
14331 // Example: from MVT::v2i32 to MVT::v4i32.
14332 SmallVector<SDValue, 16> Elts;
14333 for (unsigned i = 0, e = NumElts; i != e; ++i)
14334 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14335 DAG.getIntPtrConstant(i)));
14337 // Explicitly mark the extra elements as Undef.
14338 SDValue Undef = DAG.getUNDEF(SVT);
14339 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14340 Elts.push_back(Undef);
14342 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14343 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14344 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14345 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14346 DAG.getIntPtrConstant(0));
14349 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14350 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14351 assert((DstVT == MVT::i64 ||
14352 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14353 "Unexpected custom BITCAST");
14354 // i64 <=> MMX conversions are Legal.
14355 if (SrcVT==MVT::i64 && DstVT.isVector())
14357 if (DstVT==MVT::i64 && SrcVT.isVector())
14359 // MMX <=> MMX conversions are Legal.
14360 if (SrcVT.isVector() && DstVT.isVector())
14362 // All other conversions need to be expanded.
14366 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14367 SDNode *Node = Op.getNode();
14369 EVT T = Node->getValueType(0);
14370 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14371 DAG.getConstant(0, T), Node->getOperand(2));
14372 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14373 cast<AtomicSDNode>(Node)->getMemoryVT(),
14374 Node->getOperand(0),
14375 Node->getOperand(1), negOp,
14376 cast<AtomicSDNode>(Node)->getMemOperand(),
14377 cast<AtomicSDNode>(Node)->getOrdering(),
14378 cast<AtomicSDNode>(Node)->getSynchScope());
14381 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14382 SDNode *Node = Op.getNode();
14384 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14386 // Convert seq_cst store -> xchg
14387 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14388 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14389 // (The only way to get a 16-byte store is cmpxchg16b)
14390 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14391 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14392 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14393 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14394 cast<AtomicSDNode>(Node)->getMemoryVT(),
14395 Node->getOperand(0),
14396 Node->getOperand(1), Node->getOperand(2),
14397 cast<AtomicSDNode>(Node)->getMemOperand(),
14398 cast<AtomicSDNode>(Node)->getOrdering(),
14399 cast<AtomicSDNode>(Node)->getSynchScope());
14400 return Swap.getValue(1);
14402 // Other atomic stores have a simple pattern.
14406 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14407 EVT VT = Op.getNode()->getSimpleValueType(0);
14409 // Let legalize expand this if it isn't a legal type yet.
14410 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14413 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14416 bool ExtraOp = false;
14417 switch (Op.getOpcode()) {
14418 default: llvm_unreachable("Invalid code");
14419 case ISD::ADDC: Opc = X86ISD::ADD; break;
14420 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14421 case ISD::SUBC: Opc = X86ISD::SUB; break;
14422 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14426 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14428 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14429 Op.getOperand(1), Op.getOperand(2));
14432 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14433 SelectionDAG &DAG) {
14434 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14436 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14437 // which returns the values as { float, float } (in XMM0) or
14438 // { double, double } (which is returned in XMM0, XMM1).
14440 SDValue Arg = Op.getOperand(0);
14441 EVT ArgVT = Arg.getValueType();
14442 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14444 TargetLowering::ArgListTy Args;
14445 TargetLowering::ArgListEntry Entry;
14449 Entry.isSExt = false;
14450 Entry.isZExt = false;
14451 Args.push_back(Entry);
14453 bool isF64 = ArgVT == MVT::f64;
14454 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14455 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14456 // the results are returned via SRet in memory.
14457 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14458 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14459 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14461 Type *RetTy = isF64
14462 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14463 : (Type*)VectorType::get(ArgTy, 4);
14465 TargetLowering::CallLoweringInfo CLI(DAG);
14466 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14467 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14469 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14472 // Returned in xmm0 and xmm1.
14473 return CallResult.first;
14475 // Returned in bits 0:31 and 32:64 xmm0.
14476 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14477 CallResult.first, DAG.getIntPtrConstant(0));
14478 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14479 CallResult.first, DAG.getIntPtrConstant(1));
14480 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14481 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14484 /// LowerOperation - Provide custom lowering hooks for some operations.
14486 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14487 switch (Op.getOpcode()) {
14488 default: llvm_unreachable("Should not custom lower this!");
14489 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14490 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14491 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14492 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14493 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14494 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14495 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14496 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14497 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
14498 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14499 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14500 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14501 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14502 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14503 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14504 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14505 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14506 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14507 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14508 case ISD::SHL_PARTS:
14509 case ISD::SRA_PARTS:
14510 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14511 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14512 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14513 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14514 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14515 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14516 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14517 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14518 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14519 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14520 case ISD::FABS: return LowerFABS(Op, DAG);
14521 case ISD::FNEG: return LowerFNEG(Op, DAG);
14522 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14523 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14524 case ISD::SETCC: return LowerSETCC(Op, DAG);
14525 case ISD::SELECT: return LowerSELECT(Op, DAG);
14526 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14527 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14528 case ISD::VASTART: return LowerVASTART(Op, DAG);
14529 case ISD::VAARG: return LowerVAARG(Op, DAG);
14530 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14531 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14532 case ISD::INTRINSIC_VOID:
14533 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14534 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14535 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14536 case ISD::FRAME_TO_ARGS_OFFSET:
14537 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14538 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14539 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14540 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14541 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14542 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14543 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14544 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14545 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14546 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14547 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14548 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14549 case ISD::UMUL_LOHI:
14550 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14553 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14559 case ISD::UMULO: return LowerXALUO(Op, DAG);
14560 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14561 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14565 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14566 case ISD::ADD: return LowerADD(Op, DAG);
14567 case ISD::SUB: return LowerSUB(Op, DAG);
14568 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14572 static void ReplaceATOMIC_LOAD(SDNode *Node,
14573 SmallVectorImpl<SDValue> &Results,
14574 SelectionDAG &DAG) {
14576 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14578 // Convert wide load -> cmpxchg8b/cmpxchg16b
14579 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14580 // (The only way to get a 16-byte load is cmpxchg16b)
14581 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14582 SDValue Zero = DAG.getConstant(0, VT);
14583 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14584 Node->getOperand(0),
14585 Node->getOperand(1), Zero, Zero,
14586 cast<AtomicSDNode>(Node)->getMemOperand(),
14587 cast<AtomicSDNode>(Node)->getOrdering(),
14588 cast<AtomicSDNode>(Node)->getOrdering(),
14589 cast<AtomicSDNode>(Node)->getSynchScope());
14590 Results.push_back(Swap.getValue(0));
14591 Results.push_back(Swap.getValue(1));
14595 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14596 SelectionDAG &DAG, unsigned NewOp) {
14598 assert (Node->getValueType(0) == MVT::i64 &&
14599 "Only know how to expand i64 atomics");
14601 SDValue Chain = Node->getOperand(0);
14602 SDValue In1 = Node->getOperand(1);
14603 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14604 Node->getOperand(2), DAG.getIntPtrConstant(0));
14605 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14606 Node->getOperand(2), DAG.getIntPtrConstant(1));
14607 SDValue Ops[] = { Chain, In1, In2L, In2H };
14608 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14610 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14611 cast<MemSDNode>(Node)->getMemOperand());
14612 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14613 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14614 Results.push_back(Result.getValue(2));
14617 /// ReplaceNodeResults - Replace a node with an illegal result type
14618 /// with a new node built out of custom code.
14619 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14620 SmallVectorImpl<SDValue>&Results,
14621 SelectionDAG &DAG) const {
14623 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14624 switch (N->getOpcode()) {
14626 llvm_unreachable("Do not know how to custom type legalize this operation!");
14627 case ISD::SIGN_EXTEND_INREG:
14632 // We don't want to expand or promote these.
14639 case ISD::UDIVREM: {
14640 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14641 Results.push_back(V);
14644 case ISD::FP_TO_SINT:
14645 case ISD::FP_TO_UINT: {
14646 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14648 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14651 std::pair<SDValue,SDValue> Vals =
14652 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14653 SDValue FIST = Vals.first, StackSlot = Vals.second;
14654 if (FIST.getNode()) {
14655 EVT VT = N->getValueType(0);
14656 // Return a load from the stack slot.
14657 if (StackSlot.getNode())
14658 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14659 MachinePointerInfo(),
14660 false, false, false, 0));
14662 Results.push_back(FIST);
14666 case ISD::UINT_TO_FP: {
14667 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14668 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14669 N->getValueType(0) != MVT::v2f32)
14671 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14673 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14675 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14676 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14677 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14678 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14679 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14680 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14683 case ISD::FP_ROUND: {
14684 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14686 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14687 Results.push_back(V);
14690 case ISD::INTRINSIC_W_CHAIN: {
14691 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14693 default : llvm_unreachable("Do not know how to custom type "
14694 "legalize this intrinsic operation!");
14695 case Intrinsic::x86_rdtsc:
14696 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14698 case Intrinsic::x86_rdtscp:
14699 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14703 case ISD::READCYCLECOUNTER: {
14704 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14707 case ISD::ATOMIC_CMP_SWAP: {
14708 EVT T = N->getValueType(0);
14709 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14710 bool Regs64bit = T == MVT::i128;
14711 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14712 SDValue cpInL, cpInH;
14713 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14714 DAG.getConstant(0, HalfT));
14715 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14716 DAG.getConstant(1, HalfT));
14717 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14718 Regs64bit ? X86::RAX : X86::EAX,
14720 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14721 Regs64bit ? X86::RDX : X86::EDX,
14722 cpInH, cpInL.getValue(1));
14723 SDValue swapInL, swapInH;
14724 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14725 DAG.getConstant(0, HalfT));
14726 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14727 DAG.getConstant(1, HalfT));
14728 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14729 Regs64bit ? X86::RBX : X86::EBX,
14730 swapInL, cpInH.getValue(1));
14731 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14732 Regs64bit ? X86::RCX : X86::ECX,
14733 swapInH, swapInL.getValue(1));
14734 SDValue Ops[] = { swapInH.getValue(0),
14736 swapInH.getValue(1) };
14737 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14738 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14739 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14740 X86ISD::LCMPXCHG8_DAG;
14741 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14742 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14743 Regs64bit ? X86::RAX : X86::EAX,
14744 HalfT, Result.getValue(1));
14745 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14746 Regs64bit ? X86::RDX : X86::EDX,
14747 HalfT, cpOutL.getValue(2));
14748 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14749 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14750 Results.push_back(cpOutH.getValue(1));
14753 case ISD::ATOMIC_LOAD_ADD:
14754 case ISD::ATOMIC_LOAD_AND:
14755 case ISD::ATOMIC_LOAD_NAND:
14756 case ISD::ATOMIC_LOAD_OR:
14757 case ISD::ATOMIC_LOAD_SUB:
14758 case ISD::ATOMIC_LOAD_XOR:
14759 case ISD::ATOMIC_LOAD_MAX:
14760 case ISD::ATOMIC_LOAD_MIN:
14761 case ISD::ATOMIC_LOAD_UMAX:
14762 case ISD::ATOMIC_LOAD_UMIN:
14763 case ISD::ATOMIC_SWAP: {
14765 switch (N->getOpcode()) {
14766 default: llvm_unreachable("Unexpected opcode");
14767 case ISD::ATOMIC_LOAD_ADD:
14768 Opc = X86ISD::ATOMADD64_DAG;
14770 case ISD::ATOMIC_LOAD_AND:
14771 Opc = X86ISD::ATOMAND64_DAG;
14773 case ISD::ATOMIC_LOAD_NAND:
14774 Opc = X86ISD::ATOMNAND64_DAG;
14776 case ISD::ATOMIC_LOAD_OR:
14777 Opc = X86ISD::ATOMOR64_DAG;
14779 case ISD::ATOMIC_LOAD_SUB:
14780 Opc = X86ISD::ATOMSUB64_DAG;
14782 case ISD::ATOMIC_LOAD_XOR:
14783 Opc = X86ISD::ATOMXOR64_DAG;
14785 case ISD::ATOMIC_LOAD_MAX:
14786 Opc = X86ISD::ATOMMAX64_DAG;
14788 case ISD::ATOMIC_LOAD_MIN:
14789 Opc = X86ISD::ATOMMIN64_DAG;
14791 case ISD::ATOMIC_LOAD_UMAX:
14792 Opc = X86ISD::ATOMUMAX64_DAG;
14794 case ISD::ATOMIC_LOAD_UMIN:
14795 Opc = X86ISD::ATOMUMIN64_DAG;
14797 case ISD::ATOMIC_SWAP:
14798 Opc = X86ISD::ATOMSWAP64_DAG;
14801 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14804 case ISD::ATOMIC_LOAD: {
14805 ReplaceATOMIC_LOAD(N, Results, DAG);
14808 case ISD::BITCAST: {
14809 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14810 EVT DstVT = N->getValueType(0);
14811 EVT SrcVT = N->getOperand(0)->getValueType(0);
14813 if (SrcVT != MVT::f64 ||
14814 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
14817 unsigned NumElts = DstVT.getVectorNumElements();
14818 EVT SVT = DstVT.getVectorElementType();
14819 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14820 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14821 MVT::v2f64, N->getOperand(0));
14822 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
14824 SmallVector<SDValue, 8> Elts;
14825 for (unsigned i = 0, e = NumElts; i != e; ++i)
14826 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
14827 ToVecInt, DAG.getIntPtrConstant(i)));
14829 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
14834 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14836 default: return nullptr;
14837 case X86ISD::BSF: return "X86ISD::BSF";
14838 case X86ISD::BSR: return "X86ISD::BSR";
14839 case X86ISD::SHLD: return "X86ISD::SHLD";
14840 case X86ISD::SHRD: return "X86ISD::SHRD";
14841 case X86ISD::FAND: return "X86ISD::FAND";
14842 case X86ISD::FANDN: return "X86ISD::FANDN";
14843 case X86ISD::FOR: return "X86ISD::FOR";
14844 case X86ISD::FXOR: return "X86ISD::FXOR";
14845 case X86ISD::FSRL: return "X86ISD::FSRL";
14846 case X86ISD::FILD: return "X86ISD::FILD";
14847 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14848 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14849 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14850 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14851 case X86ISD::FLD: return "X86ISD::FLD";
14852 case X86ISD::FST: return "X86ISD::FST";
14853 case X86ISD::CALL: return "X86ISD::CALL";
14854 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14855 case X86ISD::BT: return "X86ISD::BT";
14856 case X86ISD::CMP: return "X86ISD::CMP";
14857 case X86ISD::COMI: return "X86ISD::COMI";
14858 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14859 case X86ISD::CMPM: return "X86ISD::CMPM";
14860 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14861 case X86ISD::SETCC: return "X86ISD::SETCC";
14862 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14863 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14864 case X86ISD::CMOV: return "X86ISD::CMOV";
14865 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14866 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14867 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14868 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14869 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14870 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14871 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14872 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14873 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14874 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14875 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14876 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14877 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14878 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14879 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14880 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14881 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14882 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14883 case X86ISD::HADD: return "X86ISD::HADD";
14884 case X86ISD::HSUB: return "X86ISD::HSUB";
14885 case X86ISD::FHADD: return "X86ISD::FHADD";
14886 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14887 case X86ISD::UMAX: return "X86ISD::UMAX";
14888 case X86ISD::UMIN: return "X86ISD::UMIN";
14889 case X86ISD::SMAX: return "X86ISD::SMAX";
14890 case X86ISD::SMIN: return "X86ISD::SMIN";
14891 case X86ISD::FMAX: return "X86ISD::FMAX";
14892 case X86ISD::FMIN: return "X86ISD::FMIN";
14893 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14894 case X86ISD::FMINC: return "X86ISD::FMINC";
14895 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14896 case X86ISD::FRCP: return "X86ISD::FRCP";
14897 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14898 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14899 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14900 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14901 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14902 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14903 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14904 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14905 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14906 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14907 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14908 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14909 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14910 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14911 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14912 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14913 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14914 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14915 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14916 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14917 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14918 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14919 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14920 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14921 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14922 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14923 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14924 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14925 case X86ISD::VSHL: return "X86ISD::VSHL";
14926 case X86ISD::VSRL: return "X86ISD::VSRL";
14927 case X86ISD::VSRA: return "X86ISD::VSRA";
14928 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14929 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14930 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14931 case X86ISD::CMPP: return "X86ISD::CMPP";
14932 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14933 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14934 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14935 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14936 case X86ISD::ADD: return "X86ISD::ADD";
14937 case X86ISD::SUB: return "X86ISD::SUB";
14938 case X86ISD::ADC: return "X86ISD::ADC";
14939 case X86ISD::SBB: return "X86ISD::SBB";
14940 case X86ISD::SMUL: return "X86ISD::SMUL";
14941 case X86ISD::UMUL: return "X86ISD::UMUL";
14942 case X86ISD::INC: return "X86ISD::INC";
14943 case X86ISD::DEC: return "X86ISD::DEC";
14944 case X86ISD::OR: return "X86ISD::OR";
14945 case X86ISD::XOR: return "X86ISD::XOR";
14946 case X86ISD::AND: return "X86ISD::AND";
14947 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14948 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14949 case X86ISD::PTEST: return "X86ISD::PTEST";
14950 case X86ISD::TESTP: return "X86ISD::TESTP";
14951 case X86ISD::TESTM: return "X86ISD::TESTM";
14952 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14953 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14954 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14955 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14956 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14957 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14958 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14959 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14960 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14961 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14962 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14963 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14964 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14965 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14966 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14967 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14968 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14969 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14970 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14971 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14972 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14973 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14974 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14975 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14976 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14977 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14978 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14979 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14980 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14981 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14982 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14983 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14984 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14985 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14986 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14987 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14988 case X86ISD::SAHF: return "X86ISD::SAHF";
14989 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14990 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14991 case X86ISD::FMADD: return "X86ISD::FMADD";
14992 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14993 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14994 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14995 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14996 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14997 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14998 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14999 case X86ISD::XTEST: return "X86ISD::XTEST";
15003 // isLegalAddressingMode - Return true if the addressing mode represented
15004 // by AM is legal for this target, for a load/store of the specified type.
15005 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15007 // X86 supports extremely general addressing modes.
15008 CodeModel::Model M = getTargetMachine().getCodeModel();
15009 Reloc::Model R = getTargetMachine().getRelocationModel();
15011 // X86 allows a sign-extended 32-bit immediate field as a displacement.
15012 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15017 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15019 // If a reference to this global requires an extra load, we can't fold it.
15020 if (isGlobalStubReference(GVFlags))
15023 // If BaseGV requires a register for the PIC base, we cannot also have a
15024 // BaseReg specified.
15025 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15028 // If lower 4G is not available, then we must use rip-relative addressing.
15029 if ((M != CodeModel::Small || R != Reloc::Static) &&
15030 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15034 switch (AM.Scale) {
15040 // These scales always work.
15045 // These scales are formed with basereg+scalereg. Only accept if there is
15050 default: // Other stuff never works.
15057 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15058 unsigned Bits = Ty->getScalarSizeInBits();
15060 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15061 // particularly cheaper than those without.
15065 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15066 // variable shifts just as cheap as scalar ones.
15067 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15070 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15071 // fully general vector.
15075 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15076 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15078 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15079 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15080 return NumBits1 > NumBits2;
15083 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15084 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15087 if (!isTypeLegal(EVT::getEVT(Ty1)))
15090 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15092 // Assuming the caller doesn't have a zeroext or signext return parameter,
15093 // truncation all the way down to i1 is valid.
15097 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15098 return isInt<32>(Imm);
15101 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15102 // Can also use sub to handle negated immediates.
15103 return isInt<32>(Imm);
15106 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15107 if (!VT1.isInteger() || !VT2.isInteger())
15109 unsigned NumBits1 = VT1.getSizeInBits();
15110 unsigned NumBits2 = VT2.getSizeInBits();
15111 return NumBits1 > NumBits2;
15114 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15115 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15116 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15119 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15120 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15121 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15124 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15125 EVT VT1 = Val.getValueType();
15126 if (isZExtFree(VT1, VT2))
15129 if (Val.getOpcode() != ISD::LOAD)
15132 if (!VT1.isSimple() || !VT1.isInteger() ||
15133 !VT2.isSimple() || !VT2.isInteger())
15136 switch (VT1.getSimpleVT().SimpleTy) {
15141 // X86 has 8, 16, and 32-bit zero-extending loads.
15149 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15150 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15153 VT = VT.getScalarType();
15155 if (!VT.isSimple())
15158 switch (VT.getSimpleVT().SimpleTy) {
15169 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15170 // i16 instructions are longer (0x66 prefix) and potentially slower.
15171 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15174 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15175 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15176 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15177 /// are assumed to be legal.
15179 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15181 if (!VT.isSimple())
15184 MVT SVT = VT.getSimpleVT();
15186 // Very little shuffling can be done for 64-bit vectors right now.
15187 if (VT.getSizeInBits() == 64)
15190 // If this is a single-input shuffle with no 128 bit lane crossings we can
15191 // lower it into pshufb.
15192 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15193 (SVT.is256BitVector() && Subtarget->hasInt256())) {
15194 bool isLegal = true;
15195 for (unsigned I = 0, E = M.size(); I != E; ++I) {
15196 if (M[I] >= (int)SVT.getVectorNumElements() ||
15197 ShuffleCrosses128bitLane(SVT, I, M[I])) {
15206 // FIXME: blends, shifts.
15207 return (SVT.getVectorNumElements() == 2 ||
15208 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15209 isMOVLMask(M, SVT) ||
15210 isSHUFPMask(M, SVT) ||
15211 isPSHUFDMask(M, SVT) ||
15212 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15213 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15214 isPALIGNRMask(M, SVT, Subtarget) ||
15215 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15216 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15217 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15218 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15219 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15223 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15225 if (!VT.isSimple())
15228 MVT SVT = VT.getSimpleVT();
15229 unsigned NumElts = SVT.getVectorNumElements();
15230 // FIXME: This collection of masks seems suspect.
15233 if (NumElts == 4 && SVT.is128BitVector()) {
15234 return (isMOVLMask(Mask, SVT) ||
15235 isCommutedMOVLMask(Mask, SVT, true) ||
15236 isSHUFPMask(Mask, SVT) ||
15237 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15242 //===----------------------------------------------------------------------===//
15243 // X86 Scheduler Hooks
15244 //===----------------------------------------------------------------------===//
15246 /// Utility function to emit xbegin specifying the start of an RTM region.
15247 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15248 const TargetInstrInfo *TII) {
15249 DebugLoc DL = MI->getDebugLoc();
15251 const BasicBlock *BB = MBB->getBasicBlock();
15252 MachineFunction::iterator I = MBB;
15255 // For the v = xbegin(), we generate
15266 MachineBasicBlock *thisMBB = MBB;
15267 MachineFunction *MF = MBB->getParent();
15268 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15269 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15270 MF->insert(I, mainMBB);
15271 MF->insert(I, sinkMBB);
15273 // Transfer the remainder of BB and its successor edges to sinkMBB.
15274 sinkMBB->splice(sinkMBB->begin(), MBB,
15275 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15276 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15280 // # fallthrough to mainMBB
15281 // # abortion to sinkMBB
15282 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15283 thisMBB->addSuccessor(mainMBB);
15284 thisMBB->addSuccessor(sinkMBB);
15288 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15289 mainMBB->addSuccessor(sinkMBB);
15292 // EAX is live into the sinkMBB
15293 sinkMBB->addLiveIn(X86::EAX);
15294 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15295 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15298 MI->eraseFromParent();
15302 // Get CMPXCHG opcode for the specified data type.
15303 static unsigned getCmpXChgOpcode(EVT VT) {
15304 switch (VT.getSimpleVT().SimpleTy) {
15305 case MVT::i8: return X86::LCMPXCHG8;
15306 case MVT::i16: return X86::LCMPXCHG16;
15307 case MVT::i32: return X86::LCMPXCHG32;
15308 case MVT::i64: return X86::LCMPXCHG64;
15312 llvm_unreachable("Invalid operand size!");
15315 // Get LOAD opcode for the specified data type.
15316 static unsigned getLoadOpcode(EVT VT) {
15317 switch (VT.getSimpleVT().SimpleTy) {
15318 case MVT::i8: return X86::MOV8rm;
15319 case MVT::i16: return X86::MOV16rm;
15320 case MVT::i32: return X86::MOV32rm;
15321 case MVT::i64: return X86::MOV64rm;
15325 llvm_unreachable("Invalid operand size!");
15328 // Get opcode of the non-atomic one from the specified atomic instruction.
15329 static unsigned getNonAtomicOpcode(unsigned Opc) {
15331 case X86::ATOMAND8: return X86::AND8rr;
15332 case X86::ATOMAND16: return X86::AND16rr;
15333 case X86::ATOMAND32: return X86::AND32rr;
15334 case X86::ATOMAND64: return X86::AND64rr;
15335 case X86::ATOMOR8: return X86::OR8rr;
15336 case X86::ATOMOR16: return X86::OR16rr;
15337 case X86::ATOMOR32: return X86::OR32rr;
15338 case X86::ATOMOR64: return X86::OR64rr;
15339 case X86::ATOMXOR8: return X86::XOR8rr;
15340 case X86::ATOMXOR16: return X86::XOR16rr;
15341 case X86::ATOMXOR32: return X86::XOR32rr;
15342 case X86::ATOMXOR64: return X86::XOR64rr;
15344 llvm_unreachable("Unhandled atomic-load-op opcode!");
15347 // Get opcode of the non-atomic one from the specified atomic instruction with
15349 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15350 unsigned &ExtraOpc) {
15352 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15353 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15354 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15355 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15356 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15357 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15358 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15359 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15360 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15361 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15362 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15363 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15364 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15365 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15366 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15367 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15368 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15369 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15370 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15371 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15373 llvm_unreachable("Unhandled atomic-load-op opcode!");
15376 // Get opcode of the non-atomic one from the specified atomic instruction for
15377 // 64-bit data type on 32-bit target.
15378 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15380 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15381 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15382 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15383 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15384 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15385 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15386 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15387 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15388 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15389 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15391 llvm_unreachable("Unhandled atomic-load-op opcode!");
15394 // Get opcode of the non-atomic one from the specified atomic instruction for
15395 // 64-bit data type on 32-bit target with extra opcode.
15396 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15398 unsigned &ExtraOpc) {
15400 case X86::ATOMNAND6432:
15401 ExtraOpc = X86::NOT32r;
15402 HiOpc = X86::AND32rr;
15403 return X86::AND32rr;
15405 llvm_unreachable("Unhandled atomic-load-op opcode!");
15408 // Get pseudo CMOV opcode from the specified data type.
15409 static unsigned getPseudoCMOVOpc(EVT VT) {
15410 switch (VT.getSimpleVT().SimpleTy) {
15411 case MVT::i8: return X86::CMOV_GR8;
15412 case MVT::i16: return X86::CMOV_GR16;
15413 case MVT::i32: return X86::CMOV_GR32;
15417 llvm_unreachable("Unknown CMOV opcode!");
15420 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15421 // They will be translated into a spin-loop or compare-exchange loop from
15424 // dst = atomic-fetch-op MI.addr, MI.val
15430 // t1 = LOAD MI.addr
15432 // t4 = phi(t1, t3 / loop)
15433 // t2 = OP MI.val, t4
15435 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15441 MachineBasicBlock *
15442 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15443 MachineBasicBlock *MBB) const {
15444 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15445 DebugLoc DL = MI->getDebugLoc();
15447 MachineFunction *MF = MBB->getParent();
15448 MachineRegisterInfo &MRI = MF->getRegInfo();
15450 const BasicBlock *BB = MBB->getBasicBlock();
15451 MachineFunction::iterator I = MBB;
15454 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15455 "Unexpected number of operands");
15457 assert(MI->hasOneMemOperand() &&
15458 "Expected atomic-load-op to have one memoperand");
15460 // Memory Reference
15461 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15462 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15464 unsigned DstReg, SrcReg;
15465 unsigned MemOpndSlot;
15467 unsigned CurOp = 0;
15469 DstReg = MI->getOperand(CurOp++).getReg();
15470 MemOpndSlot = CurOp;
15471 CurOp += X86::AddrNumOperands;
15472 SrcReg = MI->getOperand(CurOp++).getReg();
15474 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15475 MVT::SimpleValueType VT = *RC->vt_begin();
15476 unsigned t1 = MRI.createVirtualRegister(RC);
15477 unsigned t2 = MRI.createVirtualRegister(RC);
15478 unsigned t3 = MRI.createVirtualRegister(RC);
15479 unsigned t4 = MRI.createVirtualRegister(RC);
15480 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15482 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15483 unsigned LOADOpc = getLoadOpcode(VT);
15485 // For the atomic load-arith operator, we generate
15488 // t1 = LOAD [MI.addr]
15490 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15491 // t1 = OP MI.val, EAX
15493 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15499 MachineBasicBlock *thisMBB = MBB;
15500 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15501 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15502 MF->insert(I, mainMBB);
15503 MF->insert(I, sinkMBB);
15505 MachineInstrBuilder MIB;
15507 // Transfer the remainder of BB and its successor edges to sinkMBB.
15508 sinkMBB->splice(sinkMBB->begin(), MBB,
15509 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15510 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15513 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15514 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15515 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15517 NewMO.setIsKill(false);
15518 MIB.addOperand(NewMO);
15520 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15521 unsigned flags = (*MMOI)->getFlags();
15522 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15523 MachineMemOperand *MMO =
15524 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15525 (*MMOI)->getSize(),
15526 (*MMOI)->getBaseAlignment(),
15527 (*MMOI)->getTBAAInfo(),
15528 (*MMOI)->getRanges());
15529 MIB.addMemOperand(MMO);
15532 thisMBB->addSuccessor(mainMBB);
15535 MachineBasicBlock *origMainMBB = mainMBB;
15538 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15539 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15541 unsigned Opc = MI->getOpcode();
15544 llvm_unreachable("Unhandled atomic-load-op opcode!");
15545 case X86::ATOMAND8:
15546 case X86::ATOMAND16:
15547 case X86::ATOMAND32:
15548 case X86::ATOMAND64:
15550 case X86::ATOMOR16:
15551 case X86::ATOMOR32:
15552 case X86::ATOMOR64:
15553 case X86::ATOMXOR8:
15554 case X86::ATOMXOR16:
15555 case X86::ATOMXOR32:
15556 case X86::ATOMXOR64: {
15557 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15558 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15562 case X86::ATOMNAND8:
15563 case X86::ATOMNAND16:
15564 case X86::ATOMNAND32:
15565 case X86::ATOMNAND64: {
15566 unsigned Tmp = MRI.createVirtualRegister(RC);
15568 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15569 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15571 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15574 case X86::ATOMMAX8:
15575 case X86::ATOMMAX16:
15576 case X86::ATOMMAX32:
15577 case X86::ATOMMAX64:
15578 case X86::ATOMMIN8:
15579 case X86::ATOMMIN16:
15580 case X86::ATOMMIN32:
15581 case X86::ATOMMIN64:
15582 case X86::ATOMUMAX8:
15583 case X86::ATOMUMAX16:
15584 case X86::ATOMUMAX32:
15585 case X86::ATOMUMAX64:
15586 case X86::ATOMUMIN8:
15587 case X86::ATOMUMIN16:
15588 case X86::ATOMUMIN32:
15589 case X86::ATOMUMIN64: {
15591 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15593 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15597 if (Subtarget->hasCMov()) {
15598 if (VT != MVT::i8) {
15600 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15604 // Promote i8 to i32 to use CMOV32
15605 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15606 const TargetRegisterClass *RC32 =
15607 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15608 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15609 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15610 unsigned Tmp = MRI.createVirtualRegister(RC32);
15612 unsigned Undef = MRI.createVirtualRegister(RC32);
15613 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15615 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15618 .addImm(X86::sub_8bit);
15619 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15622 .addImm(X86::sub_8bit);
15624 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15628 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15629 .addReg(Tmp, 0, X86::sub_8bit);
15632 // Use pseudo select and lower them.
15633 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15634 "Invalid atomic-load-op transformation!");
15635 unsigned SelOpc = getPseudoCMOVOpc(VT);
15636 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15637 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15638 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15639 .addReg(SrcReg).addReg(t4)
15641 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15642 // Replace the original PHI node as mainMBB is changed after CMOV
15644 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15645 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15646 Phi->eraseFromParent();
15652 // Copy PhyReg back from virtual register.
15653 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15656 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15657 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15658 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15660 NewMO.setIsKill(false);
15661 MIB.addOperand(NewMO);
15664 MIB.setMemRefs(MMOBegin, MMOEnd);
15666 // Copy PhyReg back to virtual register.
15667 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15670 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15672 mainMBB->addSuccessor(origMainMBB);
15673 mainMBB->addSuccessor(sinkMBB);
15676 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15677 TII->get(TargetOpcode::COPY), DstReg)
15680 MI->eraseFromParent();
15684 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15685 // instructions. They will be translated into a spin-loop or compare-exchange
15689 // dst = atomic-fetch-op MI.addr, MI.val
15695 // t1L = LOAD [MI.addr + 0]
15696 // t1H = LOAD [MI.addr + 4]
15698 // t4L = phi(t1L, t3L / loop)
15699 // t4H = phi(t1H, t3H / loop)
15700 // t2L = OP MI.val.lo, t4L
15701 // t2H = OP MI.val.hi, t4H
15706 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15714 MachineBasicBlock *
15715 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15716 MachineBasicBlock *MBB) const {
15717 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15718 DebugLoc DL = MI->getDebugLoc();
15720 MachineFunction *MF = MBB->getParent();
15721 MachineRegisterInfo &MRI = MF->getRegInfo();
15723 const BasicBlock *BB = MBB->getBasicBlock();
15724 MachineFunction::iterator I = MBB;
15727 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15728 "Unexpected number of operands");
15730 assert(MI->hasOneMemOperand() &&
15731 "Expected atomic-load-op32 to have one memoperand");
15733 // Memory Reference
15734 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15735 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15737 unsigned DstLoReg, DstHiReg;
15738 unsigned SrcLoReg, SrcHiReg;
15739 unsigned MemOpndSlot;
15741 unsigned CurOp = 0;
15743 DstLoReg = MI->getOperand(CurOp++).getReg();
15744 DstHiReg = MI->getOperand(CurOp++).getReg();
15745 MemOpndSlot = CurOp;
15746 CurOp += X86::AddrNumOperands;
15747 SrcLoReg = MI->getOperand(CurOp++).getReg();
15748 SrcHiReg = MI->getOperand(CurOp++).getReg();
15750 const TargetRegisterClass *RC = &X86::GR32RegClass;
15751 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15753 unsigned t1L = MRI.createVirtualRegister(RC);
15754 unsigned t1H = MRI.createVirtualRegister(RC);
15755 unsigned t2L = MRI.createVirtualRegister(RC);
15756 unsigned t2H = MRI.createVirtualRegister(RC);
15757 unsigned t3L = MRI.createVirtualRegister(RC);
15758 unsigned t3H = MRI.createVirtualRegister(RC);
15759 unsigned t4L = MRI.createVirtualRegister(RC);
15760 unsigned t4H = MRI.createVirtualRegister(RC);
15762 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15763 unsigned LOADOpc = X86::MOV32rm;
15765 // For the atomic load-arith operator, we generate
15768 // t1L = LOAD [MI.addr + 0]
15769 // t1H = LOAD [MI.addr + 4]
15771 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15772 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15773 // t2L = OP MI.val.lo, t4L
15774 // t2H = OP MI.val.hi, t4H
15777 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15785 MachineBasicBlock *thisMBB = MBB;
15786 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15787 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15788 MF->insert(I, mainMBB);
15789 MF->insert(I, sinkMBB);
15791 MachineInstrBuilder MIB;
15793 // Transfer the remainder of BB and its successor edges to sinkMBB.
15794 sinkMBB->splice(sinkMBB->begin(), MBB,
15795 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15796 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15800 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15801 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15802 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15804 NewMO.setIsKill(false);
15805 MIB.addOperand(NewMO);
15807 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15808 unsigned flags = (*MMOI)->getFlags();
15809 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15810 MachineMemOperand *MMO =
15811 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15812 (*MMOI)->getSize(),
15813 (*MMOI)->getBaseAlignment(),
15814 (*MMOI)->getTBAAInfo(),
15815 (*MMOI)->getRanges());
15816 MIB.addMemOperand(MMO);
15818 MachineInstr *LowMI = MIB;
15821 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15822 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15823 if (i == X86::AddrDisp) {
15824 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15826 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15828 NewMO.setIsKill(false);
15829 MIB.addOperand(NewMO);
15832 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15834 thisMBB->addSuccessor(mainMBB);
15837 MachineBasicBlock *origMainMBB = mainMBB;
15840 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15841 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15842 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15843 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15845 unsigned Opc = MI->getOpcode();
15848 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15849 case X86::ATOMAND6432:
15850 case X86::ATOMOR6432:
15851 case X86::ATOMXOR6432:
15852 case X86::ATOMADD6432:
15853 case X86::ATOMSUB6432: {
15855 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15856 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15858 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15862 case X86::ATOMNAND6432: {
15863 unsigned HiOpc, NOTOpc;
15864 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15865 unsigned TmpL = MRI.createVirtualRegister(RC);
15866 unsigned TmpH = MRI.createVirtualRegister(RC);
15867 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15869 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15871 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15872 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15875 case X86::ATOMMAX6432:
15876 case X86::ATOMMIN6432:
15877 case X86::ATOMUMAX6432:
15878 case X86::ATOMUMIN6432: {
15880 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15881 unsigned cL = MRI.createVirtualRegister(RC8);
15882 unsigned cH = MRI.createVirtualRegister(RC8);
15883 unsigned cL32 = MRI.createVirtualRegister(RC);
15884 unsigned cH32 = MRI.createVirtualRegister(RC);
15885 unsigned cc = MRI.createVirtualRegister(RC);
15886 // cl := cmp src_lo, lo
15887 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15888 .addReg(SrcLoReg).addReg(t4L);
15889 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15890 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15891 // ch := cmp src_hi, hi
15892 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15893 .addReg(SrcHiReg).addReg(t4H);
15894 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15895 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15896 // cc := if (src_hi == hi) ? cl : ch;
15897 if (Subtarget->hasCMov()) {
15898 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15899 .addReg(cH32).addReg(cL32);
15901 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15902 .addReg(cH32).addReg(cL32)
15903 .addImm(X86::COND_E);
15904 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15906 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15907 if (Subtarget->hasCMov()) {
15908 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15909 .addReg(SrcLoReg).addReg(t4L);
15910 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15911 .addReg(SrcHiReg).addReg(t4H);
15913 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15914 .addReg(SrcLoReg).addReg(t4L)
15915 .addImm(X86::COND_NE);
15916 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15917 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15918 // 2nd CMOV lowering.
15919 mainMBB->addLiveIn(X86::EFLAGS);
15920 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15921 .addReg(SrcHiReg).addReg(t4H)
15922 .addImm(X86::COND_NE);
15923 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15924 // Replace the original PHI node as mainMBB is changed after CMOV
15926 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15927 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15928 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15929 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15930 PhiL->eraseFromParent();
15931 PhiH->eraseFromParent();
15935 case X86::ATOMSWAP6432: {
15937 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15938 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15939 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15944 // Copy EDX:EAX back from HiReg:LoReg
15945 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15946 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15947 // Copy ECX:EBX from t1H:t1L
15948 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15949 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15951 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15952 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15953 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15955 NewMO.setIsKill(false);
15956 MIB.addOperand(NewMO);
15958 MIB.setMemRefs(MMOBegin, MMOEnd);
15960 // Copy EDX:EAX back to t3H:t3L
15961 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15962 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15964 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15966 mainMBB->addSuccessor(origMainMBB);
15967 mainMBB->addSuccessor(sinkMBB);
15970 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15971 TII->get(TargetOpcode::COPY), DstLoReg)
15973 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15974 TII->get(TargetOpcode::COPY), DstHiReg)
15977 MI->eraseFromParent();
15981 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15982 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15983 // in the .td file.
15984 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15985 const TargetInstrInfo *TII) {
15987 switch (MI->getOpcode()) {
15988 default: llvm_unreachable("illegal opcode!");
15989 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15990 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15991 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15992 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15993 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15994 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15995 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15996 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15999 DebugLoc dl = MI->getDebugLoc();
16000 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16002 unsigned NumArgs = MI->getNumOperands();
16003 for (unsigned i = 1; i < NumArgs; ++i) {
16004 MachineOperand &Op = MI->getOperand(i);
16005 if (!(Op.isReg() && Op.isImplicit()))
16006 MIB.addOperand(Op);
16008 if (MI->hasOneMemOperand())
16009 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16011 BuildMI(*BB, MI, dl,
16012 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16013 .addReg(X86::XMM0);
16015 MI->eraseFromParent();
16019 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16020 // defs in an instruction pattern
16021 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16022 const TargetInstrInfo *TII) {
16024 switch (MI->getOpcode()) {
16025 default: llvm_unreachable("illegal opcode!");
16026 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16027 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16028 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16029 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16030 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16031 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16032 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16033 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16036 DebugLoc dl = MI->getDebugLoc();
16037 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16039 unsigned NumArgs = MI->getNumOperands(); // remove the results
16040 for (unsigned i = 1; i < NumArgs; ++i) {
16041 MachineOperand &Op = MI->getOperand(i);
16042 if (!(Op.isReg() && Op.isImplicit()))
16043 MIB.addOperand(Op);
16045 if (MI->hasOneMemOperand())
16046 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16048 BuildMI(*BB, MI, dl,
16049 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16052 MI->eraseFromParent();
16056 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16057 const TargetInstrInfo *TII,
16058 const X86Subtarget* Subtarget) {
16059 DebugLoc dl = MI->getDebugLoc();
16061 // Address into RAX/EAX, other two args into ECX, EDX.
16062 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16063 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16064 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16065 for (int i = 0; i < X86::AddrNumOperands; ++i)
16066 MIB.addOperand(MI->getOperand(i));
16068 unsigned ValOps = X86::AddrNumOperands;
16069 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16070 .addReg(MI->getOperand(ValOps).getReg());
16071 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16072 .addReg(MI->getOperand(ValOps+1).getReg());
16074 // The instruction doesn't actually take any operands though.
16075 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16077 MI->eraseFromParent(); // The pseudo is gone now.
16081 MachineBasicBlock *
16082 X86TargetLowering::EmitVAARG64WithCustomInserter(
16084 MachineBasicBlock *MBB) const {
16085 // Emit va_arg instruction on X86-64.
16087 // Operands to this pseudo-instruction:
16088 // 0 ) Output : destination address (reg)
16089 // 1-5) Input : va_list address (addr, i64mem)
16090 // 6 ) ArgSize : Size (in bytes) of vararg type
16091 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16092 // 8 ) Align : Alignment of type
16093 // 9 ) EFLAGS (implicit-def)
16095 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16096 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16098 unsigned DestReg = MI->getOperand(0).getReg();
16099 MachineOperand &Base = MI->getOperand(1);
16100 MachineOperand &Scale = MI->getOperand(2);
16101 MachineOperand &Index = MI->getOperand(3);
16102 MachineOperand &Disp = MI->getOperand(4);
16103 MachineOperand &Segment = MI->getOperand(5);
16104 unsigned ArgSize = MI->getOperand(6).getImm();
16105 unsigned ArgMode = MI->getOperand(7).getImm();
16106 unsigned Align = MI->getOperand(8).getImm();
16108 // Memory Reference
16109 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16110 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16111 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16113 // Machine Information
16114 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16115 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16116 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16117 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16118 DebugLoc DL = MI->getDebugLoc();
16120 // struct va_list {
16123 // i64 overflow_area (address)
16124 // i64 reg_save_area (address)
16126 // sizeof(va_list) = 24
16127 // alignment(va_list) = 8
16129 unsigned TotalNumIntRegs = 6;
16130 unsigned TotalNumXMMRegs = 8;
16131 bool UseGPOffset = (ArgMode == 1);
16132 bool UseFPOffset = (ArgMode == 2);
16133 unsigned MaxOffset = TotalNumIntRegs * 8 +
16134 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16136 /* Align ArgSize to a multiple of 8 */
16137 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16138 bool NeedsAlign = (Align > 8);
16140 MachineBasicBlock *thisMBB = MBB;
16141 MachineBasicBlock *overflowMBB;
16142 MachineBasicBlock *offsetMBB;
16143 MachineBasicBlock *endMBB;
16145 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
16146 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
16147 unsigned OffsetReg = 0;
16149 if (!UseGPOffset && !UseFPOffset) {
16150 // If we only pull from the overflow region, we don't create a branch.
16151 // We don't need to alter control flow.
16152 OffsetDestReg = 0; // unused
16153 OverflowDestReg = DestReg;
16155 offsetMBB = nullptr;
16156 overflowMBB = thisMBB;
16159 // First emit code to check if gp_offset (or fp_offset) is below the bound.
16160 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16161 // If not, pull from overflow_area. (branch to overflowMBB)
16166 // offsetMBB overflowMBB
16171 // Registers for the PHI in endMBB
16172 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16173 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16175 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16176 MachineFunction *MF = MBB->getParent();
16177 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16178 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16179 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16181 MachineFunction::iterator MBBIter = MBB;
16184 // Insert the new basic blocks
16185 MF->insert(MBBIter, offsetMBB);
16186 MF->insert(MBBIter, overflowMBB);
16187 MF->insert(MBBIter, endMBB);
16189 // Transfer the remainder of MBB and its successor edges to endMBB.
16190 endMBB->splice(endMBB->begin(), thisMBB,
16191 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16192 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16194 // Make offsetMBB and overflowMBB successors of thisMBB
16195 thisMBB->addSuccessor(offsetMBB);
16196 thisMBB->addSuccessor(overflowMBB);
16198 // endMBB is a successor of both offsetMBB and overflowMBB
16199 offsetMBB->addSuccessor(endMBB);
16200 overflowMBB->addSuccessor(endMBB);
16202 // Load the offset value into a register
16203 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16204 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16208 .addDisp(Disp, UseFPOffset ? 4 : 0)
16209 .addOperand(Segment)
16210 .setMemRefs(MMOBegin, MMOEnd);
16212 // Check if there is enough room left to pull this argument.
16213 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16215 .addImm(MaxOffset + 8 - ArgSizeA8);
16217 // Branch to "overflowMBB" if offset >= max
16218 // Fall through to "offsetMBB" otherwise
16219 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16220 .addMBB(overflowMBB);
16223 // In offsetMBB, emit code to use the reg_save_area.
16225 assert(OffsetReg != 0);
16227 // Read the reg_save_area address.
16228 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16229 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16234 .addOperand(Segment)
16235 .setMemRefs(MMOBegin, MMOEnd);
16237 // Zero-extend the offset
16238 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16239 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16242 .addImm(X86::sub_32bit);
16244 // Add the offset to the reg_save_area to get the final address.
16245 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16246 .addReg(OffsetReg64)
16247 .addReg(RegSaveReg);
16249 // Compute the offset for the next argument
16250 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16251 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16253 .addImm(UseFPOffset ? 16 : 8);
16255 // Store it back into the va_list.
16256 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16260 .addDisp(Disp, UseFPOffset ? 4 : 0)
16261 .addOperand(Segment)
16262 .addReg(NextOffsetReg)
16263 .setMemRefs(MMOBegin, MMOEnd);
16266 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16271 // Emit code to use overflow area
16274 // Load the overflow_area address into a register.
16275 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16276 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16281 .addOperand(Segment)
16282 .setMemRefs(MMOBegin, MMOEnd);
16284 // If we need to align it, do so. Otherwise, just copy the address
16285 // to OverflowDestReg.
16287 // Align the overflow address
16288 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16289 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16291 // aligned_addr = (addr + (align-1)) & ~(align-1)
16292 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16293 .addReg(OverflowAddrReg)
16296 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16298 .addImm(~(uint64_t)(Align-1));
16300 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16301 .addReg(OverflowAddrReg);
16304 // Compute the next overflow address after this argument.
16305 // (the overflow address should be kept 8-byte aligned)
16306 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16307 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16308 .addReg(OverflowDestReg)
16309 .addImm(ArgSizeA8);
16311 // Store the new overflow address.
16312 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16317 .addOperand(Segment)
16318 .addReg(NextAddrReg)
16319 .setMemRefs(MMOBegin, MMOEnd);
16321 // If we branched, emit the PHI to the front of endMBB.
16323 BuildMI(*endMBB, endMBB->begin(), DL,
16324 TII->get(X86::PHI), DestReg)
16325 .addReg(OffsetDestReg).addMBB(offsetMBB)
16326 .addReg(OverflowDestReg).addMBB(overflowMBB);
16329 // Erase the pseudo instruction
16330 MI->eraseFromParent();
16335 MachineBasicBlock *
16336 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16338 MachineBasicBlock *MBB) const {
16339 // Emit code to save XMM registers to the stack. The ABI says that the
16340 // number of registers to save is given in %al, so it's theoretically
16341 // possible to do an indirect jump trick to avoid saving all of them,
16342 // however this code takes a simpler approach and just executes all
16343 // of the stores if %al is non-zero. It's less code, and it's probably
16344 // easier on the hardware branch predictor, and stores aren't all that
16345 // expensive anyway.
16347 // Create the new basic blocks. One block contains all the XMM stores,
16348 // and one block is the final destination regardless of whether any
16349 // stores were performed.
16350 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16351 MachineFunction *F = MBB->getParent();
16352 MachineFunction::iterator MBBIter = MBB;
16354 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16355 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16356 F->insert(MBBIter, XMMSaveMBB);
16357 F->insert(MBBIter, EndMBB);
16359 // Transfer the remainder of MBB and its successor edges to EndMBB.
16360 EndMBB->splice(EndMBB->begin(), MBB,
16361 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16362 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16364 // The original block will now fall through to the XMM save block.
16365 MBB->addSuccessor(XMMSaveMBB);
16366 // The XMMSaveMBB will fall through to the end block.
16367 XMMSaveMBB->addSuccessor(EndMBB);
16369 // Now add the instructions.
16370 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16371 DebugLoc DL = MI->getDebugLoc();
16373 unsigned CountReg = MI->getOperand(0).getReg();
16374 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16375 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16377 if (!Subtarget->isTargetWin64()) {
16378 // If %al is 0, branch around the XMM save block.
16379 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16380 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16381 MBB->addSuccessor(EndMBB);
16384 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16385 // that was just emitted, but clearly shouldn't be "saved".
16386 assert((MI->getNumOperands() <= 3 ||
16387 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16388 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16389 && "Expected last argument to be EFLAGS");
16390 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16391 // In the XMM save block, save all the XMM argument registers.
16392 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16393 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16394 MachineMemOperand *MMO =
16395 F->getMachineMemOperand(
16396 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16397 MachineMemOperand::MOStore,
16398 /*Size=*/16, /*Align=*/16);
16399 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16400 .addFrameIndex(RegSaveFrameIndex)
16401 .addImm(/*Scale=*/1)
16402 .addReg(/*IndexReg=*/0)
16403 .addImm(/*Disp=*/Offset)
16404 .addReg(/*Segment=*/0)
16405 .addReg(MI->getOperand(i).getReg())
16406 .addMemOperand(MMO);
16409 MI->eraseFromParent(); // The pseudo instruction is gone now.
16414 // The EFLAGS operand of SelectItr might be missing a kill marker
16415 // because there were multiple uses of EFLAGS, and ISel didn't know
16416 // which to mark. Figure out whether SelectItr should have had a
16417 // kill marker, and set it if it should. Returns the correct kill
16419 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16420 MachineBasicBlock* BB,
16421 const TargetRegisterInfo* TRI) {
16422 // Scan forward through BB for a use/def of EFLAGS.
16423 MachineBasicBlock::iterator miI(std::next(SelectItr));
16424 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16425 const MachineInstr& mi = *miI;
16426 if (mi.readsRegister(X86::EFLAGS))
16428 if (mi.definesRegister(X86::EFLAGS))
16429 break; // Should have kill-flag - update below.
16432 // If we hit the end of the block, check whether EFLAGS is live into a
16434 if (miI == BB->end()) {
16435 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16436 sEnd = BB->succ_end();
16437 sItr != sEnd; ++sItr) {
16438 MachineBasicBlock* succ = *sItr;
16439 if (succ->isLiveIn(X86::EFLAGS))
16444 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16445 // out. SelectMI should have a kill flag on EFLAGS.
16446 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16450 MachineBasicBlock *
16451 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16452 MachineBasicBlock *BB) const {
16453 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16454 DebugLoc DL = MI->getDebugLoc();
16456 // To "insert" a SELECT_CC instruction, we actually have to insert the
16457 // diamond control-flow pattern. The incoming instruction knows the
16458 // destination vreg to set, the condition code register to branch on, the
16459 // true/false values to select between, and a branch opcode to use.
16460 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16461 MachineFunction::iterator It = BB;
16467 // cmpTY ccX, r1, r2
16469 // fallthrough --> copy0MBB
16470 MachineBasicBlock *thisMBB = BB;
16471 MachineFunction *F = BB->getParent();
16472 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16473 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16474 F->insert(It, copy0MBB);
16475 F->insert(It, sinkMBB);
16477 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16478 // live into the sink and copy blocks.
16479 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16480 if (!MI->killsRegister(X86::EFLAGS) &&
16481 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16482 copy0MBB->addLiveIn(X86::EFLAGS);
16483 sinkMBB->addLiveIn(X86::EFLAGS);
16486 // Transfer the remainder of BB and its successor edges to sinkMBB.
16487 sinkMBB->splice(sinkMBB->begin(), BB,
16488 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16489 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16491 // Add the true and fallthrough blocks as its successors.
16492 BB->addSuccessor(copy0MBB);
16493 BB->addSuccessor(sinkMBB);
16495 // Create the conditional branch instruction.
16497 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16498 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16501 // %FalseValue = ...
16502 // # fallthrough to sinkMBB
16503 copy0MBB->addSuccessor(sinkMBB);
16506 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16508 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16509 TII->get(X86::PHI), MI->getOperand(0).getReg())
16510 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16511 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16513 MI->eraseFromParent(); // The pseudo instruction is gone now.
16517 MachineBasicBlock *
16518 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16519 bool Is64Bit) const {
16520 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16521 DebugLoc DL = MI->getDebugLoc();
16522 MachineFunction *MF = BB->getParent();
16523 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16525 assert(MF->shouldSplitStack());
16527 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16528 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16531 // ... [Till the alloca]
16532 // If stacklet is not large enough, jump to mallocMBB
16535 // Allocate by subtracting from RSP
16536 // Jump to continueMBB
16539 // Allocate by call to runtime
16543 // [rest of original BB]
16546 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16547 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16548 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16550 MachineRegisterInfo &MRI = MF->getRegInfo();
16551 const TargetRegisterClass *AddrRegClass =
16552 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16554 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16555 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16556 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16557 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16558 sizeVReg = MI->getOperand(1).getReg(),
16559 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16561 MachineFunction::iterator MBBIter = BB;
16564 MF->insert(MBBIter, bumpMBB);
16565 MF->insert(MBBIter, mallocMBB);
16566 MF->insert(MBBIter, continueMBB);
16568 continueMBB->splice(continueMBB->begin(), BB,
16569 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16570 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16572 // Add code to the main basic block to check if the stack limit has been hit,
16573 // and if so, jump to mallocMBB otherwise to bumpMBB.
16574 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16575 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16576 .addReg(tmpSPVReg).addReg(sizeVReg);
16577 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16578 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16579 .addReg(SPLimitVReg);
16580 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16582 // bumpMBB simply decreases the stack pointer, since we know the current
16583 // stacklet has enough space.
16584 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16585 .addReg(SPLimitVReg);
16586 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16587 .addReg(SPLimitVReg);
16588 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16590 // Calls into a routine in libgcc to allocate more space from the heap.
16591 const uint32_t *RegMask =
16592 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16594 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16596 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16597 .addExternalSymbol("__morestack_allocate_stack_space")
16598 .addRegMask(RegMask)
16599 .addReg(X86::RDI, RegState::Implicit)
16600 .addReg(X86::RAX, RegState::ImplicitDefine);
16602 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16604 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16605 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16606 .addExternalSymbol("__morestack_allocate_stack_space")
16607 .addRegMask(RegMask)
16608 .addReg(X86::EAX, RegState::ImplicitDefine);
16612 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16615 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16616 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16617 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16619 // Set up the CFG correctly.
16620 BB->addSuccessor(bumpMBB);
16621 BB->addSuccessor(mallocMBB);
16622 mallocMBB->addSuccessor(continueMBB);
16623 bumpMBB->addSuccessor(continueMBB);
16625 // Take care of the PHI nodes.
16626 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16627 MI->getOperand(0).getReg())
16628 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16629 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16631 // Delete the original pseudo instruction.
16632 MI->eraseFromParent();
16635 return continueMBB;
16638 MachineBasicBlock *
16639 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16640 MachineBasicBlock *BB) const {
16641 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16642 DebugLoc DL = MI->getDebugLoc();
16644 assert(!Subtarget->isTargetMacho());
16646 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16647 // non-trivial part is impdef of ESP.
16649 if (Subtarget->isTargetWin64()) {
16650 if (Subtarget->isTargetCygMing()) {
16651 // ___chkstk(Mingw64):
16652 // Clobbers R10, R11, RAX and EFLAGS.
16654 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16655 .addExternalSymbol("___chkstk")
16656 .addReg(X86::RAX, RegState::Implicit)
16657 .addReg(X86::RSP, RegState::Implicit)
16658 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16659 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16660 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16662 // __chkstk(MSVCRT): does not update stack pointer.
16663 // Clobbers R10, R11 and EFLAGS.
16664 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16665 .addExternalSymbol("__chkstk")
16666 .addReg(X86::RAX, RegState::Implicit)
16667 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16668 // RAX has the offset to be subtracted from RSP.
16669 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16674 const char *StackProbeSymbol =
16675 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16677 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16678 .addExternalSymbol(StackProbeSymbol)
16679 .addReg(X86::EAX, RegState::Implicit)
16680 .addReg(X86::ESP, RegState::Implicit)
16681 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16682 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16683 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16686 MI->eraseFromParent(); // The pseudo instruction is gone now.
16690 MachineBasicBlock *
16691 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16692 MachineBasicBlock *BB) const {
16693 // This is pretty easy. We're taking the value that we received from
16694 // our load from the relocation, sticking it in either RDI (x86-64)
16695 // or EAX and doing an indirect call. The return value will then
16696 // be in the normal return register.
16697 const X86InstrInfo *TII
16698 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16699 DebugLoc DL = MI->getDebugLoc();
16700 MachineFunction *F = BB->getParent();
16702 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16703 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16705 // Get a register mask for the lowered call.
16706 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16707 // proper register mask.
16708 const uint32_t *RegMask =
16709 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16710 if (Subtarget->is64Bit()) {
16711 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16712 TII->get(X86::MOV64rm), X86::RDI)
16714 .addImm(0).addReg(0)
16715 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16716 MI->getOperand(3).getTargetFlags())
16718 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16719 addDirectMem(MIB, X86::RDI);
16720 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16721 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16722 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16723 TII->get(X86::MOV32rm), X86::EAX)
16725 .addImm(0).addReg(0)
16726 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16727 MI->getOperand(3).getTargetFlags())
16729 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16730 addDirectMem(MIB, X86::EAX);
16731 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16733 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16734 TII->get(X86::MOV32rm), X86::EAX)
16735 .addReg(TII->getGlobalBaseReg(F))
16736 .addImm(0).addReg(0)
16737 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16738 MI->getOperand(3).getTargetFlags())
16740 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16741 addDirectMem(MIB, X86::EAX);
16742 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16745 MI->eraseFromParent(); // The pseudo instruction is gone now.
16749 MachineBasicBlock *
16750 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16751 MachineBasicBlock *MBB) const {
16752 DebugLoc DL = MI->getDebugLoc();
16753 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16755 MachineFunction *MF = MBB->getParent();
16756 MachineRegisterInfo &MRI = MF->getRegInfo();
16758 const BasicBlock *BB = MBB->getBasicBlock();
16759 MachineFunction::iterator I = MBB;
16762 // Memory Reference
16763 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16764 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16767 unsigned MemOpndSlot = 0;
16769 unsigned CurOp = 0;
16771 DstReg = MI->getOperand(CurOp++).getReg();
16772 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16773 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16774 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16775 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16777 MemOpndSlot = CurOp;
16779 MVT PVT = getPointerTy();
16780 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16781 "Invalid Pointer Size!");
16783 // For v = setjmp(buf), we generate
16786 // buf[LabelOffset] = restoreMBB
16787 // SjLjSetup restoreMBB
16793 // v = phi(main, restore)
16798 MachineBasicBlock *thisMBB = MBB;
16799 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16800 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16801 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16802 MF->insert(I, mainMBB);
16803 MF->insert(I, sinkMBB);
16804 MF->push_back(restoreMBB);
16806 MachineInstrBuilder MIB;
16808 // Transfer the remainder of BB and its successor edges to sinkMBB.
16809 sinkMBB->splice(sinkMBB->begin(), MBB,
16810 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16811 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16814 unsigned PtrStoreOpc = 0;
16815 unsigned LabelReg = 0;
16816 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16817 Reloc::Model RM = getTargetMachine().getRelocationModel();
16818 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16819 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16821 // Prepare IP either in reg or imm.
16822 if (!UseImmLabel) {
16823 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16824 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16825 LabelReg = MRI.createVirtualRegister(PtrRC);
16826 if (Subtarget->is64Bit()) {
16827 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16831 .addMBB(restoreMBB)
16834 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16835 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16836 .addReg(XII->getGlobalBaseReg(MF))
16839 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16843 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16845 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16846 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16847 if (i == X86::AddrDisp)
16848 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16850 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16853 MIB.addReg(LabelReg);
16855 MIB.addMBB(restoreMBB);
16856 MIB.setMemRefs(MMOBegin, MMOEnd);
16858 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16859 .addMBB(restoreMBB);
16861 const X86RegisterInfo *RegInfo =
16862 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16863 MIB.addRegMask(RegInfo->getNoPreservedMask());
16864 thisMBB->addSuccessor(mainMBB);
16865 thisMBB->addSuccessor(restoreMBB);
16869 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16870 mainMBB->addSuccessor(sinkMBB);
16873 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16874 TII->get(X86::PHI), DstReg)
16875 .addReg(mainDstReg).addMBB(mainMBB)
16876 .addReg(restoreDstReg).addMBB(restoreMBB);
16879 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16880 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16881 restoreMBB->addSuccessor(sinkMBB);
16883 MI->eraseFromParent();
16887 MachineBasicBlock *
16888 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16889 MachineBasicBlock *MBB) const {
16890 DebugLoc DL = MI->getDebugLoc();
16891 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16893 MachineFunction *MF = MBB->getParent();
16894 MachineRegisterInfo &MRI = MF->getRegInfo();
16896 // Memory Reference
16897 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16898 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16900 MVT PVT = getPointerTy();
16901 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16902 "Invalid Pointer Size!");
16904 const TargetRegisterClass *RC =
16905 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16906 unsigned Tmp = MRI.createVirtualRegister(RC);
16907 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16908 const X86RegisterInfo *RegInfo =
16909 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16910 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16911 unsigned SP = RegInfo->getStackRegister();
16913 MachineInstrBuilder MIB;
16915 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16916 const int64_t SPOffset = 2 * PVT.getStoreSize();
16918 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16919 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16922 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16923 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16924 MIB.addOperand(MI->getOperand(i));
16925 MIB.setMemRefs(MMOBegin, MMOEnd);
16927 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16928 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16929 if (i == X86::AddrDisp)
16930 MIB.addDisp(MI->getOperand(i), LabelOffset);
16932 MIB.addOperand(MI->getOperand(i));
16934 MIB.setMemRefs(MMOBegin, MMOEnd);
16936 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16937 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16938 if (i == X86::AddrDisp)
16939 MIB.addDisp(MI->getOperand(i), SPOffset);
16941 MIB.addOperand(MI->getOperand(i));
16943 MIB.setMemRefs(MMOBegin, MMOEnd);
16945 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16947 MI->eraseFromParent();
16951 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16952 // accumulator loops. Writing back to the accumulator allows the coalescer
16953 // to remove extra copies in the loop.
16954 MachineBasicBlock *
16955 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16956 MachineBasicBlock *MBB) const {
16957 MachineOperand &AddendOp = MI->getOperand(3);
16959 // Bail out early if the addend isn't a register - we can't switch these.
16960 if (!AddendOp.isReg())
16963 MachineFunction &MF = *MBB->getParent();
16964 MachineRegisterInfo &MRI = MF.getRegInfo();
16966 // Check whether the addend is defined by a PHI:
16967 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16968 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16969 if (!AddendDef.isPHI())
16972 // Look for the following pattern:
16974 // %addend = phi [%entry, 0], [%loop, %result]
16976 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16980 // %addend = phi [%entry, 0], [%loop, %result]
16982 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16984 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16985 assert(AddendDef.getOperand(i).isReg());
16986 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16987 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16988 if (&PHISrcInst == MI) {
16989 // Found a matching instruction.
16990 unsigned NewFMAOpc = 0;
16991 switch (MI->getOpcode()) {
16992 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16993 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16994 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16995 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16996 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16997 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16998 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16999 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17000 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17001 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17002 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17003 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17004 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17005 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17006 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17007 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17008 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17009 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17010 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17011 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17012 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17013 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17014 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17015 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17016 default: llvm_unreachable("Unrecognized FMA variant.");
17019 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17020 MachineInstrBuilder MIB =
17021 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17022 .addOperand(MI->getOperand(0))
17023 .addOperand(MI->getOperand(3))
17024 .addOperand(MI->getOperand(2))
17025 .addOperand(MI->getOperand(1));
17026 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17027 MI->eraseFromParent();
17034 MachineBasicBlock *
17035 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17036 MachineBasicBlock *BB) const {
17037 switch (MI->getOpcode()) {
17038 default: llvm_unreachable("Unexpected instr type to insert");
17039 case X86::TAILJMPd64:
17040 case X86::TAILJMPr64:
17041 case X86::TAILJMPm64:
17042 llvm_unreachable("TAILJMP64 would not be touched here.");
17043 case X86::TCRETURNdi64:
17044 case X86::TCRETURNri64:
17045 case X86::TCRETURNmi64:
17047 case X86::WIN_ALLOCA:
17048 return EmitLoweredWinAlloca(MI, BB);
17049 case X86::SEG_ALLOCA_32:
17050 return EmitLoweredSegAlloca(MI, BB, false);
17051 case X86::SEG_ALLOCA_64:
17052 return EmitLoweredSegAlloca(MI, BB, true);
17053 case X86::TLSCall_32:
17054 case X86::TLSCall_64:
17055 return EmitLoweredTLSCall(MI, BB);
17056 case X86::CMOV_GR8:
17057 case X86::CMOV_FR32:
17058 case X86::CMOV_FR64:
17059 case X86::CMOV_V4F32:
17060 case X86::CMOV_V2F64:
17061 case X86::CMOV_V2I64:
17062 case X86::CMOV_V8F32:
17063 case X86::CMOV_V4F64:
17064 case X86::CMOV_V4I64:
17065 case X86::CMOV_V16F32:
17066 case X86::CMOV_V8F64:
17067 case X86::CMOV_V8I64:
17068 case X86::CMOV_GR16:
17069 case X86::CMOV_GR32:
17070 case X86::CMOV_RFP32:
17071 case X86::CMOV_RFP64:
17072 case X86::CMOV_RFP80:
17073 return EmitLoweredSelect(MI, BB);
17075 case X86::FP32_TO_INT16_IN_MEM:
17076 case X86::FP32_TO_INT32_IN_MEM:
17077 case X86::FP32_TO_INT64_IN_MEM:
17078 case X86::FP64_TO_INT16_IN_MEM:
17079 case X86::FP64_TO_INT32_IN_MEM:
17080 case X86::FP64_TO_INT64_IN_MEM:
17081 case X86::FP80_TO_INT16_IN_MEM:
17082 case X86::FP80_TO_INT32_IN_MEM:
17083 case X86::FP80_TO_INT64_IN_MEM: {
17084 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17085 DebugLoc DL = MI->getDebugLoc();
17087 // Change the floating point control register to use "round towards zero"
17088 // mode when truncating to an integer value.
17089 MachineFunction *F = BB->getParent();
17090 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17091 addFrameReference(BuildMI(*BB, MI, DL,
17092 TII->get(X86::FNSTCW16m)), CWFrameIdx);
17094 // Load the old value of the high byte of the control word...
17096 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17097 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17100 // Set the high part to be round to zero...
17101 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17104 // Reload the modified control word now...
17105 addFrameReference(BuildMI(*BB, MI, DL,
17106 TII->get(X86::FLDCW16m)), CWFrameIdx);
17108 // Restore the memory image of control word to original value
17109 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17112 // Get the X86 opcode to use.
17114 switch (MI->getOpcode()) {
17115 default: llvm_unreachable("illegal opcode!");
17116 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17117 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17118 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17119 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17120 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17121 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17122 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17123 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17124 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17128 MachineOperand &Op = MI->getOperand(0);
17130 AM.BaseType = X86AddressMode::RegBase;
17131 AM.Base.Reg = Op.getReg();
17133 AM.BaseType = X86AddressMode::FrameIndexBase;
17134 AM.Base.FrameIndex = Op.getIndex();
17136 Op = MI->getOperand(1);
17138 AM.Scale = Op.getImm();
17139 Op = MI->getOperand(2);
17141 AM.IndexReg = Op.getImm();
17142 Op = MI->getOperand(3);
17143 if (Op.isGlobal()) {
17144 AM.GV = Op.getGlobal();
17146 AM.Disp = Op.getImm();
17148 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17149 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17151 // Reload the original control word now.
17152 addFrameReference(BuildMI(*BB, MI, DL,
17153 TII->get(X86::FLDCW16m)), CWFrameIdx);
17155 MI->eraseFromParent(); // The pseudo instruction is gone now.
17158 // String/text processing lowering.
17159 case X86::PCMPISTRM128REG:
17160 case X86::VPCMPISTRM128REG:
17161 case X86::PCMPISTRM128MEM:
17162 case X86::VPCMPISTRM128MEM:
17163 case X86::PCMPESTRM128REG:
17164 case X86::VPCMPESTRM128REG:
17165 case X86::PCMPESTRM128MEM:
17166 case X86::VPCMPESTRM128MEM:
17167 assert(Subtarget->hasSSE42() &&
17168 "Target must have SSE4.2 or AVX features enabled");
17169 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17171 // String/text processing lowering.
17172 case X86::PCMPISTRIREG:
17173 case X86::VPCMPISTRIREG:
17174 case X86::PCMPISTRIMEM:
17175 case X86::VPCMPISTRIMEM:
17176 case X86::PCMPESTRIREG:
17177 case X86::VPCMPESTRIREG:
17178 case X86::PCMPESTRIMEM:
17179 case X86::VPCMPESTRIMEM:
17180 assert(Subtarget->hasSSE42() &&
17181 "Target must have SSE4.2 or AVX features enabled");
17182 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17184 // Thread synchronization.
17186 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17190 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17192 // Atomic Lowering.
17193 case X86::ATOMAND8:
17194 case X86::ATOMAND16:
17195 case X86::ATOMAND32:
17196 case X86::ATOMAND64:
17199 case X86::ATOMOR16:
17200 case X86::ATOMOR32:
17201 case X86::ATOMOR64:
17203 case X86::ATOMXOR16:
17204 case X86::ATOMXOR8:
17205 case X86::ATOMXOR32:
17206 case X86::ATOMXOR64:
17208 case X86::ATOMNAND8:
17209 case X86::ATOMNAND16:
17210 case X86::ATOMNAND32:
17211 case X86::ATOMNAND64:
17213 case X86::ATOMMAX8:
17214 case X86::ATOMMAX16:
17215 case X86::ATOMMAX32:
17216 case X86::ATOMMAX64:
17218 case X86::ATOMMIN8:
17219 case X86::ATOMMIN16:
17220 case X86::ATOMMIN32:
17221 case X86::ATOMMIN64:
17223 case X86::ATOMUMAX8:
17224 case X86::ATOMUMAX16:
17225 case X86::ATOMUMAX32:
17226 case X86::ATOMUMAX64:
17228 case X86::ATOMUMIN8:
17229 case X86::ATOMUMIN16:
17230 case X86::ATOMUMIN32:
17231 case X86::ATOMUMIN64:
17232 return EmitAtomicLoadArith(MI, BB);
17234 // This group does 64-bit operations on a 32-bit host.
17235 case X86::ATOMAND6432:
17236 case X86::ATOMOR6432:
17237 case X86::ATOMXOR6432:
17238 case X86::ATOMNAND6432:
17239 case X86::ATOMADD6432:
17240 case X86::ATOMSUB6432:
17241 case X86::ATOMMAX6432:
17242 case X86::ATOMMIN6432:
17243 case X86::ATOMUMAX6432:
17244 case X86::ATOMUMIN6432:
17245 case X86::ATOMSWAP6432:
17246 return EmitAtomicLoadArith6432(MI, BB);
17248 case X86::VASTART_SAVE_XMM_REGS:
17249 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17251 case X86::VAARG_64:
17252 return EmitVAARG64WithCustomInserter(MI, BB);
17254 case X86::EH_SjLj_SetJmp32:
17255 case X86::EH_SjLj_SetJmp64:
17256 return emitEHSjLjSetJmp(MI, BB);
17258 case X86::EH_SjLj_LongJmp32:
17259 case X86::EH_SjLj_LongJmp64:
17260 return emitEHSjLjLongJmp(MI, BB);
17262 case TargetOpcode::STACKMAP:
17263 case TargetOpcode::PATCHPOINT:
17264 return emitPatchPoint(MI, BB);
17266 case X86::VFMADDPDr213r:
17267 case X86::VFMADDPSr213r:
17268 case X86::VFMADDSDr213r:
17269 case X86::VFMADDSSr213r:
17270 case X86::VFMSUBPDr213r:
17271 case X86::VFMSUBPSr213r:
17272 case X86::VFMSUBSDr213r:
17273 case X86::VFMSUBSSr213r:
17274 case X86::VFNMADDPDr213r:
17275 case X86::VFNMADDPSr213r:
17276 case X86::VFNMADDSDr213r:
17277 case X86::VFNMADDSSr213r:
17278 case X86::VFNMSUBPDr213r:
17279 case X86::VFNMSUBPSr213r:
17280 case X86::VFNMSUBSDr213r:
17281 case X86::VFNMSUBSSr213r:
17282 case X86::VFMADDPDr213rY:
17283 case X86::VFMADDPSr213rY:
17284 case X86::VFMSUBPDr213rY:
17285 case X86::VFMSUBPSr213rY:
17286 case X86::VFNMADDPDr213rY:
17287 case X86::VFNMADDPSr213rY:
17288 case X86::VFNMSUBPDr213rY:
17289 case X86::VFNMSUBPSr213rY:
17290 return emitFMA3Instr(MI, BB);
17294 //===----------------------------------------------------------------------===//
17295 // X86 Optimization Hooks
17296 //===----------------------------------------------------------------------===//
17298 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17301 const SelectionDAG &DAG,
17302 unsigned Depth) const {
17303 unsigned BitWidth = KnownZero.getBitWidth();
17304 unsigned Opc = Op.getOpcode();
17305 assert((Opc >= ISD::BUILTIN_OP_END ||
17306 Opc == ISD::INTRINSIC_WO_CHAIN ||
17307 Opc == ISD::INTRINSIC_W_CHAIN ||
17308 Opc == ISD::INTRINSIC_VOID) &&
17309 "Should use MaskedValueIsZero if you don't know whether Op"
17310 " is a target node!");
17312 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17326 // These nodes' second result is a boolean.
17327 if (Op.getResNo() == 0)
17330 case X86ISD::SETCC:
17331 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17333 case ISD::INTRINSIC_WO_CHAIN: {
17334 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17335 unsigned NumLoBits = 0;
17338 case Intrinsic::x86_sse_movmsk_ps:
17339 case Intrinsic::x86_avx_movmsk_ps_256:
17340 case Intrinsic::x86_sse2_movmsk_pd:
17341 case Intrinsic::x86_avx_movmsk_pd_256:
17342 case Intrinsic::x86_mmx_pmovmskb:
17343 case Intrinsic::x86_sse2_pmovmskb_128:
17344 case Intrinsic::x86_avx2_pmovmskb: {
17345 // High bits of movmskp{s|d}, pmovmskb are known zero.
17347 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17348 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17349 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17350 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17351 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17352 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17353 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17354 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17356 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17365 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17367 const SelectionDAG &,
17368 unsigned Depth) const {
17369 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17370 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17371 return Op.getValueType().getScalarType().getSizeInBits();
17377 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17378 /// node is a GlobalAddress + offset.
17379 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17380 const GlobalValue* &GA,
17381 int64_t &Offset) const {
17382 if (N->getOpcode() == X86ISD::Wrapper) {
17383 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17384 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17385 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17389 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17392 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17393 /// same as extracting the high 128-bit part of 256-bit vector and then
17394 /// inserting the result into the low part of a new 256-bit vector
17395 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17396 EVT VT = SVOp->getValueType(0);
17397 unsigned NumElems = VT.getVectorNumElements();
17399 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17400 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17401 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17402 SVOp->getMaskElt(j) >= 0)
17408 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17409 /// same as extracting the low 128-bit part of 256-bit vector and then
17410 /// inserting the result into the high part of a new 256-bit vector
17411 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17412 EVT VT = SVOp->getValueType(0);
17413 unsigned NumElems = VT.getVectorNumElements();
17415 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17416 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17417 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17418 SVOp->getMaskElt(j) >= 0)
17424 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17425 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17426 TargetLowering::DAGCombinerInfo &DCI,
17427 const X86Subtarget* Subtarget) {
17429 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17430 SDValue V1 = SVOp->getOperand(0);
17431 SDValue V2 = SVOp->getOperand(1);
17432 EVT VT = SVOp->getValueType(0);
17433 unsigned NumElems = VT.getVectorNumElements();
17435 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17436 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17440 // V UNDEF BUILD_VECTOR UNDEF
17442 // CONCAT_VECTOR CONCAT_VECTOR
17445 // RESULT: V + zero extended
17447 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17448 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17449 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17452 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17455 // To match the shuffle mask, the first half of the mask should
17456 // be exactly the first vector, and all the rest a splat with the
17457 // first element of the second one.
17458 for (unsigned i = 0; i != NumElems/2; ++i)
17459 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17460 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17463 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17464 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17465 if (Ld->hasNUsesOfValue(1, 0)) {
17466 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17467 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17469 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17471 Ld->getPointerInfo(),
17472 Ld->getAlignment(),
17473 false/*isVolatile*/, true/*ReadMem*/,
17474 false/*WriteMem*/);
17476 // Make sure the newly-created LOAD is in the same position as Ld in
17477 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17478 // and update uses of Ld's output chain to use the TokenFactor.
17479 if (Ld->hasAnyUseOfValue(1)) {
17480 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17481 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17482 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17483 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17484 SDValue(ResNode.getNode(), 1));
17487 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17491 // Emit a zeroed vector and insert the desired subvector on its
17493 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17494 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17495 return DCI.CombineTo(N, InsV);
17498 //===--------------------------------------------------------------------===//
17499 // Combine some shuffles into subvector extracts and inserts:
17502 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17503 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17504 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17505 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17506 return DCI.CombineTo(N, InsV);
17509 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17510 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17511 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17512 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17513 return DCI.CombineTo(N, InsV);
17519 /// PerformShuffleCombine - Performs several different shuffle combines.
17520 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17521 TargetLowering::DAGCombinerInfo &DCI,
17522 const X86Subtarget *Subtarget) {
17524 SDValue N0 = N->getOperand(0);
17525 SDValue N1 = N->getOperand(1);
17526 EVT VT = N->getValueType(0);
17528 // Don't create instructions with illegal types after legalize types has run.
17529 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17530 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17533 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17534 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17535 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17536 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17538 // During Type Legalization, when promoting illegal vector types,
17539 // the backend might introduce new shuffle dag nodes and bitcasts.
17541 // This code performs the following transformation:
17542 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17543 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17545 // We do this only if both the bitcast and the BINOP dag nodes have
17546 // one use. Also, perform this transformation only if the new binary
17547 // operation is legal. This is to avoid introducing dag nodes that
17548 // potentially need to be further expanded (or custom lowered) into a
17549 // less optimal sequence of dag nodes.
17550 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17551 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17552 N0.getOpcode() == ISD::BITCAST) {
17553 SDValue BC0 = N0.getOperand(0);
17554 EVT SVT = BC0.getValueType();
17555 unsigned Opcode = BC0.getOpcode();
17556 unsigned NumElts = VT.getVectorNumElements();
17558 if (BC0.hasOneUse() && SVT.isVector() &&
17559 SVT.getVectorNumElements() * 2 == NumElts &&
17560 TLI.isOperationLegal(Opcode, VT)) {
17561 bool CanFold = false;
17573 unsigned SVTNumElts = SVT.getVectorNumElements();
17574 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17575 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17576 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17577 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17578 CanFold = SVOp->getMaskElt(i) < 0;
17581 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17582 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17583 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17584 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17589 // Only handle 128 wide vector from here on.
17590 if (!VT.is128BitVector())
17593 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17594 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17595 // consecutive, non-overlapping, and in the right order.
17596 SmallVector<SDValue, 16> Elts;
17597 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17598 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17600 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17603 /// PerformTruncateCombine - Converts truncate operation to
17604 /// a sequence of vector shuffle operations.
17605 /// It is possible when we truncate 256-bit vector to 128-bit vector
17606 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17607 TargetLowering::DAGCombinerInfo &DCI,
17608 const X86Subtarget *Subtarget) {
17612 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17613 /// specific shuffle of a load can be folded into a single element load.
17614 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17615 /// shuffles have been customed lowered so we need to handle those here.
17616 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17617 TargetLowering::DAGCombinerInfo &DCI) {
17618 if (DCI.isBeforeLegalizeOps())
17621 SDValue InVec = N->getOperand(0);
17622 SDValue EltNo = N->getOperand(1);
17624 if (!isa<ConstantSDNode>(EltNo))
17627 EVT VT = InVec.getValueType();
17629 bool HasShuffleIntoBitcast = false;
17630 if (InVec.getOpcode() == ISD::BITCAST) {
17631 // Don't duplicate a load with other uses.
17632 if (!InVec.hasOneUse())
17634 EVT BCVT = InVec.getOperand(0).getValueType();
17635 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17637 InVec = InVec.getOperand(0);
17638 HasShuffleIntoBitcast = true;
17641 if (!isTargetShuffle(InVec.getOpcode()))
17644 // Don't duplicate a load with other uses.
17645 if (!InVec.hasOneUse())
17648 SmallVector<int, 16> ShuffleMask;
17650 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17654 // Select the input vector, guarding against out of range extract vector.
17655 unsigned NumElems = VT.getVectorNumElements();
17656 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17657 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17658 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17659 : InVec.getOperand(1);
17661 // If inputs to shuffle are the same for both ops, then allow 2 uses
17662 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17664 if (LdNode.getOpcode() == ISD::BITCAST) {
17665 // Don't duplicate a load with other uses.
17666 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17669 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17670 LdNode = LdNode.getOperand(0);
17673 if (!ISD::isNormalLoad(LdNode.getNode()))
17676 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17678 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17681 if (HasShuffleIntoBitcast) {
17682 // If there's a bitcast before the shuffle, check if the load type and
17683 // alignment is valid.
17684 unsigned Align = LN0->getAlignment();
17685 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17686 unsigned NewAlign = TLI.getDataLayout()->
17687 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17689 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17693 // All checks match so transform back to vector_shuffle so that DAG combiner
17694 // can finish the job
17697 // Create shuffle node taking into account the case that its a unary shuffle
17698 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17699 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17700 InVec.getOperand(0), Shuffle,
17702 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17703 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17707 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17708 /// generation and convert it from being a bunch of shuffles and extracts
17709 /// to a simple store and scalar loads to extract the elements.
17710 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17711 TargetLowering::DAGCombinerInfo &DCI) {
17712 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17713 if (NewOp.getNode())
17716 SDValue InputVector = N->getOperand(0);
17718 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17719 // from mmx to v2i32 has a single usage.
17720 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17721 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17722 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17723 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17724 N->getValueType(0),
17725 InputVector.getNode()->getOperand(0));
17727 // Only operate on vectors of 4 elements, where the alternative shuffling
17728 // gets to be more expensive.
17729 if (InputVector.getValueType() != MVT::v4i32)
17732 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17733 // single use which is a sign-extend or zero-extend, and all elements are
17735 SmallVector<SDNode *, 4> Uses;
17736 unsigned ExtractedElements = 0;
17737 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17738 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17739 if (UI.getUse().getResNo() != InputVector.getResNo())
17742 SDNode *Extract = *UI;
17743 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17746 if (Extract->getValueType(0) != MVT::i32)
17748 if (!Extract->hasOneUse())
17750 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17751 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17753 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17756 // Record which element was extracted.
17757 ExtractedElements |=
17758 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17760 Uses.push_back(Extract);
17763 // If not all the elements were used, this may not be worthwhile.
17764 if (ExtractedElements != 15)
17767 // Ok, we've now decided to do the transformation.
17768 SDLoc dl(InputVector);
17770 // Store the value to a temporary stack slot.
17771 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17772 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17773 MachinePointerInfo(), false, false, 0);
17775 // Replace each use (extract) with a load of the appropriate element.
17776 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17777 UE = Uses.end(); UI != UE; ++UI) {
17778 SDNode *Extract = *UI;
17780 // cOMpute the element's address.
17781 SDValue Idx = Extract->getOperand(1);
17783 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17784 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17785 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17786 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17788 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17789 StackPtr, OffsetVal);
17791 // Load the scalar.
17792 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17793 ScalarAddr, MachinePointerInfo(),
17794 false, false, false, 0);
17796 // Replace the exact with the load.
17797 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17800 // The replacement was made in place; don't return anything.
17804 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17805 static std::pair<unsigned, bool>
17806 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17807 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17808 if (!VT.isVector())
17809 return std::make_pair(0, false);
17811 bool NeedSplit = false;
17812 switch (VT.getSimpleVT().SimpleTy) {
17813 default: return std::make_pair(0, false);
17817 if (!Subtarget->hasAVX2())
17819 if (!Subtarget->hasAVX())
17820 return std::make_pair(0, false);
17825 if (!Subtarget->hasSSE2())
17826 return std::make_pair(0, false);
17829 // SSE2 has only a small subset of the operations.
17830 bool hasUnsigned = Subtarget->hasSSE41() ||
17831 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17832 bool hasSigned = Subtarget->hasSSE41() ||
17833 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17835 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17838 // Check for x CC y ? x : y.
17839 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17840 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17845 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17848 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17851 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17854 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17856 // Check for x CC y ? y : x -- a min/max with reversed arms.
17857 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17858 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17863 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17866 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17869 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17872 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17876 return std::make_pair(Opc, NeedSplit);
17880 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
17881 const X86Subtarget *Subtarget) {
17883 SDValue Cond = N->getOperand(0);
17884 SDValue LHS = N->getOperand(1);
17885 SDValue RHS = N->getOperand(2);
17887 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
17888 SDValue CondSrc = Cond->getOperand(0);
17889 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
17890 Cond = CondSrc->getOperand(0);
17893 MVT VT = N->getSimpleValueType(0);
17894 MVT EltVT = VT.getVectorElementType();
17895 unsigned NumElems = VT.getVectorNumElements();
17896 // There is no blend with immediate in AVX-512.
17897 if (VT.is512BitVector())
17900 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
17902 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
17905 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
17908 unsigned MaskValue = 0;
17909 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
17912 SmallVector<int, 8> ShuffleMask(NumElems, -1);
17913 for (unsigned i = 0; i < NumElems; ++i) {
17914 // Be sure we emit undef where we can.
17915 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
17916 ShuffleMask[i] = -1;
17918 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
17921 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
17924 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17926 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17927 TargetLowering::DAGCombinerInfo &DCI,
17928 const X86Subtarget *Subtarget) {
17930 SDValue Cond = N->getOperand(0);
17931 // Get the LHS/RHS of the select.
17932 SDValue LHS = N->getOperand(1);
17933 SDValue RHS = N->getOperand(2);
17934 EVT VT = LHS.getValueType();
17935 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17937 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17938 // instructions match the semantics of the common C idiom x<y?x:y but not
17939 // x<=y?x:y, because of how they handle negative zero (which can be
17940 // ignored in unsafe-math mode).
17941 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17942 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17943 (Subtarget->hasSSE2() ||
17944 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17945 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17947 unsigned Opcode = 0;
17948 // Check for x CC y ? x : y.
17949 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17950 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17954 // Converting this to a min would handle NaNs incorrectly, and swapping
17955 // the operands would cause it to handle comparisons between positive
17956 // and negative zero incorrectly.
17957 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17958 if (!DAG.getTarget().Options.UnsafeFPMath &&
17959 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17961 std::swap(LHS, RHS);
17963 Opcode = X86ISD::FMIN;
17966 // Converting this to a min would handle comparisons between positive
17967 // and negative zero incorrectly.
17968 if (!DAG.getTarget().Options.UnsafeFPMath &&
17969 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17971 Opcode = X86ISD::FMIN;
17974 // Converting this to a min would handle both negative zeros and NaNs
17975 // incorrectly, but we can swap the operands to fix both.
17976 std::swap(LHS, RHS);
17980 Opcode = X86ISD::FMIN;
17984 // Converting this to a max would handle comparisons between positive
17985 // and negative zero incorrectly.
17986 if (!DAG.getTarget().Options.UnsafeFPMath &&
17987 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17989 Opcode = X86ISD::FMAX;
17992 // Converting this to a max would handle NaNs incorrectly, and swapping
17993 // the operands would cause it to handle comparisons between positive
17994 // and negative zero incorrectly.
17995 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17996 if (!DAG.getTarget().Options.UnsafeFPMath &&
17997 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17999 std::swap(LHS, RHS);
18001 Opcode = X86ISD::FMAX;
18004 // Converting this to a max would handle both negative zeros and NaNs
18005 // incorrectly, but we can swap the operands to fix both.
18006 std::swap(LHS, RHS);
18010 Opcode = X86ISD::FMAX;
18013 // Check for x CC y ? y : x -- a min/max with reversed arms.
18014 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18015 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18019 // Converting this to a min would handle comparisons between positive
18020 // and negative zero incorrectly, and swapping the operands would
18021 // cause it to handle NaNs incorrectly.
18022 if (!DAG.getTarget().Options.UnsafeFPMath &&
18023 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18024 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18026 std::swap(LHS, RHS);
18028 Opcode = X86ISD::FMIN;
18031 // Converting this to a min would handle NaNs incorrectly.
18032 if (!DAG.getTarget().Options.UnsafeFPMath &&
18033 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18035 Opcode = X86ISD::FMIN;
18038 // Converting this to a min would handle both negative zeros and NaNs
18039 // incorrectly, but we can swap the operands to fix both.
18040 std::swap(LHS, RHS);
18044 Opcode = X86ISD::FMIN;
18048 // Converting this to a max would handle NaNs incorrectly.
18049 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18051 Opcode = X86ISD::FMAX;
18054 // Converting this to a max would handle comparisons between positive
18055 // and negative zero incorrectly, and swapping the operands would
18056 // cause it to handle NaNs incorrectly.
18057 if (!DAG.getTarget().Options.UnsafeFPMath &&
18058 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18059 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18061 std::swap(LHS, RHS);
18063 Opcode = X86ISD::FMAX;
18066 // Converting this to a max would handle both negative zeros and NaNs
18067 // incorrectly, but we can swap the operands to fix both.
18068 std::swap(LHS, RHS);
18072 Opcode = X86ISD::FMAX;
18078 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18081 EVT CondVT = Cond.getValueType();
18082 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18083 CondVT.getVectorElementType() == MVT::i1) {
18084 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18085 // lowering on AVX-512. In this case we convert it to
18086 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18087 // The same situation for all 128 and 256-bit vectors of i8 and i16
18088 EVT OpVT = LHS.getValueType();
18089 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18090 (OpVT.getVectorElementType() == MVT::i8 ||
18091 OpVT.getVectorElementType() == MVT::i16)) {
18092 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18093 DCI.AddToWorklist(Cond.getNode());
18094 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18097 // If this is a select between two integer constants, try to do some
18099 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18100 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18101 // Don't do this for crazy integer types.
18102 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18103 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18104 // so that TrueC (the true value) is larger than FalseC.
18105 bool NeedsCondInvert = false;
18107 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18108 // Efficiently invertible.
18109 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
18110 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
18111 isa<ConstantSDNode>(Cond.getOperand(1))))) {
18112 NeedsCondInvert = true;
18113 std::swap(TrueC, FalseC);
18116 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
18117 if (FalseC->getAPIntValue() == 0 &&
18118 TrueC->getAPIntValue().isPowerOf2()) {
18119 if (NeedsCondInvert) // Invert the condition if needed.
18120 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18121 DAG.getConstant(1, Cond.getValueType()));
18123 // Zero extend the condition if needed.
18124 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18126 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18127 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18128 DAG.getConstant(ShAmt, MVT::i8));
18131 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18132 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18133 if (NeedsCondInvert) // Invert the condition if needed.
18134 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18135 DAG.getConstant(1, Cond.getValueType()));
18137 // Zero extend the condition if needed.
18138 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18139 FalseC->getValueType(0), Cond);
18140 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18141 SDValue(FalseC, 0));
18144 // Optimize cases that will turn into an LEA instruction. This requires
18145 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18146 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18147 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18148 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18150 bool isFastMultiplier = false;
18152 switch ((unsigned char)Diff) {
18154 case 1: // result = add base, cond
18155 case 2: // result = lea base( , cond*2)
18156 case 3: // result = lea base(cond, cond*2)
18157 case 4: // result = lea base( , cond*4)
18158 case 5: // result = lea base(cond, cond*4)
18159 case 8: // result = lea base( , cond*8)
18160 case 9: // result = lea base(cond, cond*8)
18161 isFastMultiplier = true;
18166 if (isFastMultiplier) {
18167 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18168 if (NeedsCondInvert) // Invert the condition if needed.
18169 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18170 DAG.getConstant(1, Cond.getValueType()));
18172 // Zero extend the condition if needed.
18173 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18175 // Scale the condition by the difference.
18177 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18178 DAG.getConstant(Diff, Cond.getValueType()));
18180 // Add the base if non-zero.
18181 if (FalseC->getAPIntValue() != 0)
18182 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18183 SDValue(FalseC, 0));
18190 // Canonicalize max and min:
18191 // (x > y) ? x : y -> (x >= y) ? x : y
18192 // (x < y) ? x : y -> (x <= y) ? x : y
18193 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18194 // the need for an extra compare
18195 // against zero. e.g.
18196 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18198 // testl %edi, %edi
18200 // cmovgl %edi, %eax
18204 // cmovsl %eax, %edi
18205 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18206 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18207 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18208 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18213 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18214 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18215 Cond.getOperand(0), Cond.getOperand(1), NewCC);
18216 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18221 // Early exit check
18222 if (!TLI.isTypeLegal(VT))
18225 // Match VSELECTs into subs with unsigned saturation.
18226 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18227 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18228 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18229 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18230 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18232 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18233 // left side invert the predicate to simplify logic below.
18235 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18237 CC = ISD::getSetCCInverse(CC, true);
18238 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18242 if (Other.getNode() && Other->getNumOperands() == 2 &&
18243 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18244 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18245 SDValue CondRHS = Cond->getOperand(1);
18247 // Look for a general sub with unsigned saturation first.
18248 // x >= y ? x-y : 0 --> subus x, y
18249 // x > y ? x-y : 0 --> subus x, y
18250 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18251 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18252 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18254 // If the RHS is a constant we have to reverse the const canonicalization.
18255 // x > C-1 ? x+-C : 0 --> subus x, C
18256 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18257 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18258 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18259 if (CondRHS.getConstantOperandVal(0) == -A-1)
18260 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18261 DAG.getConstant(-A, VT));
18264 // Another special case: If C was a sign bit, the sub has been
18265 // canonicalized into a xor.
18266 // FIXME: Would it be better to use computeKnownBits to determine whether
18267 // it's safe to decanonicalize the xor?
18268 // x s< 0 ? x^C : 0 --> subus x, C
18269 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18270 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18271 isSplatVector(OpRHS.getNode())) {
18272 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18274 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18279 // Try to match a min/max vector operation.
18280 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18281 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18282 unsigned Opc = ret.first;
18283 bool NeedSplit = ret.second;
18285 if (Opc && NeedSplit) {
18286 unsigned NumElems = VT.getVectorNumElements();
18287 // Extract the LHS vectors
18288 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18289 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18291 // Extract the RHS vectors
18292 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18293 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18295 // Create min/max for each subvector
18296 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18297 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18299 // Merge the result
18300 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18302 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18305 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18306 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18307 // Check if SETCC has already been promoted
18308 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18309 // Check that condition value type matches vselect operand type
18312 assert(Cond.getValueType().isVector() &&
18313 "vector select expects a vector selector!");
18315 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18316 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18318 if (!TValIsAllOnes && !FValIsAllZeros) {
18319 // Try invert the condition if true value is not all 1s and false value
18321 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18322 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18324 if (TValIsAllZeros || FValIsAllOnes) {
18325 SDValue CC = Cond.getOperand(2);
18326 ISD::CondCode NewCC =
18327 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18328 Cond.getOperand(0).getValueType().isInteger());
18329 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18330 std::swap(LHS, RHS);
18331 TValIsAllOnes = FValIsAllOnes;
18332 FValIsAllZeros = TValIsAllZeros;
18336 if (TValIsAllOnes || FValIsAllZeros) {
18339 if (TValIsAllOnes && FValIsAllZeros)
18341 else if (TValIsAllOnes)
18342 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18343 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18344 else if (FValIsAllZeros)
18345 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18346 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18348 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18352 // Try to fold this VSELECT into a MOVSS/MOVSD
18353 if (N->getOpcode() == ISD::VSELECT &&
18354 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18355 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18356 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18357 bool CanFold = false;
18358 unsigned NumElems = Cond.getNumOperands();
18362 if (isZero(Cond.getOperand(0))) {
18365 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18366 // fold (vselect <0,-1> -> (movsd A, B)
18367 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18368 CanFold = isAllOnes(Cond.getOperand(i));
18369 } else if (isAllOnes(Cond.getOperand(0))) {
18373 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18374 // fold (vselect <-1,0> -> (movsd B, A)
18375 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18376 CanFold = isZero(Cond.getOperand(i));
18380 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18381 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18382 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18385 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18386 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18387 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18388 // (v2i64 (bitcast B)))))
18390 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18391 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18392 // (v2f64 (bitcast B)))))
18394 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18395 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18396 // (v2i64 (bitcast A)))))
18398 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18399 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18400 // (v2f64 (bitcast A)))))
18402 CanFold = (isZero(Cond.getOperand(0)) &&
18403 isZero(Cond.getOperand(1)) &&
18404 isAllOnes(Cond.getOperand(2)) &&
18405 isAllOnes(Cond.getOperand(3)));
18407 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18408 isAllOnes(Cond.getOperand(1)) &&
18409 isZero(Cond.getOperand(2)) &&
18410 isZero(Cond.getOperand(3))) {
18412 std::swap(LHS, RHS);
18416 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18417 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18418 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18419 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18421 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18427 // If we know that this node is legal then we know that it is going to be
18428 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18429 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18430 // to simplify previous instructions.
18431 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18432 !DCI.isBeforeLegalize() &&
18433 // We explicitly check against v8i16 and v16i16 because, although
18434 // they're marked as Custom, they might only be legal when Cond is a
18435 // build_vector of constants. This will be taken care in a later
18437 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18438 VT != MVT::v8i16)) {
18439 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18441 // Don't optimize vector selects that map to mask-registers.
18445 // Check all uses of that condition operand to check whether it will be
18446 // consumed by non-BLEND instructions, which may depend on all bits are set
18448 for (SDNode::use_iterator I = Cond->use_begin(),
18449 E = Cond->use_end(); I != E; ++I)
18450 if (I->getOpcode() != ISD::VSELECT)
18451 // TODO: Add other opcodes eventually lowered into BLEND.
18454 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18455 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18457 APInt KnownZero, KnownOne;
18458 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18459 DCI.isBeforeLegalizeOps());
18460 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18461 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18462 DCI.CommitTargetLoweringOpt(TLO);
18465 // We should generate an X86ISD::BLENDI from a vselect if its argument
18466 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18467 // constants. This specific pattern gets generated when we split a
18468 // selector for a 512 bit vector in a machine without AVX512 (but with
18469 // 256-bit vectors), during legalization:
18471 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18473 // Iff we find this pattern and the build_vectors are built from
18474 // constants, we translate the vselect into a shuffle_vector that we
18475 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18476 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18477 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18478 if (Shuffle.getNode())
18485 // Check whether a boolean test is testing a boolean value generated by
18486 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18489 // Simplify the following patterns:
18490 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18491 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18492 // to (Op EFLAGS Cond)
18494 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18495 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18496 // to (Op EFLAGS !Cond)
18498 // where Op could be BRCOND or CMOV.
18500 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18501 // Quit if not CMP and SUB with its value result used.
18502 if (Cmp.getOpcode() != X86ISD::CMP &&
18503 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18506 // Quit if not used as a boolean value.
18507 if (CC != X86::COND_E && CC != X86::COND_NE)
18510 // Check CMP operands. One of them should be 0 or 1 and the other should be
18511 // an SetCC or extended from it.
18512 SDValue Op1 = Cmp.getOperand(0);
18513 SDValue Op2 = Cmp.getOperand(1);
18516 const ConstantSDNode* C = nullptr;
18517 bool needOppositeCond = (CC == X86::COND_E);
18518 bool checkAgainstTrue = false; // Is it a comparison against 1?
18520 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18522 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18524 else // Quit if all operands are not constants.
18527 if (C->getZExtValue() == 1) {
18528 needOppositeCond = !needOppositeCond;
18529 checkAgainstTrue = true;
18530 } else if (C->getZExtValue() != 0)
18531 // Quit if the constant is neither 0 or 1.
18534 bool truncatedToBoolWithAnd = false;
18535 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18536 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18537 SetCC.getOpcode() == ISD::TRUNCATE ||
18538 SetCC.getOpcode() == ISD::AND) {
18539 if (SetCC.getOpcode() == ISD::AND) {
18541 ConstantSDNode *CS;
18542 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18543 CS->getZExtValue() == 1)
18545 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18546 CS->getZExtValue() == 1)
18550 SetCC = SetCC.getOperand(OpIdx);
18551 truncatedToBoolWithAnd = true;
18553 SetCC = SetCC.getOperand(0);
18556 switch (SetCC.getOpcode()) {
18557 case X86ISD::SETCC_CARRY:
18558 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18559 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18560 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18561 // truncated to i1 using 'and'.
18562 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18564 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18565 "Invalid use of SETCC_CARRY!");
18567 case X86ISD::SETCC:
18568 // Set the condition code or opposite one if necessary.
18569 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18570 if (needOppositeCond)
18571 CC = X86::GetOppositeBranchCondition(CC);
18572 return SetCC.getOperand(1);
18573 case X86ISD::CMOV: {
18574 // Check whether false/true value has canonical one, i.e. 0 or 1.
18575 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18576 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18577 // Quit if true value is not a constant.
18580 // Quit if false value is not a constant.
18582 SDValue Op = SetCC.getOperand(0);
18583 // Skip 'zext' or 'trunc' node.
18584 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18585 Op.getOpcode() == ISD::TRUNCATE)
18586 Op = Op.getOperand(0);
18587 // A special case for rdrand/rdseed, where 0 is set if false cond is
18589 if ((Op.getOpcode() != X86ISD::RDRAND &&
18590 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18593 // Quit if false value is not the constant 0 or 1.
18594 bool FValIsFalse = true;
18595 if (FVal && FVal->getZExtValue() != 0) {
18596 if (FVal->getZExtValue() != 1)
18598 // If FVal is 1, opposite cond is needed.
18599 needOppositeCond = !needOppositeCond;
18600 FValIsFalse = false;
18602 // Quit if TVal is not the constant opposite of FVal.
18603 if (FValIsFalse && TVal->getZExtValue() != 1)
18605 if (!FValIsFalse && TVal->getZExtValue() != 0)
18607 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18608 if (needOppositeCond)
18609 CC = X86::GetOppositeBranchCondition(CC);
18610 return SetCC.getOperand(3);
18617 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18618 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18619 TargetLowering::DAGCombinerInfo &DCI,
18620 const X86Subtarget *Subtarget) {
18623 // If the flag operand isn't dead, don't touch this CMOV.
18624 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18627 SDValue FalseOp = N->getOperand(0);
18628 SDValue TrueOp = N->getOperand(1);
18629 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18630 SDValue Cond = N->getOperand(3);
18632 if (CC == X86::COND_E || CC == X86::COND_NE) {
18633 switch (Cond.getOpcode()) {
18637 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18638 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18639 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18645 Flags = checkBoolTestSetCCCombine(Cond, CC);
18646 if (Flags.getNode() &&
18647 // Extra check as FCMOV only supports a subset of X86 cond.
18648 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18649 SDValue Ops[] = { FalseOp, TrueOp,
18650 DAG.getConstant(CC, MVT::i8), Flags };
18651 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18654 // If this is a select between two integer constants, try to do some
18655 // optimizations. Note that the operands are ordered the opposite of SELECT
18657 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18658 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18659 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18660 // larger than FalseC (the false value).
18661 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18662 CC = X86::GetOppositeBranchCondition(CC);
18663 std::swap(TrueC, FalseC);
18664 std::swap(TrueOp, FalseOp);
18667 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18668 // This is efficient for any integer data type (including i8/i16) and
18670 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18671 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18672 DAG.getConstant(CC, MVT::i8), Cond);
18674 // Zero extend the condition if needed.
18675 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18677 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18678 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18679 DAG.getConstant(ShAmt, MVT::i8));
18680 if (N->getNumValues() == 2) // Dead flag value?
18681 return DCI.CombineTo(N, Cond, SDValue());
18685 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18686 // for any integer data type, including i8/i16.
18687 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18688 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18689 DAG.getConstant(CC, MVT::i8), Cond);
18691 // Zero extend the condition if needed.
18692 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18693 FalseC->getValueType(0), Cond);
18694 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18695 SDValue(FalseC, 0));
18697 if (N->getNumValues() == 2) // Dead flag value?
18698 return DCI.CombineTo(N, Cond, SDValue());
18702 // Optimize cases that will turn into an LEA instruction. This requires
18703 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18704 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18705 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18706 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18708 bool isFastMultiplier = false;
18710 switch ((unsigned char)Diff) {
18712 case 1: // result = add base, cond
18713 case 2: // result = lea base( , cond*2)
18714 case 3: // result = lea base(cond, cond*2)
18715 case 4: // result = lea base( , cond*4)
18716 case 5: // result = lea base(cond, cond*4)
18717 case 8: // result = lea base( , cond*8)
18718 case 9: // result = lea base(cond, cond*8)
18719 isFastMultiplier = true;
18724 if (isFastMultiplier) {
18725 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18726 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18727 DAG.getConstant(CC, MVT::i8), Cond);
18728 // Zero extend the condition if needed.
18729 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18731 // Scale the condition by the difference.
18733 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18734 DAG.getConstant(Diff, Cond.getValueType()));
18736 // Add the base if non-zero.
18737 if (FalseC->getAPIntValue() != 0)
18738 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18739 SDValue(FalseC, 0));
18740 if (N->getNumValues() == 2) // Dead flag value?
18741 return DCI.CombineTo(N, Cond, SDValue());
18748 // Handle these cases:
18749 // (select (x != c), e, c) -> select (x != c), e, x),
18750 // (select (x == c), c, e) -> select (x == c), x, e)
18751 // where the c is an integer constant, and the "select" is the combination
18752 // of CMOV and CMP.
18754 // The rationale for this change is that the conditional-move from a constant
18755 // needs two instructions, however, conditional-move from a register needs
18756 // only one instruction.
18758 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18759 // some instruction-combining opportunities. This opt needs to be
18760 // postponed as late as possible.
18762 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18763 // the DCI.xxxx conditions are provided to postpone the optimization as
18764 // late as possible.
18766 ConstantSDNode *CmpAgainst = nullptr;
18767 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18768 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18769 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18771 if (CC == X86::COND_NE &&
18772 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18773 CC = X86::GetOppositeBranchCondition(CC);
18774 std::swap(TrueOp, FalseOp);
18777 if (CC == X86::COND_E &&
18778 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18779 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18780 DAG.getConstant(CC, MVT::i8), Cond };
18781 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18789 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18790 const X86Subtarget *Subtarget) {
18791 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18793 default: return SDValue();
18794 // SSE/AVX/AVX2 blend intrinsics.
18795 case Intrinsic::x86_avx2_pblendvb:
18796 case Intrinsic::x86_avx2_pblendw:
18797 case Intrinsic::x86_avx2_pblendd_128:
18798 case Intrinsic::x86_avx2_pblendd_256:
18799 // Don't try to simplify this intrinsic if we don't have AVX2.
18800 if (!Subtarget->hasAVX2())
18803 case Intrinsic::x86_avx_blend_pd_256:
18804 case Intrinsic::x86_avx_blend_ps_256:
18805 case Intrinsic::x86_avx_blendv_pd_256:
18806 case Intrinsic::x86_avx_blendv_ps_256:
18807 // Don't try to simplify this intrinsic if we don't have AVX.
18808 if (!Subtarget->hasAVX())
18811 case Intrinsic::x86_sse41_pblendw:
18812 case Intrinsic::x86_sse41_blendpd:
18813 case Intrinsic::x86_sse41_blendps:
18814 case Intrinsic::x86_sse41_blendvps:
18815 case Intrinsic::x86_sse41_blendvpd:
18816 case Intrinsic::x86_sse41_pblendvb: {
18817 SDValue Op0 = N->getOperand(1);
18818 SDValue Op1 = N->getOperand(2);
18819 SDValue Mask = N->getOperand(3);
18821 // Don't try to simplify this intrinsic if we don't have SSE4.1.
18822 if (!Subtarget->hasSSE41())
18825 // fold (blend A, A, Mask) -> A
18828 // fold (blend A, B, allZeros) -> A
18829 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18831 // fold (blend A, B, allOnes) -> B
18832 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18835 // Simplify the case where the mask is a constant i32 value.
18836 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18837 if (C->isNullValue())
18839 if (C->isAllOnesValue())
18844 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18845 case Intrinsic::x86_sse2_psrai_w:
18846 case Intrinsic::x86_sse2_psrai_d:
18847 case Intrinsic::x86_avx2_psrai_w:
18848 case Intrinsic::x86_avx2_psrai_d:
18849 case Intrinsic::x86_sse2_psra_w:
18850 case Intrinsic::x86_sse2_psra_d:
18851 case Intrinsic::x86_avx2_psra_w:
18852 case Intrinsic::x86_avx2_psra_d: {
18853 SDValue Op0 = N->getOperand(1);
18854 SDValue Op1 = N->getOperand(2);
18855 EVT VT = Op0.getValueType();
18856 assert(VT.isVector() && "Expected a vector type!");
18858 if (isa<BuildVectorSDNode>(Op1))
18859 Op1 = Op1.getOperand(0);
18861 if (!isa<ConstantSDNode>(Op1))
18864 EVT SVT = VT.getVectorElementType();
18865 unsigned SVTBits = SVT.getSizeInBits();
18867 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18868 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18869 uint64_t ShAmt = C.getZExtValue();
18871 // Don't try to convert this shift into a ISD::SRA if the shift
18872 // count is bigger than or equal to the element size.
18873 if (ShAmt >= SVTBits)
18876 // Trivial case: if the shift count is zero, then fold this
18877 // into the first operand.
18881 // Replace this packed shift intrinsic with a target independent
18883 SDValue Splat = DAG.getConstant(C, VT);
18884 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18889 /// PerformMulCombine - Optimize a single multiply with constant into two
18890 /// in order to implement it with two cheaper instructions, e.g.
18891 /// LEA + SHL, LEA + LEA.
18892 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18893 TargetLowering::DAGCombinerInfo &DCI) {
18894 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18897 EVT VT = N->getValueType(0);
18898 if (VT != MVT::i64)
18901 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18904 uint64_t MulAmt = C->getZExtValue();
18905 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18908 uint64_t MulAmt1 = 0;
18909 uint64_t MulAmt2 = 0;
18910 if ((MulAmt % 9) == 0) {
18912 MulAmt2 = MulAmt / 9;
18913 } else if ((MulAmt % 5) == 0) {
18915 MulAmt2 = MulAmt / 5;
18916 } else if ((MulAmt % 3) == 0) {
18918 MulAmt2 = MulAmt / 3;
18921 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18924 if (isPowerOf2_64(MulAmt2) &&
18925 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18926 // If second multiplifer is pow2, issue it first. We want the multiply by
18927 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18929 std::swap(MulAmt1, MulAmt2);
18932 if (isPowerOf2_64(MulAmt1))
18933 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18934 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18936 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18937 DAG.getConstant(MulAmt1, VT));
18939 if (isPowerOf2_64(MulAmt2))
18940 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18941 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18943 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18944 DAG.getConstant(MulAmt2, VT));
18946 // Do not add new nodes to DAG combiner worklist.
18947 DCI.CombineTo(N, NewMul, false);
18952 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18953 SDValue N0 = N->getOperand(0);
18954 SDValue N1 = N->getOperand(1);
18955 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18956 EVT VT = N0.getValueType();
18958 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18959 // since the result of setcc_c is all zero's or all ones.
18960 if (VT.isInteger() && !VT.isVector() &&
18961 N1C && N0.getOpcode() == ISD::AND &&
18962 N0.getOperand(1).getOpcode() == ISD::Constant) {
18963 SDValue N00 = N0.getOperand(0);
18964 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18965 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18966 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18967 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18968 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18969 APInt ShAmt = N1C->getAPIntValue();
18970 Mask = Mask.shl(ShAmt);
18972 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18973 N00, DAG.getConstant(Mask, VT));
18977 // Hardware support for vector shifts is sparse which makes us scalarize the
18978 // vector operations in many cases. Also, on sandybridge ADD is faster than
18980 // (shl V, 1) -> add V,V
18981 if (isSplatVector(N1.getNode())) {
18982 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18983 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18984 // We shift all of the values by one. In many cases we do not have
18985 // hardware support for this operation. This is better expressed as an ADD
18987 if (N1C && (1 == N1C->getZExtValue())) {
18988 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18995 /// \brief Returns a vector of 0s if the node in input is a vector logical
18996 /// shift by a constant amount which is known to be bigger than or equal
18997 /// to the vector element size in bits.
18998 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18999 const X86Subtarget *Subtarget) {
19000 EVT VT = N->getValueType(0);
19002 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19003 (!Subtarget->hasInt256() ||
19004 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19007 SDValue Amt = N->getOperand(1);
19009 if (isSplatVector(Amt.getNode())) {
19010 SDValue SclrAmt = Amt->getOperand(0);
19011 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19012 APInt ShiftAmt = C->getAPIntValue();
19013 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19015 // SSE2/AVX2 logical shifts always return a vector of 0s
19016 // if the shift amount is bigger than or equal to
19017 // the element size. The constant shift amount will be
19018 // encoded as a 8-bit immediate.
19019 if (ShiftAmt.trunc(8).uge(MaxAmount))
19020 return getZeroVector(VT, Subtarget, DAG, DL);
19027 /// PerformShiftCombine - Combine shifts.
19028 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19029 TargetLowering::DAGCombinerInfo &DCI,
19030 const X86Subtarget *Subtarget) {
19031 if (N->getOpcode() == ISD::SHL) {
19032 SDValue V = PerformSHLCombine(N, DAG);
19033 if (V.getNode()) return V;
19036 if (N->getOpcode() != ISD::SRA) {
19037 // Try to fold this logical shift into a zero vector.
19038 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19039 if (V.getNode()) return V;
19045 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
19046 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19047 // and friends. Likewise for OR -> CMPNEQSS.
19048 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19049 TargetLowering::DAGCombinerInfo &DCI,
19050 const X86Subtarget *Subtarget) {
19053 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19054 // we're requiring SSE2 for both.
19055 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19056 SDValue N0 = N->getOperand(0);
19057 SDValue N1 = N->getOperand(1);
19058 SDValue CMP0 = N0->getOperand(1);
19059 SDValue CMP1 = N1->getOperand(1);
19062 // The SETCCs should both refer to the same CMP.
19063 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19066 SDValue CMP00 = CMP0->getOperand(0);
19067 SDValue CMP01 = CMP0->getOperand(1);
19068 EVT VT = CMP00.getValueType();
19070 if (VT == MVT::f32 || VT == MVT::f64) {
19071 bool ExpectingFlags = false;
19072 // Check for any users that want flags:
19073 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19074 !ExpectingFlags && UI != UE; ++UI)
19075 switch (UI->getOpcode()) {
19080 ExpectingFlags = true;
19082 case ISD::CopyToReg:
19083 case ISD::SIGN_EXTEND:
19084 case ISD::ZERO_EXTEND:
19085 case ISD::ANY_EXTEND:
19089 if (!ExpectingFlags) {
19090 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19091 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19093 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19094 X86::CondCode tmp = cc0;
19099 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
19100 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19101 // FIXME: need symbolic constants for these magic numbers.
19102 // See X86ATTInstPrinter.cpp:printSSECC().
19103 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19104 if (Subtarget->hasAVX512()) {
19105 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19106 CMP01, DAG.getConstant(x86cc, MVT::i8));
19107 if (N->getValueType(0) != MVT::i1)
19108 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19112 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19113 CMP00.getValueType(), CMP00, CMP01,
19114 DAG.getConstant(x86cc, MVT::i8));
19116 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19117 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19119 if (is64BitFP && !Subtarget->is64Bit()) {
19120 // On a 32-bit target, we cannot bitcast the 64-bit float to a
19121 // 64-bit integer, since that's not a legal type. Since
19122 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19123 // bits, but can do this little dance to extract the lowest 32 bits
19124 // and work with those going forward.
19125 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19127 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19129 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19130 Vector32, DAG.getIntPtrConstant(0));
19134 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19135 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19136 DAG.getConstant(1, IntVT));
19137 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19138 return OneBitOfTruth;
19146 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19147 /// so it can be folded inside ANDNP.
19148 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19149 EVT VT = N->getValueType(0);
19151 // Match direct AllOnes for 128 and 256-bit vectors
19152 if (ISD::isBuildVectorAllOnes(N))
19155 // Look through a bit convert.
19156 if (N->getOpcode() == ISD::BITCAST)
19157 N = N->getOperand(0).getNode();
19159 // Sometimes the operand may come from a insert_subvector building a 256-bit
19161 if (VT.is256BitVector() &&
19162 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19163 SDValue V1 = N->getOperand(0);
19164 SDValue V2 = N->getOperand(1);
19166 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19167 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19168 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19169 ISD::isBuildVectorAllOnes(V2.getNode()))
19176 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19177 // register. In most cases we actually compare or select YMM-sized registers
19178 // and mixing the two types creates horrible code. This method optimizes
19179 // some of the transition sequences.
19180 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19181 TargetLowering::DAGCombinerInfo &DCI,
19182 const X86Subtarget *Subtarget) {
19183 EVT VT = N->getValueType(0);
19184 if (!VT.is256BitVector())
19187 assert((N->getOpcode() == ISD::ANY_EXTEND ||
19188 N->getOpcode() == ISD::ZERO_EXTEND ||
19189 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19191 SDValue Narrow = N->getOperand(0);
19192 EVT NarrowVT = Narrow->getValueType(0);
19193 if (!NarrowVT.is128BitVector())
19196 if (Narrow->getOpcode() != ISD::XOR &&
19197 Narrow->getOpcode() != ISD::AND &&
19198 Narrow->getOpcode() != ISD::OR)
19201 SDValue N0 = Narrow->getOperand(0);
19202 SDValue N1 = Narrow->getOperand(1);
19205 // The Left side has to be a trunc.
19206 if (N0.getOpcode() != ISD::TRUNCATE)
19209 // The type of the truncated inputs.
19210 EVT WideVT = N0->getOperand(0)->getValueType(0);
19214 // The right side has to be a 'trunc' or a constant vector.
19215 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19216 bool RHSConst = (isSplatVector(N1.getNode()) &&
19217 isa<ConstantSDNode>(N1->getOperand(0)));
19218 if (!RHSTrunc && !RHSConst)
19221 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19223 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19226 // Set N0 and N1 to hold the inputs to the new wide operation.
19227 N0 = N0->getOperand(0);
19229 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19230 N1->getOperand(0));
19231 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19232 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19233 } else if (RHSTrunc) {
19234 N1 = N1->getOperand(0);
19237 // Generate the wide operation.
19238 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19239 unsigned Opcode = N->getOpcode();
19241 case ISD::ANY_EXTEND:
19243 case ISD::ZERO_EXTEND: {
19244 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19245 APInt Mask = APInt::getAllOnesValue(InBits);
19246 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19247 return DAG.getNode(ISD::AND, DL, VT,
19248 Op, DAG.getConstant(Mask, VT));
19250 case ISD::SIGN_EXTEND:
19251 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19252 Op, DAG.getValueType(NarrowVT));
19254 llvm_unreachable("Unexpected opcode");
19258 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19259 TargetLowering::DAGCombinerInfo &DCI,
19260 const X86Subtarget *Subtarget) {
19261 EVT VT = N->getValueType(0);
19262 if (DCI.isBeforeLegalizeOps())
19265 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19269 // Create BEXTR instructions
19270 // BEXTR is ((X >> imm) & (2**size-1))
19271 if (VT == MVT::i32 || VT == MVT::i64) {
19272 SDValue N0 = N->getOperand(0);
19273 SDValue N1 = N->getOperand(1);
19276 // Check for BEXTR.
19277 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19278 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19279 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19280 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19281 if (MaskNode && ShiftNode) {
19282 uint64_t Mask = MaskNode->getZExtValue();
19283 uint64_t Shift = ShiftNode->getZExtValue();
19284 if (isMask_64(Mask)) {
19285 uint64_t MaskSize = CountPopulation_64(Mask);
19286 if (Shift + MaskSize <= VT.getSizeInBits())
19287 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19288 DAG.getConstant(Shift | (MaskSize << 8), VT));
19296 // Want to form ANDNP nodes:
19297 // 1) In the hopes of then easily combining them with OR and AND nodes
19298 // to form PBLEND/PSIGN.
19299 // 2) To match ANDN packed intrinsics
19300 if (VT != MVT::v2i64 && VT != MVT::v4i64)
19303 SDValue N0 = N->getOperand(0);
19304 SDValue N1 = N->getOperand(1);
19307 // Check LHS for vnot
19308 if (N0.getOpcode() == ISD::XOR &&
19309 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19310 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19311 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19313 // Check RHS for vnot
19314 if (N1.getOpcode() == ISD::XOR &&
19315 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19316 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19317 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19322 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19323 TargetLowering::DAGCombinerInfo &DCI,
19324 const X86Subtarget *Subtarget) {
19325 if (DCI.isBeforeLegalizeOps())
19328 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19332 SDValue N0 = N->getOperand(0);
19333 SDValue N1 = N->getOperand(1);
19334 EVT VT = N->getValueType(0);
19336 // look for psign/blend
19337 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19338 if (!Subtarget->hasSSSE3() ||
19339 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19342 // Canonicalize pandn to RHS
19343 if (N0.getOpcode() == X86ISD::ANDNP)
19345 // or (and (m, y), (pandn m, x))
19346 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19347 SDValue Mask = N1.getOperand(0);
19348 SDValue X = N1.getOperand(1);
19350 if (N0.getOperand(0) == Mask)
19351 Y = N0.getOperand(1);
19352 if (N0.getOperand(1) == Mask)
19353 Y = N0.getOperand(0);
19355 // Check to see if the mask appeared in both the AND and ANDNP and
19359 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19360 // Look through mask bitcast.
19361 if (Mask.getOpcode() == ISD::BITCAST)
19362 Mask = Mask.getOperand(0);
19363 if (X.getOpcode() == ISD::BITCAST)
19364 X = X.getOperand(0);
19365 if (Y.getOpcode() == ISD::BITCAST)
19366 Y = Y.getOperand(0);
19368 EVT MaskVT = Mask.getValueType();
19370 // Validate that the Mask operand is a vector sra node.
19371 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19372 // there is no psrai.b
19373 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19374 unsigned SraAmt = ~0;
19375 if (Mask.getOpcode() == ISD::SRA) {
19376 SDValue Amt = Mask.getOperand(1);
19377 if (isSplatVector(Amt.getNode())) {
19378 SDValue SclrAmt = Amt->getOperand(0);
19379 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19380 SraAmt = C->getZExtValue();
19382 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19383 SDValue SraC = Mask.getOperand(1);
19384 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19386 if ((SraAmt + 1) != EltBits)
19391 // Now we know we at least have a plendvb with the mask val. See if
19392 // we can form a psignb/w/d.
19393 // psign = x.type == y.type == mask.type && y = sub(0, x);
19394 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19395 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19396 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19397 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19398 "Unsupported VT for PSIGN");
19399 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19400 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19402 // PBLENDVB only available on SSE 4.1
19403 if (!Subtarget->hasSSE41())
19406 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19408 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19409 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19410 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19411 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19412 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19416 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19419 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19420 MachineFunction &MF = DAG.getMachineFunction();
19421 bool OptForSize = MF.getFunction()->getAttributes().
19422 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19424 // SHLD/SHRD instructions have lower register pressure, but on some
19425 // platforms they have higher latency than the equivalent
19426 // series of shifts/or that would otherwise be generated.
19427 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19428 // have higher latencies and we are not optimizing for size.
19429 if (!OptForSize && Subtarget->isSHLDSlow())
19432 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19434 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19436 if (!N0.hasOneUse() || !N1.hasOneUse())
19439 SDValue ShAmt0 = N0.getOperand(1);
19440 if (ShAmt0.getValueType() != MVT::i8)
19442 SDValue ShAmt1 = N1.getOperand(1);
19443 if (ShAmt1.getValueType() != MVT::i8)
19445 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19446 ShAmt0 = ShAmt0.getOperand(0);
19447 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19448 ShAmt1 = ShAmt1.getOperand(0);
19451 unsigned Opc = X86ISD::SHLD;
19452 SDValue Op0 = N0.getOperand(0);
19453 SDValue Op1 = N1.getOperand(0);
19454 if (ShAmt0.getOpcode() == ISD::SUB) {
19455 Opc = X86ISD::SHRD;
19456 std::swap(Op0, Op1);
19457 std::swap(ShAmt0, ShAmt1);
19460 unsigned Bits = VT.getSizeInBits();
19461 if (ShAmt1.getOpcode() == ISD::SUB) {
19462 SDValue Sum = ShAmt1.getOperand(0);
19463 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19464 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19465 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19466 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19467 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19468 return DAG.getNode(Opc, DL, VT,
19470 DAG.getNode(ISD::TRUNCATE, DL,
19473 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19474 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19476 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19477 return DAG.getNode(Opc, DL, VT,
19478 N0.getOperand(0), N1.getOperand(0),
19479 DAG.getNode(ISD::TRUNCATE, DL,
19486 // Generate NEG and CMOV for integer abs.
19487 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19488 EVT VT = N->getValueType(0);
19490 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19491 // 8-bit integer abs to NEG and CMOV.
19492 if (VT.isInteger() && VT.getSizeInBits() == 8)
19495 SDValue N0 = N->getOperand(0);
19496 SDValue N1 = N->getOperand(1);
19499 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19500 // and change it to SUB and CMOV.
19501 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19502 N0.getOpcode() == ISD::ADD &&
19503 N0.getOperand(1) == N1 &&
19504 N1.getOpcode() == ISD::SRA &&
19505 N1.getOperand(0) == N0.getOperand(0))
19506 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19507 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19508 // Generate SUB & CMOV.
19509 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19510 DAG.getConstant(0, VT), N0.getOperand(0));
19512 SDValue Ops[] = { N0.getOperand(0), Neg,
19513 DAG.getConstant(X86::COND_GE, MVT::i8),
19514 SDValue(Neg.getNode(), 1) };
19515 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19520 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19521 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19522 TargetLowering::DAGCombinerInfo &DCI,
19523 const X86Subtarget *Subtarget) {
19524 if (DCI.isBeforeLegalizeOps())
19527 if (Subtarget->hasCMov()) {
19528 SDValue RV = performIntegerAbsCombine(N, DAG);
19536 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19537 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19538 TargetLowering::DAGCombinerInfo &DCI,
19539 const X86Subtarget *Subtarget) {
19540 LoadSDNode *Ld = cast<LoadSDNode>(N);
19541 EVT RegVT = Ld->getValueType(0);
19542 EVT MemVT = Ld->getMemoryVT();
19544 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19545 unsigned RegSz = RegVT.getSizeInBits();
19547 // On Sandybridge unaligned 256bit loads are inefficient.
19548 ISD::LoadExtType Ext = Ld->getExtensionType();
19549 unsigned Alignment = Ld->getAlignment();
19550 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19551 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19552 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19553 unsigned NumElems = RegVT.getVectorNumElements();
19557 SDValue Ptr = Ld->getBasePtr();
19558 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19560 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19562 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19563 Ld->getPointerInfo(), Ld->isVolatile(),
19564 Ld->isNonTemporal(), Ld->isInvariant(),
19566 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19567 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19568 Ld->getPointerInfo(), Ld->isVolatile(),
19569 Ld->isNonTemporal(), Ld->isInvariant(),
19570 std::min(16U, Alignment));
19571 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19573 Load2.getValue(1));
19575 SDValue NewVec = DAG.getUNDEF(RegVT);
19576 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19577 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19578 return DCI.CombineTo(N, NewVec, TF, true);
19581 // If this is a vector EXT Load then attempt to optimize it using a
19582 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19583 // expansion is still better than scalar code.
19584 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19585 // emit a shuffle and a arithmetic shift.
19586 // TODO: It is possible to support ZExt by zeroing the undef values
19587 // during the shuffle phase or after the shuffle.
19588 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19589 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19590 assert(MemVT != RegVT && "Cannot extend to the same type");
19591 assert(MemVT.isVector() && "Must load a vector from memory");
19593 unsigned NumElems = RegVT.getVectorNumElements();
19594 unsigned MemSz = MemVT.getSizeInBits();
19595 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19597 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19600 // All sizes must be a power of two.
19601 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19604 // Attempt to load the original value using scalar loads.
19605 // Find the largest scalar type that divides the total loaded size.
19606 MVT SclrLoadTy = MVT::i8;
19607 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19608 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19609 MVT Tp = (MVT::SimpleValueType)tp;
19610 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19615 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19616 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19618 SclrLoadTy = MVT::f64;
19620 // Calculate the number of scalar loads that we need to perform
19621 // in order to load our vector from memory.
19622 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19623 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19626 unsigned loadRegZize = RegSz;
19627 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19630 // Represent our vector as a sequence of elements which are the
19631 // largest scalar that we can load.
19632 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19633 loadRegZize/SclrLoadTy.getSizeInBits());
19635 // Represent the data using the same element type that is stored in
19636 // memory. In practice, we ''widen'' MemVT.
19638 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19639 loadRegZize/MemVT.getScalarType().getSizeInBits());
19641 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19642 "Invalid vector type");
19644 // We can't shuffle using an illegal type.
19645 if (!TLI.isTypeLegal(WideVecVT))
19648 SmallVector<SDValue, 8> Chains;
19649 SDValue Ptr = Ld->getBasePtr();
19650 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19651 TLI.getPointerTy());
19652 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19654 for (unsigned i = 0; i < NumLoads; ++i) {
19655 // Perform a single load.
19656 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19657 Ptr, Ld->getPointerInfo(),
19658 Ld->isVolatile(), Ld->isNonTemporal(),
19659 Ld->isInvariant(), Ld->getAlignment());
19660 Chains.push_back(ScalarLoad.getValue(1));
19661 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19662 // another round of DAGCombining.
19664 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19666 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19667 ScalarLoad, DAG.getIntPtrConstant(i));
19669 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19672 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19674 // Bitcast the loaded value to a vector of the original element type, in
19675 // the size of the target vector type.
19676 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19677 unsigned SizeRatio = RegSz/MemSz;
19679 if (Ext == ISD::SEXTLOAD) {
19680 // If we have SSE4.1 we can directly emit a VSEXT node.
19681 if (Subtarget->hasSSE41()) {
19682 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19683 return DCI.CombineTo(N, Sext, TF, true);
19686 // Otherwise we'll shuffle the small elements in the high bits of the
19687 // larger type and perform an arithmetic shift. If the shift is not legal
19688 // it's better to scalarize.
19689 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19692 // Redistribute the loaded elements into the different locations.
19693 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19694 for (unsigned i = 0; i != NumElems; ++i)
19695 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19697 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19698 DAG.getUNDEF(WideVecVT),
19701 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19703 // Build the arithmetic shift.
19704 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19705 MemVT.getVectorElementType().getSizeInBits();
19706 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19707 DAG.getConstant(Amt, RegVT));
19709 return DCI.CombineTo(N, Shuff, TF, true);
19712 // Redistribute the loaded elements into the different locations.
19713 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19714 for (unsigned i = 0; i != NumElems; ++i)
19715 ShuffleVec[i*SizeRatio] = i;
19717 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19718 DAG.getUNDEF(WideVecVT),
19721 // Bitcast to the requested type.
19722 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19723 // Replace the original load with the new sequence
19724 // and return the new chain.
19725 return DCI.CombineTo(N, Shuff, TF, true);
19731 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19732 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19733 const X86Subtarget *Subtarget) {
19734 StoreSDNode *St = cast<StoreSDNode>(N);
19735 EVT VT = St->getValue().getValueType();
19736 EVT StVT = St->getMemoryVT();
19738 SDValue StoredVal = St->getOperand(1);
19739 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19741 // If we are saving a concatenation of two XMM registers, perform two stores.
19742 // On Sandy Bridge, 256-bit memory operations are executed by two
19743 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19744 // memory operation.
19745 unsigned Alignment = St->getAlignment();
19746 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19747 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19748 StVT == VT && !IsAligned) {
19749 unsigned NumElems = VT.getVectorNumElements();
19753 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19754 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19756 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19757 SDValue Ptr0 = St->getBasePtr();
19758 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19760 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19761 St->getPointerInfo(), St->isVolatile(),
19762 St->isNonTemporal(), Alignment);
19763 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19764 St->getPointerInfo(), St->isVolatile(),
19765 St->isNonTemporal(),
19766 std::min(16U, Alignment));
19767 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19770 // Optimize trunc store (of multiple scalars) to shuffle and store.
19771 // First, pack all of the elements in one place. Next, store to memory
19772 // in fewer chunks.
19773 if (St->isTruncatingStore() && VT.isVector()) {
19774 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19775 unsigned NumElems = VT.getVectorNumElements();
19776 assert(StVT != VT && "Cannot truncate to the same type");
19777 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19778 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19780 // From, To sizes and ElemCount must be pow of two
19781 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19782 // We are going to use the original vector elt for storing.
19783 // Accumulated smaller vector elements must be a multiple of the store size.
19784 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19786 unsigned SizeRatio = FromSz / ToSz;
19788 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19790 // Create a type on which we perform the shuffle
19791 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19792 StVT.getScalarType(), NumElems*SizeRatio);
19794 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19796 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19797 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19798 for (unsigned i = 0; i != NumElems; ++i)
19799 ShuffleVec[i] = i * SizeRatio;
19801 // Can't shuffle using an illegal type.
19802 if (!TLI.isTypeLegal(WideVecVT))
19805 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19806 DAG.getUNDEF(WideVecVT),
19808 // At this point all of the data is stored at the bottom of the
19809 // register. We now need to save it to mem.
19811 // Find the largest store unit
19812 MVT StoreType = MVT::i8;
19813 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19814 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19815 MVT Tp = (MVT::SimpleValueType)tp;
19816 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19820 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19821 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19822 (64 <= NumElems * ToSz))
19823 StoreType = MVT::f64;
19825 // Bitcast the original vector into a vector of store-size units
19826 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19827 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19828 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19829 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19830 SmallVector<SDValue, 8> Chains;
19831 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19832 TLI.getPointerTy());
19833 SDValue Ptr = St->getBasePtr();
19835 // Perform one or more big stores into memory.
19836 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19837 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19838 StoreType, ShuffWide,
19839 DAG.getIntPtrConstant(i));
19840 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19841 St->getPointerInfo(), St->isVolatile(),
19842 St->isNonTemporal(), St->getAlignment());
19843 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19844 Chains.push_back(Ch);
19847 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19850 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19851 // the FP state in cases where an emms may be missing.
19852 // A preferable solution to the general problem is to figure out the right
19853 // places to insert EMMS. This qualifies as a quick hack.
19855 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19856 if (VT.getSizeInBits() != 64)
19859 const Function *F = DAG.getMachineFunction().getFunction();
19860 bool NoImplicitFloatOps = F->getAttributes().
19861 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19862 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19863 && Subtarget->hasSSE2();
19864 if ((VT.isVector() ||
19865 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19866 isa<LoadSDNode>(St->getValue()) &&
19867 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19868 St->getChain().hasOneUse() && !St->isVolatile()) {
19869 SDNode* LdVal = St->getValue().getNode();
19870 LoadSDNode *Ld = nullptr;
19871 int TokenFactorIndex = -1;
19872 SmallVector<SDValue, 8> Ops;
19873 SDNode* ChainVal = St->getChain().getNode();
19874 // Must be a store of a load. We currently handle two cases: the load
19875 // is a direct child, and it's under an intervening TokenFactor. It is
19876 // possible to dig deeper under nested TokenFactors.
19877 if (ChainVal == LdVal)
19878 Ld = cast<LoadSDNode>(St->getChain());
19879 else if (St->getValue().hasOneUse() &&
19880 ChainVal->getOpcode() == ISD::TokenFactor) {
19881 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19882 if (ChainVal->getOperand(i).getNode() == LdVal) {
19883 TokenFactorIndex = i;
19884 Ld = cast<LoadSDNode>(St->getValue());
19886 Ops.push_back(ChainVal->getOperand(i));
19890 if (!Ld || !ISD::isNormalLoad(Ld))
19893 // If this is not the MMX case, i.e. we are just turning i64 load/store
19894 // into f64 load/store, avoid the transformation if there are multiple
19895 // uses of the loaded value.
19896 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19901 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19902 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19904 if (Subtarget->is64Bit() || F64IsLegal) {
19905 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19906 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19907 Ld->getPointerInfo(), Ld->isVolatile(),
19908 Ld->isNonTemporal(), Ld->isInvariant(),
19909 Ld->getAlignment());
19910 SDValue NewChain = NewLd.getValue(1);
19911 if (TokenFactorIndex != -1) {
19912 Ops.push_back(NewChain);
19913 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19915 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19916 St->getPointerInfo(),
19917 St->isVolatile(), St->isNonTemporal(),
19918 St->getAlignment());
19921 // Otherwise, lower to two pairs of 32-bit loads / stores.
19922 SDValue LoAddr = Ld->getBasePtr();
19923 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19924 DAG.getConstant(4, MVT::i32));
19926 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19927 Ld->getPointerInfo(),
19928 Ld->isVolatile(), Ld->isNonTemporal(),
19929 Ld->isInvariant(), Ld->getAlignment());
19930 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19931 Ld->getPointerInfo().getWithOffset(4),
19932 Ld->isVolatile(), Ld->isNonTemporal(),
19934 MinAlign(Ld->getAlignment(), 4));
19936 SDValue NewChain = LoLd.getValue(1);
19937 if (TokenFactorIndex != -1) {
19938 Ops.push_back(LoLd);
19939 Ops.push_back(HiLd);
19940 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19943 LoAddr = St->getBasePtr();
19944 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19945 DAG.getConstant(4, MVT::i32));
19947 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19948 St->getPointerInfo(),
19949 St->isVolatile(), St->isNonTemporal(),
19950 St->getAlignment());
19951 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19952 St->getPointerInfo().getWithOffset(4),
19954 St->isNonTemporal(),
19955 MinAlign(St->getAlignment(), 4));
19956 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19961 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19962 /// and return the operands for the horizontal operation in LHS and RHS. A
19963 /// horizontal operation performs the binary operation on successive elements
19964 /// of its first operand, then on successive elements of its second operand,
19965 /// returning the resulting values in a vector. For example, if
19966 /// A = < float a0, float a1, float a2, float a3 >
19968 /// B = < float b0, float b1, float b2, float b3 >
19969 /// then the result of doing a horizontal operation on A and B is
19970 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19971 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19972 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19973 /// set to A, RHS to B, and the routine returns 'true'.
19974 /// Note that the binary operation should have the property that if one of the
19975 /// operands is UNDEF then the result is UNDEF.
19976 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19977 // Look for the following pattern: if
19978 // A = < float a0, float a1, float a2, float a3 >
19979 // B = < float b0, float b1, float b2, float b3 >
19981 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19982 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19983 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19984 // which is A horizontal-op B.
19986 // At least one of the operands should be a vector shuffle.
19987 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19988 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19991 MVT VT = LHS.getSimpleValueType();
19993 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19994 "Unsupported vector type for horizontal add/sub");
19996 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19997 // operate independently on 128-bit lanes.
19998 unsigned NumElts = VT.getVectorNumElements();
19999 unsigned NumLanes = VT.getSizeInBits()/128;
20000 unsigned NumLaneElts = NumElts / NumLanes;
20001 assert((NumLaneElts % 2 == 0) &&
20002 "Vector type should have an even number of elements in each lane");
20003 unsigned HalfLaneElts = NumLaneElts/2;
20005 // View LHS in the form
20006 // LHS = VECTOR_SHUFFLE A, B, LMask
20007 // If LHS is not a shuffle then pretend it is the shuffle
20008 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20009 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20012 SmallVector<int, 16> LMask(NumElts);
20013 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20014 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20015 A = LHS.getOperand(0);
20016 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20017 B = LHS.getOperand(1);
20018 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20019 std::copy(Mask.begin(), Mask.end(), LMask.begin());
20021 if (LHS.getOpcode() != ISD::UNDEF)
20023 for (unsigned i = 0; i != NumElts; ++i)
20027 // Likewise, view RHS in the form
20028 // RHS = VECTOR_SHUFFLE C, D, RMask
20030 SmallVector<int, 16> RMask(NumElts);
20031 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20032 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20033 C = RHS.getOperand(0);
20034 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20035 D = RHS.getOperand(1);
20036 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20037 std::copy(Mask.begin(), Mask.end(), RMask.begin());
20039 if (RHS.getOpcode() != ISD::UNDEF)
20041 for (unsigned i = 0; i != NumElts; ++i)
20045 // Check that the shuffles are both shuffling the same vectors.
20046 if (!(A == C && B == D) && !(A == D && B == C))
20049 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20050 if (!A.getNode() && !B.getNode())
20053 // If A and B occur in reverse order in RHS, then "swap" them (which means
20054 // rewriting the mask).
20056 CommuteVectorShuffleMask(RMask, NumElts);
20058 // At this point LHS and RHS are equivalent to
20059 // LHS = VECTOR_SHUFFLE A, B, LMask
20060 // RHS = VECTOR_SHUFFLE A, B, RMask
20061 // Check that the masks correspond to performing a horizontal operation.
20062 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20063 for (unsigned i = 0; i != NumLaneElts; ++i) {
20064 int LIdx = LMask[i+l], RIdx = RMask[i+l];
20066 // Ignore any UNDEF components.
20067 if (LIdx < 0 || RIdx < 0 ||
20068 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20069 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20072 // Check that successive elements are being operated on. If not, this is
20073 // not a horizontal operation.
20074 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20075 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20076 if (!(LIdx == Index && RIdx == Index + 1) &&
20077 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20082 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20083 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20087 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20088 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20089 const X86Subtarget *Subtarget) {
20090 EVT VT = N->getValueType(0);
20091 SDValue LHS = N->getOperand(0);
20092 SDValue RHS = N->getOperand(1);
20094 // Try to synthesize horizontal adds from adds of shuffles.
20095 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20096 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20097 isHorizontalBinOp(LHS, RHS, true))
20098 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20102 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20103 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20104 const X86Subtarget *Subtarget) {
20105 EVT VT = N->getValueType(0);
20106 SDValue LHS = N->getOperand(0);
20107 SDValue RHS = N->getOperand(1);
20109 // Try to synthesize horizontal subs from subs of shuffles.
20110 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20111 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20112 isHorizontalBinOp(LHS, RHS, false))
20113 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20117 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20118 /// X86ISD::FXOR nodes.
20119 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20120 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20121 // F[X]OR(0.0, x) -> x
20122 // F[X]OR(x, 0.0) -> x
20123 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20124 if (C->getValueAPF().isPosZero())
20125 return N->getOperand(1);
20126 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20127 if (C->getValueAPF().isPosZero())
20128 return N->getOperand(0);
20132 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20133 /// X86ISD::FMAX nodes.
20134 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20135 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20137 // Only perform optimizations if UnsafeMath is used.
20138 if (!DAG.getTarget().Options.UnsafeFPMath)
20141 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20142 // into FMINC and FMAXC, which are Commutative operations.
20143 unsigned NewOp = 0;
20144 switch (N->getOpcode()) {
20145 default: llvm_unreachable("unknown opcode");
20146 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
20147 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
20150 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20151 N->getOperand(0), N->getOperand(1));
20154 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20155 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20156 // FAND(0.0, x) -> 0.0
20157 // FAND(x, 0.0) -> 0.0
20158 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20159 if (C->getValueAPF().isPosZero())
20160 return N->getOperand(0);
20161 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20162 if (C->getValueAPF().isPosZero())
20163 return N->getOperand(1);
20167 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20168 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20169 // FANDN(x, 0.0) -> 0.0
20170 // FANDN(0.0, x) -> x
20171 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20172 if (C->getValueAPF().isPosZero())
20173 return N->getOperand(1);
20174 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20175 if (C->getValueAPF().isPosZero())
20176 return N->getOperand(1);
20180 static SDValue PerformBTCombine(SDNode *N,
20182 TargetLowering::DAGCombinerInfo &DCI) {
20183 // BT ignores high bits in the bit index operand.
20184 SDValue Op1 = N->getOperand(1);
20185 if (Op1.hasOneUse()) {
20186 unsigned BitWidth = Op1.getValueSizeInBits();
20187 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20188 APInt KnownZero, KnownOne;
20189 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20190 !DCI.isBeforeLegalizeOps());
20191 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20192 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20193 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20194 DCI.CommitTargetLoweringOpt(TLO);
20199 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20200 SDValue Op = N->getOperand(0);
20201 if (Op.getOpcode() == ISD::BITCAST)
20202 Op = Op.getOperand(0);
20203 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20204 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20205 VT.getVectorElementType().getSizeInBits() ==
20206 OpVT.getVectorElementType().getSizeInBits()) {
20207 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20212 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20213 const X86Subtarget *Subtarget) {
20214 EVT VT = N->getValueType(0);
20215 if (!VT.isVector())
20218 SDValue N0 = N->getOperand(0);
20219 SDValue N1 = N->getOperand(1);
20220 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20223 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20224 // both SSE and AVX2 since there is no sign-extended shift right
20225 // operation on a vector with 64-bit elements.
20226 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20227 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20228 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20229 N0.getOpcode() == ISD::SIGN_EXTEND)) {
20230 SDValue N00 = N0.getOperand(0);
20232 // EXTLOAD has a better solution on AVX2,
20233 // it may be replaced with X86ISD::VSEXT node.
20234 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20235 if (!ISD::isNormalLoad(N00.getNode()))
20238 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20239 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20241 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20247 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20248 TargetLowering::DAGCombinerInfo &DCI,
20249 const X86Subtarget *Subtarget) {
20250 if (!DCI.isBeforeLegalizeOps())
20253 if (!Subtarget->hasFp256())
20256 EVT VT = N->getValueType(0);
20257 if (VT.isVector() && VT.getSizeInBits() == 256) {
20258 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20266 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20267 const X86Subtarget* Subtarget) {
20269 EVT VT = N->getValueType(0);
20271 // Let legalize expand this if it isn't a legal type yet.
20272 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20275 EVT ScalarVT = VT.getScalarType();
20276 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20277 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20280 SDValue A = N->getOperand(0);
20281 SDValue B = N->getOperand(1);
20282 SDValue C = N->getOperand(2);
20284 bool NegA = (A.getOpcode() == ISD::FNEG);
20285 bool NegB = (B.getOpcode() == ISD::FNEG);
20286 bool NegC = (C.getOpcode() == ISD::FNEG);
20288 // Negative multiplication when NegA xor NegB
20289 bool NegMul = (NegA != NegB);
20291 A = A.getOperand(0);
20293 B = B.getOperand(0);
20295 C = C.getOperand(0);
20299 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20301 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20303 return DAG.getNode(Opcode, dl, VT, A, B, C);
20306 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20307 TargetLowering::DAGCombinerInfo &DCI,
20308 const X86Subtarget *Subtarget) {
20309 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
20310 // (and (i32 x86isd::setcc_carry), 1)
20311 // This eliminates the zext. This transformation is necessary because
20312 // ISD::SETCC is always legalized to i8.
20314 SDValue N0 = N->getOperand(0);
20315 EVT VT = N->getValueType(0);
20317 if (N0.getOpcode() == ISD::AND &&
20319 N0.getOperand(0).hasOneUse()) {
20320 SDValue N00 = N0.getOperand(0);
20321 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20322 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20323 if (!C || C->getZExtValue() != 1)
20325 return DAG.getNode(ISD::AND, dl, VT,
20326 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20327 N00.getOperand(0), N00.getOperand(1)),
20328 DAG.getConstant(1, VT));
20332 if (N0.getOpcode() == ISD::TRUNCATE &&
20334 N0.getOperand(0).hasOneUse()) {
20335 SDValue N00 = N0.getOperand(0);
20336 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20337 return DAG.getNode(ISD::AND, dl, VT,
20338 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20339 N00.getOperand(0), N00.getOperand(1)),
20340 DAG.getConstant(1, VT));
20343 if (VT.is256BitVector()) {
20344 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20352 // Optimize x == -y --> x+y == 0
20353 // x != -y --> x+y != 0
20354 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20355 const X86Subtarget* Subtarget) {
20356 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20357 SDValue LHS = N->getOperand(0);
20358 SDValue RHS = N->getOperand(1);
20359 EVT VT = N->getValueType(0);
20362 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20363 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20364 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20365 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20366 LHS.getValueType(), RHS, LHS.getOperand(1));
20367 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20368 addV, DAG.getConstant(0, addV.getValueType()), CC);
20370 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20371 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20372 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20373 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20374 RHS.getValueType(), LHS, RHS.getOperand(1));
20375 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20376 addV, DAG.getConstant(0, addV.getValueType()), CC);
20379 if (VT.getScalarType() == MVT::i1) {
20380 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20381 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20382 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20383 if (!IsSEXT0 && !IsVZero0)
20385 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20386 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20387 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20389 if (!IsSEXT1 && !IsVZero1)
20392 if (IsSEXT0 && IsVZero1) {
20393 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20394 if (CC == ISD::SETEQ)
20395 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20396 return LHS.getOperand(0);
20398 if (IsSEXT1 && IsVZero0) {
20399 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20400 if (CC == ISD::SETEQ)
20401 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20402 return RHS.getOperand(0);
20409 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20410 const X86Subtarget *Subtarget) {
20412 MVT VT = N->getOperand(1)->getSimpleValueType(0);
20413 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20414 "X86insertps is only defined for v4x32");
20416 SDValue Ld = N->getOperand(1);
20417 if (MayFoldLoad(Ld)) {
20418 // Extract the countS bits from the immediate so we can get the proper
20419 // address when narrowing the vector load to a specific element.
20420 // When the second source op is a memory address, interps doesn't use
20421 // countS and just gets an f32 from that address.
20422 unsigned DestIndex =
20423 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20424 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20428 // Create this as a scalar to vector to match the instruction pattern.
20429 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20430 // countS bits are ignored when loading from memory on insertps, which
20431 // means we don't need to explicitly set them to 0.
20432 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20433 LoadScalarToVector, N->getOperand(2));
20436 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20437 // as "sbb reg,reg", since it can be extended without zext and produces
20438 // an all-ones bit which is more useful than 0/1 in some cases.
20439 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20442 return DAG.getNode(ISD::AND, DL, VT,
20443 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20444 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20445 DAG.getConstant(1, VT));
20446 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20447 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20448 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20449 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20452 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20453 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20454 TargetLowering::DAGCombinerInfo &DCI,
20455 const X86Subtarget *Subtarget) {
20457 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20458 SDValue EFLAGS = N->getOperand(1);
20460 if (CC == X86::COND_A) {
20461 // Try to convert COND_A into COND_B in an attempt to facilitate
20462 // materializing "setb reg".
20464 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20465 // cannot take an immediate as its first operand.
20467 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20468 EFLAGS.getValueType().isInteger() &&
20469 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20470 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20471 EFLAGS.getNode()->getVTList(),
20472 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20473 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20474 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20478 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20479 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20481 if (CC == X86::COND_B)
20482 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20486 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20487 if (Flags.getNode()) {
20488 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20489 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20495 // Optimize branch condition evaluation.
20497 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20498 TargetLowering::DAGCombinerInfo &DCI,
20499 const X86Subtarget *Subtarget) {
20501 SDValue Chain = N->getOperand(0);
20502 SDValue Dest = N->getOperand(1);
20503 SDValue EFLAGS = N->getOperand(3);
20504 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20508 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20509 if (Flags.getNode()) {
20510 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20511 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20518 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20519 const X86TargetLowering *XTLI) {
20520 SDValue Op0 = N->getOperand(0);
20521 EVT InVT = Op0->getValueType(0);
20523 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20524 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20526 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20527 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20528 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20531 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20532 // a 32-bit target where SSE doesn't support i64->FP operations.
20533 if (Op0.getOpcode() == ISD::LOAD) {
20534 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20535 EVT VT = Ld->getValueType(0);
20536 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20537 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20538 !XTLI->getSubtarget()->is64Bit() &&
20540 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20541 Ld->getChain(), Op0, DAG);
20542 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20549 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20550 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20551 X86TargetLowering::DAGCombinerInfo &DCI) {
20552 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20553 // the result is either zero or one (depending on the input carry bit).
20554 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20555 if (X86::isZeroNode(N->getOperand(0)) &&
20556 X86::isZeroNode(N->getOperand(1)) &&
20557 // We don't have a good way to replace an EFLAGS use, so only do this when
20559 SDValue(N, 1).use_empty()) {
20561 EVT VT = N->getValueType(0);
20562 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20563 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20564 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20565 DAG.getConstant(X86::COND_B,MVT::i8),
20567 DAG.getConstant(1, VT));
20568 return DCI.CombineTo(N, Res1, CarryOut);
20574 // fold (add Y, (sete X, 0)) -> adc 0, Y
20575 // (add Y, (setne X, 0)) -> sbb -1, Y
20576 // (sub (sete X, 0), Y) -> sbb 0, Y
20577 // (sub (setne X, 0), Y) -> adc -1, Y
20578 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20581 // Look through ZExts.
20582 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20583 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20586 SDValue SetCC = Ext.getOperand(0);
20587 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20590 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20591 if (CC != X86::COND_E && CC != X86::COND_NE)
20594 SDValue Cmp = SetCC.getOperand(1);
20595 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20596 !X86::isZeroNode(Cmp.getOperand(1)) ||
20597 !Cmp.getOperand(0).getValueType().isInteger())
20600 SDValue CmpOp0 = Cmp.getOperand(0);
20601 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20602 DAG.getConstant(1, CmpOp0.getValueType()));
20604 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20605 if (CC == X86::COND_NE)
20606 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20607 DL, OtherVal.getValueType(), OtherVal,
20608 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20609 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20610 DL, OtherVal.getValueType(), OtherVal,
20611 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20614 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20615 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20616 const X86Subtarget *Subtarget) {
20617 EVT VT = N->getValueType(0);
20618 SDValue Op0 = N->getOperand(0);
20619 SDValue Op1 = N->getOperand(1);
20621 // Try to synthesize horizontal adds from adds of shuffles.
20622 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20623 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20624 isHorizontalBinOp(Op0, Op1, true))
20625 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20627 return OptimizeConditionalInDecrement(N, DAG);
20630 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20631 const X86Subtarget *Subtarget) {
20632 SDValue Op0 = N->getOperand(0);
20633 SDValue Op1 = N->getOperand(1);
20635 // X86 can't encode an immediate LHS of a sub. See if we can push the
20636 // negation into a preceding instruction.
20637 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20638 // If the RHS of the sub is a XOR with one use and a constant, invert the
20639 // immediate. Then add one to the LHS of the sub so we can turn
20640 // X-Y -> X+~Y+1, saving one register.
20641 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20642 isa<ConstantSDNode>(Op1.getOperand(1))) {
20643 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20644 EVT VT = Op0.getValueType();
20645 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20647 DAG.getConstant(~XorC, VT));
20648 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20649 DAG.getConstant(C->getAPIntValue()+1, VT));
20653 // Try to synthesize horizontal adds from adds of shuffles.
20654 EVT VT = N->getValueType(0);
20655 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20656 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20657 isHorizontalBinOp(Op0, Op1, true))
20658 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20660 return OptimizeConditionalInDecrement(N, DAG);
20663 /// performVZEXTCombine - Performs build vector combines
20664 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20665 TargetLowering::DAGCombinerInfo &DCI,
20666 const X86Subtarget *Subtarget) {
20667 // (vzext (bitcast (vzext (x)) -> (vzext x)
20668 SDValue In = N->getOperand(0);
20669 while (In.getOpcode() == ISD::BITCAST)
20670 In = In.getOperand(0);
20672 if (In.getOpcode() != X86ISD::VZEXT)
20675 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20679 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20680 DAGCombinerInfo &DCI) const {
20681 SelectionDAG &DAG = DCI.DAG;
20682 switch (N->getOpcode()) {
20684 case ISD::EXTRACT_VECTOR_ELT:
20685 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20687 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20688 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20689 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20690 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20691 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20692 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20695 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20696 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20697 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20698 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20699 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20700 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20701 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20702 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20703 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20705 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20707 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20708 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20709 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20710 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20711 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20712 case ISD::ANY_EXTEND:
20713 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20714 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20715 case ISD::SIGN_EXTEND_INREG:
20716 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20717 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20718 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20719 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20720 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20721 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20722 case X86ISD::SHUFP: // Handle all target specific shuffles
20723 case X86ISD::PALIGNR:
20724 case X86ISD::UNPCKH:
20725 case X86ISD::UNPCKL:
20726 case X86ISD::MOVHLPS:
20727 case X86ISD::MOVLHPS:
20728 case X86ISD::PSHUFD:
20729 case X86ISD::PSHUFHW:
20730 case X86ISD::PSHUFLW:
20731 case X86ISD::MOVSS:
20732 case X86ISD::MOVSD:
20733 case X86ISD::VPERMILP:
20734 case X86ISD::VPERM2X128:
20735 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20736 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20737 case ISD::INTRINSIC_WO_CHAIN:
20738 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20739 case X86ISD::INSERTPS:
20740 return PerformINSERTPSCombine(N, DAG, Subtarget);
20746 /// isTypeDesirableForOp - Return true if the target has native support for
20747 /// the specified value type and it is 'desirable' to use the type for the
20748 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20749 /// instruction encodings are longer and some i16 instructions are slow.
20750 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20751 if (!isTypeLegal(VT))
20753 if (VT != MVT::i16)
20760 case ISD::SIGN_EXTEND:
20761 case ISD::ZERO_EXTEND:
20762 case ISD::ANY_EXTEND:
20775 /// IsDesirableToPromoteOp - This method query the target whether it is
20776 /// beneficial for dag combiner to promote the specified node. If true, it
20777 /// should return the desired promotion type by reference.
20778 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20779 EVT VT = Op.getValueType();
20780 if (VT != MVT::i16)
20783 bool Promote = false;
20784 bool Commute = false;
20785 switch (Op.getOpcode()) {
20788 LoadSDNode *LD = cast<LoadSDNode>(Op);
20789 // If the non-extending load has a single use and it's not live out, then it
20790 // might be folded.
20791 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20792 Op.hasOneUse()*/) {
20793 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20794 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20795 // The only case where we'd want to promote LOAD (rather then it being
20796 // promoted as an operand is when it's only use is liveout.
20797 if (UI->getOpcode() != ISD::CopyToReg)
20804 case ISD::SIGN_EXTEND:
20805 case ISD::ZERO_EXTEND:
20806 case ISD::ANY_EXTEND:
20811 SDValue N0 = Op.getOperand(0);
20812 // Look out for (store (shl (load), x)).
20813 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20826 SDValue N0 = Op.getOperand(0);
20827 SDValue N1 = Op.getOperand(1);
20828 if (!Commute && MayFoldLoad(N1))
20830 // Avoid disabling potential load folding opportunities.
20831 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20833 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20843 //===----------------------------------------------------------------------===//
20844 // X86 Inline Assembly Support
20845 //===----------------------------------------------------------------------===//
20848 // Helper to match a string separated by whitespace.
20849 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20850 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20852 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20853 StringRef piece(*args[i]);
20854 if (!s.startswith(piece)) // Check if the piece matches.
20857 s = s.substr(piece.size());
20858 StringRef::size_type pos = s.find_first_not_of(" \t");
20859 if (pos == 0) // We matched a prefix.
20867 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20870 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20872 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20873 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20874 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20875 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20877 if (AsmPieces.size() == 3)
20879 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20886 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20887 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20889 std::string AsmStr = IA->getAsmString();
20891 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20892 if (!Ty || Ty->getBitWidth() % 16 != 0)
20895 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20896 SmallVector<StringRef, 4> AsmPieces;
20897 SplitString(AsmStr, AsmPieces, ";\n");
20899 switch (AsmPieces.size()) {
20900 default: return false;
20902 // FIXME: this should verify that we are targeting a 486 or better. If not,
20903 // we will turn this bswap into something that will be lowered to logical
20904 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20905 // lower so don't worry about this.
20907 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20908 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20909 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20910 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20911 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20912 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20913 // No need to check constraints, nothing other than the equivalent of
20914 // "=r,0" would be valid here.
20915 return IntrinsicLowering::LowerToByteSwap(CI);
20918 // rorw $$8, ${0:w} --> llvm.bswap.i16
20919 if (CI->getType()->isIntegerTy(16) &&
20920 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20921 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20922 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20924 const std::string &ConstraintsStr = IA->getConstraintString();
20925 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20926 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20927 if (clobbersFlagRegisters(AsmPieces))
20928 return IntrinsicLowering::LowerToByteSwap(CI);
20932 if (CI->getType()->isIntegerTy(32) &&
20933 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20934 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20935 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20936 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20938 const std::string &ConstraintsStr = IA->getConstraintString();
20939 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20940 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20941 if (clobbersFlagRegisters(AsmPieces))
20942 return IntrinsicLowering::LowerToByteSwap(CI);
20945 if (CI->getType()->isIntegerTy(64)) {
20946 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20947 if (Constraints.size() >= 2 &&
20948 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20949 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20950 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20951 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20952 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20953 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20954 return IntrinsicLowering::LowerToByteSwap(CI);
20962 /// getConstraintType - Given a constraint letter, return the type of
20963 /// constraint it is for this target.
20964 X86TargetLowering::ConstraintType
20965 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20966 if (Constraint.size() == 1) {
20967 switch (Constraint[0]) {
20978 return C_RegisterClass;
21002 return TargetLowering::getConstraintType(Constraint);
21005 /// Examine constraint type and operand type and determine a weight value.
21006 /// This object must already have been set up with the operand type
21007 /// and the current alternative constraint selected.
21008 TargetLowering::ConstraintWeight
21009 X86TargetLowering::getSingleConstraintMatchWeight(
21010 AsmOperandInfo &info, const char *constraint) const {
21011 ConstraintWeight weight = CW_Invalid;
21012 Value *CallOperandVal = info.CallOperandVal;
21013 // If we don't have a value, we can't do a match,
21014 // but allow it at the lowest weight.
21015 if (!CallOperandVal)
21017 Type *type = CallOperandVal->getType();
21018 // Look at the constraint type.
21019 switch (*constraint) {
21021 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21032 if (CallOperandVal->getType()->isIntegerTy())
21033 weight = CW_SpecificReg;
21038 if (type->isFloatingPointTy())
21039 weight = CW_SpecificReg;
21042 if (type->isX86_MMXTy() && Subtarget->hasMMX())
21043 weight = CW_SpecificReg;
21047 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21048 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21049 weight = CW_Register;
21052 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21053 if (C->getZExtValue() <= 31)
21054 weight = CW_Constant;
21058 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21059 if (C->getZExtValue() <= 63)
21060 weight = CW_Constant;
21064 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21065 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21066 weight = CW_Constant;
21070 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21071 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21072 weight = CW_Constant;
21076 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21077 if (C->getZExtValue() <= 3)
21078 weight = CW_Constant;
21082 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21083 if (C->getZExtValue() <= 0xff)
21084 weight = CW_Constant;
21089 if (dyn_cast<ConstantFP>(CallOperandVal)) {
21090 weight = CW_Constant;
21094 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21095 if ((C->getSExtValue() >= -0x80000000LL) &&
21096 (C->getSExtValue() <= 0x7fffffffLL))
21097 weight = CW_Constant;
21101 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21102 if (C->getZExtValue() <= 0xffffffff)
21103 weight = CW_Constant;
21110 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21111 /// with another that has more specific requirements based on the type of the
21112 /// corresponding operand.
21113 const char *X86TargetLowering::
21114 LowerXConstraint(EVT ConstraintVT) const {
21115 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21116 // 'f' like normal targets.
21117 if (ConstraintVT.isFloatingPoint()) {
21118 if (Subtarget->hasSSE2())
21120 if (Subtarget->hasSSE1())
21124 return TargetLowering::LowerXConstraint(ConstraintVT);
21127 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21128 /// vector. If it is invalid, don't add anything to Ops.
21129 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21130 std::string &Constraint,
21131 std::vector<SDValue>&Ops,
21132 SelectionDAG &DAG) const {
21135 // Only support length 1 constraints for now.
21136 if (Constraint.length() > 1) return;
21138 char ConstraintLetter = Constraint[0];
21139 switch (ConstraintLetter) {
21142 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21143 if (C->getZExtValue() <= 31) {
21144 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21150 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21151 if (C->getZExtValue() <= 63) {
21152 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21158 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21159 if (isInt<8>(C->getSExtValue())) {
21160 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21166 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21167 if (C->getZExtValue() <= 255) {
21168 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21174 // 32-bit signed value
21175 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21176 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21177 C->getSExtValue())) {
21178 // Widen to 64 bits here to get it sign extended.
21179 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21182 // FIXME gcc accepts some relocatable values here too, but only in certain
21183 // memory models; it's complicated.
21188 // 32-bit unsigned value
21189 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21190 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21191 C->getZExtValue())) {
21192 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21196 // FIXME gcc accepts some relocatable values here too, but only in certain
21197 // memory models; it's complicated.
21201 // Literal immediates are always ok.
21202 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21203 // Widen to 64 bits here to get it sign extended.
21204 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21208 // In any sort of PIC mode addresses need to be computed at runtime by
21209 // adding in a register or some sort of table lookup. These can't
21210 // be used as immediates.
21211 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21214 // If we are in non-pic codegen mode, we allow the address of a global (with
21215 // an optional displacement) to be used with 'i'.
21216 GlobalAddressSDNode *GA = nullptr;
21217 int64_t Offset = 0;
21219 // Match either (GA), (GA+C), (GA+C1+C2), etc.
21221 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21222 Offset += GA->getOffset();
21224 } else if (Op.getOpcode() == ISD::ADD) {
21225 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21226 Offset += C->getZExtValue();
21227 Op = Op.getOperand(0);
21230 } else if (Op.getOpcode() == ISD::SUB) {
21231 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21232 Offset += -C->getZExtValue();
21233 Op = Op.getOperand(0);
21238 // Otherwise, this isn't something we can handle, reject it.
21242 const GlobalValue *GV = GA->getGlobal();
21243 // If we require an extra load to get this address, as in PIC mode, we
21244 // can't accept it.
21245 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
21246 getTargetMachine())))
21249 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21250 GA->getValueType(0), Offset);
21255 if (Result.getNode()) {
21256 Ops.push_back(Result);
21259 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21262 std::pair<unsigned, const TargetRegisterClass*>
21263 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21265 // First, see if this is a constraint that directly corresponds to an LLVM
21267 if (Constraint.size() == 1) {
21268 // GCC Constraint Letters
21269 switch (Constraint[0]) {
21271 // TODO: Slight differences here in allocation order and leaving
21272 // RIP in the class. Do they matter any more here than they do
21273 // in the normal allocation?
21274 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21275 if (Subtarget->is64Bit()) {
21276 if (VT == MVT::i32 || VT == MVT::f32)
21277 return std::make_pair(0U, &X86::GR32RegClass);
21278 if (VT == MVT::i16)
21279 return std::make_pair(0U, &X86::GR16RegClass);
21280 if (VT == MVT::i8 || VT == MVT::i1)
21281 return std::make_pair(0U, &X86::GR8RegClass);
21282 if (VT == MVT::i64 || VT == MVT::f64)
21283 return std::make_pair(0U, &X86::GR64RegClass);
21286 // 32-bit fallthrough
21287 case 'Q': // Q_REGS
21288 if (VT == MVT::i32 || VT == MVT::f32)
21289 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21290 if (VT == MVT::i16)
21291 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21292 if (VT == MVT::i8 || VT == MVT::i1)
21293 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21294 if (VT == MVT::i64)
21295 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21297 case 'r': // GENERAL_REGS
21298 case 'l': // INDEX_REGS
21299 if (VT == MVT::i8 || VT == MVT::i1)
21300 return std::make_pair(0U, &X86::GR8RegClass);
21301 if (VT == MVT::i16)
21302 return std::make_pair(0U, &X86::GR16RegClass);
21303 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21304 return std::make_pair(0U, &X86::GR32RegClass);
21305 return std::make_pair(0U, &X86::GR64RegClass);
21306 case 'R': // LEGACY_REGS
21307 if (VT == MVT::i8 || VT == MVT::i1)
21308 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21309 if (VT == MVT::i16)
21310 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21311 if (VT == MVT::i32 || !Subtarget->is64Bit())
21312 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21313 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21314 case 'f': // FP Stack registers.
21315 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21316 // value to the correct fpstack register class.
21317 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21318 return std::make_pair(0U, &X86::RFP32RegClass);
21319 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21320 return std::make_pair(0U, &X86::RFP64RegClass);
21321 return std::make_pair(0U, &X86::RFP80RegClass);
21322 case 'y': // MMX_REGS if MMX allowed.
21323 if (!Subtarget->hasMMX()) break;
21324 return std::make_pair(0U, &X86::VR64RegClass);
21325 case 'Y': // SSE_REGS if SSE2 allowed
21326 if (!Subtarget->hasSSE2()) break;
21328 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21329 if (!Subtarget->hasSSE1()) break;
21331 switch (VT.SimpleTy) {
21333 // Scalar SSE types.
21336 return std::make_pair(0U, &X86::FR32RegClass);
21339 return std::make_pair(0U, &X86::FR64RegClass);
21347 return std::make_pair(0U, &X86::VR128RegClass);
21355 return std::make_pair(0U, &X86::VR256RegClass);
21360 return std::make_pair(0U, &X86::VR512RegClass);
21366 // Use the default implementation in TargetLowering to convert the register
21367 // constraint into a member of a register class.
21368 std::pair<unsigned, const TargetRegisterClass*> Res;
21369 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21371 // Not found as a standard register?
21373 // Map st(0) -> st(7) -> ST0
21374 if (Constraint.size() == 7 && Constraint[0] == '{' &&
21375 tolower(Constraint[1]) == 's' &&
21376 tolower(Constraint[2]) == 't' &&
21377 Constraint[3] == '(' &&
21378 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21379 Constraint[5] == ')' &&
21380 Constraint[6] == '}') {
21382 Res.first = X86::ST0+Constraint[4]-'0';
21383 Res.second = &X86::RFP80RegClass;
21387 // GCC allows "st(0)" to be called just plain "st".
21388 if (StringRef("{st}").equals_lower(Constraint)) {
21389 Res.first = X86::ST0;
21390 Res.second = &X86::RFP80RegClass;
21395 if (StringRef("{flags}").equals_lower(Constraint)) {
21396 Res.first = X86::EFLAGS;
21397 Res.second = &X86::CCRRegClass;
21401 // 'A' means EAX + EDX.
21402 if (Constraint == "A") {
21403 Res.first = X86::EAX;
21404 Res.second = &X86::GR32_ADRegClass;
21410 // Otherwise, check to see if this is a register class of the wrong value
21411 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21412 // turn into {ax},{dx}.
21413 if (Res.second->hasType(VT))
21414 return Res; // Correct type already, nothing to do.
21416 // All of the single-register GCC register classes map their values onto
21417 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21418 // really want an 8-bit or 32-bit register, map to the appropriate register
21419 // class and return the appropriate register.
21420 if (Res.second == &X86::GR16RegClass) {
21421 if (VT == MVT::i8 || VT == MVT::i1) {
21422 unsigned DestReg = 0;
21423 switch (Res.first) {
21425 case X86::AX: DestReg = X86::AL; break;
21426 case X86::DX: DestReg = X86::DL; break;
21427 case X86::CX: DestReg = X86::CL; break;
21428 case X86::BX: DestReg = X86::BL; break;
21431 Res.first = DestReg;
21432 Res.second = &X86::GR8RegClass;
21434 } else if (VT == MVT::i32 || VT == MVT::f32) {
21435 unsigned DestReg = 0;
21436 switch (Res.first) {
21438 case X86::AX: DestReg = X86::EAX; break;
21439 case X86::DX: DestReg = X86::EDX; break;
21440 case X86::CX: DestReg = X86::ECX; break;
21441 case X86::BX: DestReg = X86::EBX; break;
21442 case X86::SI: DestReg = X86::ESI; break;
21443 case X86::DI: DestReg = X86::EDI; break;
21444 case X86::BP: DestReg = X86::EBP; break;
21445 case X86::SP: DestReg = X86::ESP; break;
21448 Res.first = DestReg;
21449 Res.second = &X86::GR32RegClass;
21451 } else if (VT == MVT::i64 || VT == MVT::f64) {
21452 unsigned DestReg = 0;
21453 switch (Res.first) {
21455 case X86::AX: DestReg = X86::RAX; break;
21456 case X86::DX: DestReg = X86::RDX; break;
21457 case X86::CX: DestReg = X86::RCX; break;
21458 case X86::BX: DestReg = X86::RBX; break;
21459 case X86::SI: DestReg = X86::RSI; break;
21460 case X86::DI: DestReg = X86::RDI; break;
21461 case X86::BP: DestReg = X86::RBP; break;
21462 case X86::SP: DestReg = X86::RSP; break;
21465 Res.first = DestReg;
21466 Res.second = &X86::GR64RegClass;
21469 } else if (Res.second == &X86::FR32RegClass ||
21470 Res.second == &X86::FR64RegClass ||
21471 Res.second == &X86::VR128RegClass ||
21472 Res.second == &X86::VR256RegClass ||
21473 Res.second == &X86::FR32XRegClass ||
21474 Res.second == &X86::FR64XRegClass ||
21475 Res.second == &X86::VR128XRegClass ||
21476 Res.second == &X86::VR256XRegClass ||
21477 Res.second == &X86::VR512RegClass) {
21478 // Handle references to XMM physical registers that got mapped into the
21479 // wrong class. This can happen with constraints like {xmm0} where the
21480 // target independent register mapper will just pick the first match it can
21481 // find, ignoring the required type.
21483 if (VT == MVT::f32 || VT == MVT::i32)
21484 Res.second = &X86::FR32RegClass;
21485 else if (VT == MVT::f64 || VT == MVT::i64)
21486 Res.second = &X86::FR64RegClass;
21487 else if (X86::VR128RegClass.hasType(VT))
21488 Res.second = &X86::VR128RegClass;
21489 else if (X86::VR256RegClass.hasType(VT))
21490 Res.second = &X86::VR256RegClass;
21491 else if (X86::VR512RegClass.hasType(VT))
21492 Res.second = &X86::VR512RegClass;
21498 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21500 // Scaling factors are not free at all.
21501 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21502 // will take 2 allocations in the out of order engine instead of 1
21503 // for plain addressing mode, i.e. inst (reg1).
21505 // vaddps (%rsi,%drx), %ymm0, %ymm1
21506 // Requires two allocations (one for the load, one for the computation)
21508 // vaddps (%rsi), %ymm0, %ymm1
21509 // Requires just 1 allocation, i.e., freeing allocations for other operations
21510 // and having less micro operations to execute.
21512 // For some X86 architectures, this is even worse because for instance for
21513 // stores, the complex addressing mode forces the instruction to use the
21514 // "load" ports instead of the dedicated "store" port.
21515 // E.g., on Haswell:
21516 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21517 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21518 if (isLegalAddressingMode(AM, Ty))
21519 // Scale represents reg2 * scale, thus account for 1
21520 // as soon as we use a second register.
21521 return AM.Scale != 0;