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::f32, Expand);
444 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
445 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
446 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
447 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
448 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
449 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
450 if (Subtarget->is64Bit())
451 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
452 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
453 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
454 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
455 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
456 setOperationAction(ISD::FREM , MVT::f32 , Expand);
457 setOperationAction(ISD::FREM , MVT::f64 , Expand);
458 setOperationAction(ISD::FREM , MVT::f80 , Expand);
459 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
461 // Promote the i8 variants and force them on up to i32 which has a shorter
463 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
464 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
466 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
467 if (Subtarget->hasBMI()) {
468 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
469 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
470 if (Subtarget->is64Bit())
471 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
473 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
474 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
475 if (Subtarget->is64Bit())
476 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
479 if (Subtarget->hasLZCNT()) {
480 // When promoting the i8 variants, force them to i32 for a shorter
482 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
483 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
484 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
485 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
486 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
487 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
488 if (Subtarget->is64Bit())
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
491 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
492 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
493 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
494 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
495 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
496 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
497 if (Subtarget->is64Bit()) {
498 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
499 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
503 if (Subtarget->hasPOPCNT()) {
504 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
506 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
507 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
508 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
509 if (Subtarget->is64Bit())
510 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
513 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
515 if (!Subtarget->hasMOVBE())
516 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
518 // These should be promoted to a larger select which is supported.
519 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
520 // X86 wants to expand cmov itself.
521 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
522 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
523 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
524 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
525 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
526 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
527 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
528 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
529 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
530 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
531 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
532 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
533 if (Subtarget->is64Bit()) {
534 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
535 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
537 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
538 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
539 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
540 // support continuation, user-level threading, and etc.. As a result, no
541 // other SjLj exception interfaces are implemented and please don't build
542 // your own exception handling based on them.
543 // LLVM/Clang supports zero-cost DWARF exception handling.
544 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
545 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
548 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
549 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
550 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
551 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
552 if (Subtarget->is64Bit())
553 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
554 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
555 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
556 if (Subtarget->is64Bit()) {
557 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
558 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
559 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
560 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
561 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
563 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
564 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
565 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
566 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
567 if (Subtarget->is64Bit()) {
568 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
569 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
570 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
573 if (Subtarget->hasSSE1())
574 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
576 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
578 // Expand certain atomics
579 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
581 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
582 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
583 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
586 if (!Subtarget->is64Bit()) {
587 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
594 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
595 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
596 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
597 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
598 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
601 if (Subtarget->hasCmpxchg16b()) {
602 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
605 // FIXME - use subtarget debug flags
606 if (!Subtarget->isTargetDarwin() &&
607 !Subtarget->isTargetELF() &&
608 !Subtarget->isTargetCygMing()) {
609 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
612 if (Subtarget->is64Bit()) {
613 setExceptionPointerRegister(X86::RAX);
614 setExceptionSelectorRegister(X86::RDX);
616 setExceptionPointerRegister(X86::EAX);
617 setExceptionSelectorRegister(X86::EDX);
619 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
620 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
622 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
623 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
625 setOperationAction(ISD::TRAP, MVT::Other, Legal);
626 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
628 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
629 setOperationAction(ISD::VASTART , MVT::Other, Custom);
630 setOperationAction(ISD::VAEND , MVT::Other, Expand);
631 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
632 // TargetInfo::X86_64ABIBuiltinVaList
633 setOperationAction(ISD::VAARG , MVT::Other, Custom);
634 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
636 // TargetInfo::CharPtrBuiltinVaList
637 setOperationAction(ISD::VAARG , MVT::Other, Expand);
638 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
641 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
642 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
644 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
645 MVT::i64 : MVT::i32, Custom);
647 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
648 // f32 and f64 use SSE.
649 // Set up the FP register classes.
650 addRegisterClass(MVT::f32, &X86::FR32RegClass);
651 addRegisterClass(MVT::f64, &X86::FR64RegClass);
653 // Use ANDPD to simulate FABS.
654 setOperationAction(ISD::FABS , MVT::f64, Custom);
655 setOperationAction(ISD::FABS , MVT::f32, Custom);
657 // Use XORP to simulate FNEG.
658 setOperationAction(ISD::FNEG , MVT::f64, Custom);
659 setOperationAction(ISD::FNEG , MVT::f32, Custom);
661 // Use ANDPD and ORPD to simulate FCOPYSIGN.
662 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
663 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
665 // Lower this to FGETSIGNx86 plus an AND.
666 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
667 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
669 // We don't support sin/cos/fmod
670 setOperationAction(ISD::FSIN , MVT::f64, Expand);
671 setOperationAction(ISD::FCOS , MVT::f64, Expand);
672 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
673 setOperationAction(ISD::FSIN , MVT::f32, Expand);
674 setOperationAction(ISD::FCOS , MVT::f32, Expand);
675 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
677 // Expand FP immediates into loads from the stack, except for the special
679 addLegalFPImmediate(APFloat(+0.0)); // xorpd
680 addLegalFPImmediate(APFloat(+0.0f)); // xorps
681 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
682 // Use SSE for f32, x87 for f64.
683 // Set up the FP register classes.
684 addRegisterClass(MVT::f32, &X86::FR32RegClass);
685 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
687 // Use ANDPS to simulate FABS.
688 setOperationAction(ISD::FABS , MVT::f32, Custom);
690 // Use XORP to simulate FNEG.
691 setOperationAction(ISD::FNEG , MVT::f32, Custom);
693 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
695 // Use ANDPS and ORPS to simulate FCOPYSIGN.
696 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
697 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
699 // We don't support sin/cos/fmod
700 setOperationAction(ISD::FSIN , MVT::f32, Expand);
701 setOperationAction(ISD::FCOS , MVT::f32, Expand);
702 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
704 // Special cases we handle for FP constants.
705 addLegalFPImmediate(APFloat(+0.0f)); // xorps
706 addLegalFPImmediate(APFloat(+0.0)); // FLD0
707 addLegalFPImmediate(APFloat(+1.0)); // FLD1
708 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
709 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
711 if (!TM.Options.UnsafeFPMath) {
712 setOperationAction(ISD::FSIN , MVT::f64, Expand);
713 setOperationAction(ISD::FCOS , MVT::f64, Expand);
714 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
716 } else if (!TM.Options.UseSoftFloat) {
717 // f32 and f64 in x87.
718 // Set up the FP register classes.
719 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
720 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
722 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
723 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
724 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
725 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
727 if (!TM.Options.UnsafeFPMath) {
728 setOperationAction(ISD::FSIN , MVT::f64, Expand);
729 setOperationAction(ISD::FSIN , MVT::f32, Expand);
730 setOperationAction(ISD::FCOS , MVT::f64, Expand);
731 setOperationAction(ISD::FCOS , MVT::f32, Expand);
732 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
735 addLegalFPImmediate(APFloat(+0.0)); // FLD0
736 addLegalFPImmediate(APFloat(+1.0)); // FLD1
737 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
738 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
739 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
740 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
741 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
742 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
745 // We don't support FMA.
746 setOperationAction(ISD::FMA, MVT::f64, Expand);
747 setOperationAction(ISD::FMA, MVT::f32, Expand);
749 // Long double always uses X87.
750 if (!TM.Options.UseSoftFloat) {
751 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
752 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
753 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
755 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
756 addLegalFPImmediate(TmpFlt); // FLD0
758 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
761 APFloat TmpFlt2(+1.0);
762 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
764 addLegalFPImmediate(TmpFlt2); // FLD1
765 TmpFlt2.changeSign();
766 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
769 if (!TM.Options.UnsafeFPMath) {
770 setOperationAction(ISD::FSIN , MVT::f80, Expand);
771 setOperationAction(ISD::FCOS , MVT::f80, Expand);
772 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
775 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
776 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
777 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
778 setOperationAction(ISD::FRINT, MVT::f80, Expand);
779 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
780 setOperationAction(ISD::FMA, MVT::f80, Expand);
783 // Always use a library call for pow.
784 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
785 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
786 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
788 setOperationAction(ISD::FLOG, MVT::f80, Expand);
789 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
790 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
791 setOperationAction(ISD::FEXP, MVT::f80, Expand);
792 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
794 // First set operation action for all vector types to either promote
795 // (for widening) or expand (for scalarization). Then we will selectively
796 // turn on ones that can be effectively codegen'd.
797 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
798 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
799 MVT VT = (MVT::SimpleValueType)i;
800 setOperationAction(ISD::ADD , VT, Expand);
801 setOperationAction(ISD::SUB , VT, Expand);
802 setOperationAction(ISD::FADD, VT, Expand);
803 setOperationAction(ISD::FNEG, VT, Expand);
804 setOperationAction(ISD::FSUB, VT, Expand);
805 setOperationAction(ISD::MUL , VT, Expand);
806 setOperationAction(ISD::FMUL, VT, Expand);
807 setOperationAction(ISD::SDIV, VT, Expand);
808 setOperationAction(ISD::UDIV, VT, Expand);
809 setOperationAction(ISD::FDIV, VT, Expand);
810 setOperationAction(ISD::SREM, VT, Expand);
811 setOperationAction(ISD::UREM, VT, Expand);
812 setOperationAction(ISD::LOAD, VT, Expand);
813 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
814 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
815 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
816 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
817 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
818 setOperationAction(ISD::FABS, VT, Expand);
819 setOperationAction(ISD::FSIN, VT, Expand);
820 setOperationAction(ISD::FSINCOS, VT, Expand);
821 setOperationAction(ISD::FCOS, VT, Expand);
822 setOperationAction(ISD::FSINCOS, VT, Expand);
823 setOperationAction(ISD::FREM, VT, Expand);
824 setOperationAction(ISD::FMA, VT, Expand);
825 setOperationAction(ISD::FPOWI, VT, Expand);
826 setOperationAction(ISD::FSQRT, VT, Expand);
827 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
828 setOperationAction(ISD::FFLOOR, VT, Expand);
829 setOperationAction(ISD::FCEIL, VT, Expand);
830 setOperationAction(ISD::FTRUNC, VT, Expand);
831 setOperationAction(ISD::FRINT, VT, Expand);
832 setOperationAction(ISD::FNEARBYINT, VT, Expand);
833 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
834 setOperationAction(ISD::MULHS, VT, Expand);
835 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
836 setOperationAction(ISD::MULHU, VT, Expand);
837 setOperationAction(ISD::SDIVREM, VT, Expand);
838 setOperationAction(ISD::UDIVREM, VT, Expand);
839 setOperationAction(ISD::FPOW, VT, Expand);
840 setOperationAction(ISD::CTPOP, VT, Expand);
841 setOperationAction(ISD::CTTZ, VT, Expand);
842 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
843 setOperationAction(ISD::CTLZ, VT, Expand);
844 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
845 setOperationAction(ISD::SHL, VT, Expand);
846 setOperationAction(ISD::SRA, VT, Expand);
847 setOperationAction(ISD::SRL, VT, Expand);
848 setOperationAction(ISD::ROTL, VT, Expand);
849 setOperationAction(ISD::ROTR, VT, Expand);
850 setOperationAction(ISD::BSWAP, VT, Expand);
851 setOperationAction(ISD::SETCC, VT, Expand);
852 setOperationAction(ISD::FLOG, VT, Expand);
853 setOperationAction(ISD::FLOG2, VT, Expand);
854 setOperationAction(ISD::FLOG10, VT, Expand);
855 setOperationAction(ISD::FEXP, VT, Expand);
856 setOperationAction(ISD::FEXP2, VT, Expand);
857 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
858 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
859 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
860 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
861 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
862 setOperationAction(ISD::TRUNCATE, VT, Expand);
863 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
864 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
865 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
866 setOperationAction(ISD::VSELECT, VT, Expand);
867 setOperationAction(ISD::SELECT_CC, VT, Expand);
868 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
869 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
870 setTruncStoreAction(VT,
871 (MVT::SimpleValueType)InnerVT, Expand);
872 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
873 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
874 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
877 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
878 // with -msoft-float, disable use of MMX as well.
879 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
880 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
881 // No operations on x86mmx supported, everything uses intrinsics.
884 // MMX-sized vectors (other than x86mmx) are expected to be expanded
885 // into smaller operations.
886 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
887 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
888 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
889 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
890 setOperationAction(ISD::AND, MVT::v8i8, Expand);
891 setOperationAction(ISD::AND, MVT::v4i16, Expand);
892 setOperationAction(ISD::AND, MVT::v2i32, Expand);
893 setOperationAction(ISD::AND, MVT::v1i64, Expand);
894 setOperationAction(ISD::OR, MVT::v8i8, Expand);
895 setOperationAction(ISD::OR, MVT::v4i16, Expand);
896 setOperationAction(ISD::OR, MVT::v2i32, Expand);
897 setOperationAction(ISD::OR, MVT::v1i64, Expand);
898 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
899 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
900 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
901 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
902 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
903 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
904 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
905 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
906 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
907 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
908 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
909 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
910 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
911 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
912 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
913 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
914 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
916 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
917 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
919 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
920 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
921 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
922 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
923 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
924 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
925 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
926 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
927 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
928 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
929 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
930 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
933 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
934 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
936 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
937 // registers cannot be used even for integer operations.
938 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
939 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
940 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
941 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
943 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
944 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
945 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
946 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
947 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
948 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
949 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
950 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
951 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
952 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
953 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
954 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
955 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
956 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
957 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
958 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
959 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
960 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
961 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
962 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
963 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
964 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
966 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
967 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
968 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
969 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
971 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
972 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
973 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
974 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
975 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
977 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
978 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
979 MVT VT = (MVT::SimpleValueType)i;
980 // Do not attempt to custom lower non-power-of-2 vectors
981 if (!isPowerOf2_32(VT.getVectorNumElements()))
983 // Do not attempt to custom lower non-128-bit vectors
984 if (!VT.is128BitVector())
986 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
987 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
991 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
992 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
993 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
994 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
995 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
998 if (Subtarget->is64Bit()) {
999 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1000 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1004 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1005 MVT VT = (MVT::SimpleValueType)i;
1007 // Do not attempt to promote non-128-bit vectors
1008 if (!VT.is128BitVector())
1011 setOperationAction(ISD::AND, VT, Promote);
1012 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1013 setOperationAction(ISD::OR, VT, Promote);
1014 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1015 setOperationAction(ISD::XOR, VT, Promote);
1016 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1017 setOperationAction(ISD::LOAD, VT, Promote);
1018 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1019 setOperationAction(ISD::SELECT, VT, Promote);
1020 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1023 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1025 // Custom lower v2i64 and v2f64 selects.
1026 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1027 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1028 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1029 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1031 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1032 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1034 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1035 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1036 // As there is no 64-bit GPR available, we need build a special custom
1037 // sequence to convert from v2i32 to v2f32.
1038 if (!Subtarget->is64Bit())
1039 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1041 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1042 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1044 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1046 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1047 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1048 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1051 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1052 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1055 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1057 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1058 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1059 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1060 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1061 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1063 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1064 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1065 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1066 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1067 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1068 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1069 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1070 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1071 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1072 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1074 // FIXME: Do we need to handle scalar-to-vector here?
1075 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1077 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1078 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1079 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1080 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1081 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1082 // There is no BLENDI for byte vectors. We don't need to custom lower
1083 // some vselects for now.
1084 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1086 // i8 and i16 vectors are custom , because the source register and source
1087 // source memory operand types are not the same width. f32 vectors are
1088 // custom since the immediate controlling the insert encodes additional
1090 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1091 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1092 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1093 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1095 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1096 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1097 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1098 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1100 // FIXME: these should be Legal but thats only for the case where
1101 // the index is constant. For now custom expand to deal with that.
1102 if (Subtarget->is64Bit()) {
1103 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1104 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1108 if (Subtarget->hasSSE2()) {
1109 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1110 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1112 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1113 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1115 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1116 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1118 // In the customized shift lowering, the legal cases in AVX2 will be
1120 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1121 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1123 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1124 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1126 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1129 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1130 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1131 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1132 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1133 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1134 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1135 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1137 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1138 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1139 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1141 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1142 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1143 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1145 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1146 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1147 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1148 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1149 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1150 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1151 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1152 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1154 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1156 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1158 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1159 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1160 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1161 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1162 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1163 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1164 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1165 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1167 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1168 // even though v8i16 is a legal type.
1169 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1170 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1171 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1173 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1174 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1175 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1177 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1178 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1180 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1182 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1183 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1185 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1186 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1188 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1189 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1191 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1192 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1193 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1194 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1196 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1197 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1198 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1200 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1201 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1202 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1203 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1205 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1206 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1207 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1208 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1209 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1210 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1211 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1212 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1213 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1214 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1215 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1216 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1218 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1219 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1220 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1221 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1222 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1223 setOperationAction(ISD::FMA, MVT::f32, Legal);
1224 setOperationAction(ISD::FMA, MVT::f64, Legal);
1227 if (Subtarget->hasInt256()) {
1228 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1229 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1230 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1231 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1233 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1234 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1235 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1236 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1238 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1239 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1240 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1241 // Don't lower v32i8 because there is no 128-bit byte mul
1243 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1244 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1245 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1246 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1248 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1249 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1251 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1252 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1253 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1254 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1256 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1257 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1258 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1259 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1261 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1262 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1263 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1264 // Don't lower v32i8 because there is no 128-bit byte mul
1267 // In the customized shift lowering, the legal cases in AVX2 will be
1269 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1270 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1272 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1273 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1275 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1277 // Custom lower several nodes for 256-bit types.
1278 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1279 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1280 MVT VT = (MVT::SimpleValueType)i;
1282 // Extract subvector is special because the value type
1283 // (result) is 128-bit but the source is 256-bit wide.
1284 if (VT.is128BitVector())
1285 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1287 // Do not attempt to custom lower other non-256-bit vectors
1288 if (!VT.is256BitVector())
1291 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1292 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1293 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1294 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1295 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1296 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1297 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1300 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1301 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1302 MVT VT = (MVT::SimpleValueType)i;
1304 // Do not attempt to promote non-256-bit vectors
1305 if (!VT.is256BitVector())
1308 setOperationAction(ISD::AND, VT, Promote);
1309 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1310 setOperationAction(ISD::OR, VT, Promote);
1311 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1312 setOperationAction(ISD::XOR, VT, Promote);
1313 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1314 setOperationAction(ISD::LOAD, VT, Promote);
1315 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1316 setOperationAction(ISD::SELECT, VT, Promote);
1317 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1321 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1322 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1323 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1324 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1325 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1327 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1328 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1329 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1331 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1332 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1333 setOperationAction(ISD::XOR, MVT::i1, Legal);
1334 setOperationAction(ISD::OR, MVT::i1, Legal);
1335 setOperationAction(ISD::AND, MVT::i1, Legal);
1336 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1337 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1338 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1339 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1340 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1341 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1343 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1344 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1345 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1347 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1348 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1350 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1351 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1352 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1353 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1354 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1355 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1356 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1357 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1359 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1361 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1362 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1363 if (Subtarget->is64Bit()) {
1364 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1365 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1366 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1367 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1369 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1370 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1371 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1372 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1373 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1374 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1375 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1376 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1377 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1378 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1380 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1381 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1382 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1383 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1384 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1385 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1386 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1387 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1388 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1389 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1390 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1391 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1392 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1394 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1395 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1396 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1397 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1398 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1399 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1401 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1402 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1404 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1406 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1407 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1408 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1409 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1410 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1411 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1412 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1413 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1414 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1416 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1417 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1419 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1420 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1422 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1424 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1425 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1427 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1428 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1430 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1431 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1433 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1434 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1435 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1436 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1437 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1438 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1440 // Custom lower several nodes.
1441 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1442 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1443 MVT VT = (MVT::SimpleValueType)i;
1445 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1446 // Extract subvector is special because the value type
1447 // (result) is 256/128-bit but the source is 512-bit wide.
1448 if (VT.is128BitVector() || VT.is256BitVector())
1449 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1451 if (VT.getVectorElementType() == MVT::i1)
1452 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1454 // Do not attempt to custom lower other non-512-bit vectors
1455 if (!VT.is512BitVector())
1458 if ( EltSize >= 32) {
1459 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1460 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1461 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1462 setOperationAction(ISD::VSELECT, VT, Legal);
1463 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1464 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1465 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1468 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1469 MVT VT = (MVT::SimpleValueType)i;
1471 // Do not attempt to promote non-256-bit vectors
1472 if (!VT.is512BitVector())
1475 setOperationAction(ISD::SELECT, VT, Promote);
1476 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1480 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1481 // of this type with custom code.
1482 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1483 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1484 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1488 // We want to custom lower some of our intrinsics.
1489 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1490 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1491 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1492 if (!Subtarget->is64Bit())
1493 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1495 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1496 // handle type legalization for these operations here.
1498 // FIXME: We really should do custom legalization for addition and
1499 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1500 // than generic legalization for 64-bit multiplication-with-overflow, though.
1501 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1502 // Add/Sub/Mul with overflow operations are custom lowered.
1504 setOperationAction(ISD::SADDO, VT, Custom);
1505 setOperationAction(ISD::UADDO, VT, Custom);
1506 setOperationAction(ISD::SSUBO, VT, Custom);
1507 setOperationAction(ISD::USUBO, VT, Custom);
1508 setOperationAction(ISD::SMULO, VT, Custom);
1509 setOperationAction(ISD::UMULO, VT, Custom);
1512 // There are no 8-bit 3-address imul/mul instructions
1513 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1514 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1516 if (!Subtarget->is64Bit()) {
1517 // These libcalls are not available in 32-bit.
1518 setLibcallName(RTLIB::SHL_I128, nullptr);
1519 setLibcallName(RTLIB::SRL_I128, nullptr);
1520 setLibcallName(RTLIB::SRA_I128, nullptr);
1523 // Combine sin / cos into one node or libcall if possible.
1524 if (Subtarget->hasSinCos()) {
1525 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1526 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1527 if (Subtarget->isTargetDarwin()) {
1528 // For MacOSX, we don't want to the normal expansion of a libcall to
1529 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1531 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1532 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1536 if (Subtarget->isTargetWin64()) {
1537 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1538 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1539 setOperationAction(ISD::SREM, MVT::i128, Custom);
1540 setOperationAction(ISD::UREM, MVT::i128, Custom);
1541 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1542 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1545 // We have target-specific dag combine patterns for the following nodes:
1546 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1547 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1548 setTargetDAGCombine(ISD::VSELECT);
1549 setTargetDAGCombine(ISD::SELECT);
1550 setTargetDAGCombine(ISD::SHL);
1551 setTargetDAGCombine(ISD::SRA);
1552 setTargetDAGCombine(ISD::SRL);
1553 setTargetDAGCombine(ISD::OR);
1554 setTargetDAGCombine(ISD::AND);
1555 setTargetDAGCombine(ISD::ADD);
1556 setTargetDAGCombine(ISD::FADD);
1557 setTargetDAGCombine(ISD::FSUB);
1558 setTargetDAGCombine(ISD::FMA);
1559 setTargetDAGCombine(ISD::SUB);
1560 setTargetDAGCombine(ISD::LOAD);
1561 setTargetDAGCombine(ISD::STORE);
1562 setTargetDAGCombine(ISD::ZERO_EXTEND);
1563 setTargetDAGCombine(ISD::ANY_EXTEND);
1564 setTargetDAGCombine(ISD::SIGN_EXTEND);
1565 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1566 setTargetDAGCombine(ISD::TRUNCATE);
1567 setTargetDAGCombine(ISD::SINT_TO_FP);
1568 setTargetDAGCombine(ISD::SETCC);
1569 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1570 setTargetDAGCombine(ISD::BUILD_VECTOR);
1571 if (Subtarget->is64Bit())
1572 setTargetDAGCombine(ISD::MUL);
1573 setTargetDAGCombine(ISD::XOR);
1575 computeRegisterProperties();
1577 // On Darwin, -Os means optimize for size without hurting performance,
1578 // do not reduce the limit.
1579 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1580 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1581 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1582 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1583 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1584 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1585 setPrefLoopAlignment(4); // 2^4 bytes.
1587 // Predictable cmov don't hurt on atom because it's in-order.
1588 PredictableSelectIsExpensive = !Subtarget->isAtom();
1590 setPrefFunctionAlignment(4); // 2^4 bytes.
1593 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1595 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1597 if (Subtarget->hasAVX512())
1598 switch(VT.getVectorNumElements()) {
1599 case 8: return MVT::v8i1;
1600 case 16: return MVT::v16i1;
1603 return VT.changeVectorElementTypeToInteger();
1606 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1607 /// the desired ByVal argument alignment.
1608 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1611 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1612 if (VTy->getBitWidth() == 128)
1614 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1615 unsigned EltAlign = 0;
1616 getMaxByValAlign(ATy->getElementType(), EltAlign);
1617 if (EltAlign > MaxAlign)
1618 MaxAlign = EltAlign;
1619 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1620 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1621 unsigned EltAlign = 0;
1622 getMaxByValAlign(STy->getElementType(i), EltAlign);
1623 if (EltAlign > MaxAlign)
1624 MaxAlign = EltAlign;
1631 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1632 /// function arguments in the caller parameter area. For X86, aggregates
1633 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1634 /// are at 4-byte boundaries.
1635 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1636 if (Subtarget->is64Bit()) {
1637 // Max of 8 and alignment of type.
1638 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1645 if (Subtarget->hasSSE1())
1646 getMaxByValAlign(Ty, Align);
1650 /// getOptimalMemOpType - Returns the target specific optimal type for load
1651 /// and store operations as a result of memset, memcpy, and memmove
1652 /// lowering. If DstAlign is zero that means it's safe to destination
1653 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1654 /// means there isn't a need to check it against alignment requirement,
1655 /// probably because the source does not need to be loaded. If 'IsMemset' is
1656 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1657 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1658 /// source is constant so it does not need to be loaded.
1659 /// It returns EVT::Other if the type should be determined using generic
1660 /// target-independent logic.
1662 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1663 unsigned DstAlign, unsigned SrcAlign,
1664 bool IsMemset, bool ZeroMemset,
1666 MachineFunction &MF) const {
1667 const Function *F = MF.getFunction();
1668 if ((!IsMemset || ZeroMemset) &&
1669 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1670 Attribute::NoImplicitFloat)) {
1672 (Subtarget->isUnalignedMemAccessFast() ||
1673 ((DstAlign == 0 || DstAlign >= 16) &&
1674 (SrcAlign == 0 || SrcAlign >= 16)))) {
1676 if (Subtarget->hasInt256())
1678 if (Subtarget->hasFp256())
1681 if (Subtarget->hasSSE2())
1683 if (Subtarget->hasSSE1())
1685 } else if (!MemcpyStrSrc && Size >= 8 &&
1686 !Subtarget->is64Bit() &&
1687 Subtarget->hasSSE2()) {
1688 // Do not use f64 to lower memcpy if source is string constant. It's
1689 // better to use i32 to avoid the loads.
1693 if (Subtarget->is64Bit() && Size >= 8)
1698 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1700 return X86ScalarSSEf32;
1701 else if (VT == MVT::f64)
1702 return X86ScalarSSEf64;
1707 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1711 *Fast = Subtarget->isUnalignedMemAccessFast();
1715 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1716 /// current function. The returned value is a member of the
1717 /// MachineJumpTableInfo::JTEntryKind enum.
1718 unsigned X86TargetLowering::getJumpTableEncoding() const {
1719 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1721 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1722 Subtarget->isPICStyleGOT())
1723 return MachineJumpTableInfo::EK_Custom32;
1725 // Otherwise, use the normal jump table encoding heuristics.
1726 return TargetLowering::getJumpTableEncoding();
1730 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1731 const MachineBasicBlock *MBB,
1732 unsigned uid,MCContext &Ctx) const{
1733 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1734 Subtarget->isPICStyleGOT());
1735 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1737 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1738 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1741 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1743 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1744 SelectionDAG &DAG) const {
1745 if (!Subtarget->is64Bit())
1746 // This doesn't have SDLoc associated with it, but is not really the
1747 // same as a Register.
1748 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1752 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1753 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1755 const MCExpr *X86TargetLowering::
1756 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1757 MCContext &Ctx) const {
1758 // X86-64 uses RIP relative addressing based on the jump table label.
1759 if (Subtarget->isPICStyleRIPRel())
1760 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1762 // Otherwise, the reference is relative to the PIC base.
1763 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1766 // FIXME: Why this routine is here? Move to RegInfo!
1767 std::pair<const TargetRegisterClass*, uint8_t>
1768 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1769 const TargetRegisterClass *RRC = nullptr;
1771 switch (VT.SimpleTy) {
1773 return TargetLowering::findRepresentativeClass(VT);
1774 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1775 RRC = Subtarget->is64Bit() ?
1776 (const TargetRegisterClass*)&X86::GR64RegClass :
1777 (const TargetRegisterClass*)&X86::GR32RegClass;
1780 RRC = &X86::VR64RegClass;
1782 case MVT::f32: case MVT::f64:
1783 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1784 case MVT::v4f32: case MVT::v2f64:
1785 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1787 RRC = &X86::VR128RegClass;
1790 return std::make_pair(RRC, Cost);
1793 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1794 unsigned &Offset) const {
1795 if (!Subtarget->isTargetLinux())
1798 if (Subtarget->is64Bit()) {
1799 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1801 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1813 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1814 unsigned DestAS) const {
1815 assert(SrcAS != DestAS && "Expected different address spaces!");
1817 return SrcAS < 256 && DestAS < 256;
1820 //===----------------------------------------------------------------------===//
1821 // Return Value Calling Convention Implementation
1822 //===----------------------------------------------------------------------===//
1824 #include "X86GenCallingConv.inc"
1827 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1828 MachineFunction &MF, bool isVarArg,
1829 const SmallVectorImpl<ISD::OutputArg> &Outs,
1830 LLVMContext &Context) const {
1831 SmallVector<CCValAssign, 16> RVLocs;
1832 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1834 return CCInfo.CheckReturn(Outs, RetCC_X86);
1837 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1838 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1843 X86TargetLowering::LowerReturn(SDValue Chain,
1844 CallingConv::ID CallConv, bool isVarArg,
1845 const SmallVectorImpl<ISD::OutputArg> &Outs,
1846 const SmallVectorImpl<SDValue> &OutVals,
1847 SDLoc dl, SelectionDAG &DAG) const {
1848 MachineFunction &MF = DAG.getMachineFunction();
1849 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1851 SmallVector<CCValAssign, 16> RVLocs;
1852 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1853 RVLocs, *DAG.getContext());
1854 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1857 SmallVector<SDValue, 6> RetOps;
1858 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1859 // Operand #1 = Bytes To Pop
1860 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1863 // Copy the result values into the output registers.
1864 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1865 CCValAssign &VA = RVLocs[i];
1866 assert(VA.isRegLoc() && "Can only return in registers!");
1867 SDValue ValToCopy = OutVals[i];
1868 EVT ValVT = ValToCopy.getValueType();
1870 // Promote values to the appropriate types
1871 if (VA.getLocInfo() == CCValAssign::SExt)
1872 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1873 else if (VA.getLocInfo() == CCValAssign::ZExt)
1874 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1875 else if (VA.getLocInfo() == CCValAssign::AExt)
1876 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1877 else if (VA.getLocInfo() == CCValAssign::BCvt)
1878 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1880 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1881 "Unexpected FP-extend for return value.");
1883 // If this is x86-64, and we disabled SSE, we can't return FP values,
1884 // or SSE or MMX vectors.
1885 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1886 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1887 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1888 report_fatal_error("SSE register return with SSE disabled");
1890 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1891 // llvm-gcc has never done it right and no one has noticed, so this
1892 // should be OK for now.
1893 if (ValVT == MVT::f64 &&
1894 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1895 report_fatal_error("SSE2 register return with SSE2 disabled");
1897 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1898 // the RET instruction and handled by the FP Stackifier.
1899 if (VA.getLocReg() == X86::ST0 ||
1900 VA.getLocReg() == X86::ST1) {
1901 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1902 // change the value to the FP stack register class.
1903 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1904 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1905 RetOps.push_back(ValToCopy);
1906 // Don't emit a copytoreg.
1910 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1911 // which is returned in RAX / RDX.
1912 if (Subtarget->is64Bit()) {
1913 if (ValVT == MVT::x86mmx) {
1914 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1915 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1916 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1918 // If we don't have SSE2 available, convert to v4f32 so the generated
1919 // register is legal.
1920 if (!Subtarget->hasSSE2())
1921 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1926 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1927 Flag = Chain.getValue(1);
1928 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1931 // The x86-64 ABIs require that for returning structs by value we copy
1932 // the sret argument into %rax/%eax (depending on ABI) for the return.
1933 // Win32 requires us to put the sret argument to %eax as well.
1934 // We saved the argument into a virtual register in the entry block,
1935 // so now we copy the value out and into %rax/%eax.
1936 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1937 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1938 MachineFunction &MF = DAG.getMachineFunction();
1939 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1940 unsigned Reg = FuncInfo->getSRetReturnReg();
1942 "SRetReturnReg should have been set in LowerFormalArguments().");
1943 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1946 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1947 X86::RAX : X86::EAX;
1948 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1949 Flag = Chain.getValue(1);
1951 // RAX/EAX now acts like a return value.
1952 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1955 RetOps[0] = Chain; // Update chain.
1957 // Add the flag if we have it.
1959 RetOps.push_back(Flag);
1961 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1964 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1965 if (N->getNumValues() != 1)
1967 if (!N->hasNUsesOfValue(1, 0))
1970 SDValue TCChain = Chain;
1971 SDNode *Copy = *N->use_begin();
1972 if (Copy->getOpcode() == ISD::CopyToReg) {
1973 // If the copy has a glue operand, we conservatively assume it isn't safe to
1974 // perform a tail call.
1975 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1977 TCChain = Copy->getOperand(0);
1978 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1981 bool HasRet = false;
1982 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1984 if (UI->getOpcode() != X86ISD::RET_FLAG)
1997 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1998 ISD::NodeType ExtendKind) const {
2000 // TODO: Is this also valid on 32-bit?
2001 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2002 ReturnMVT = MVT::i8;
2004 ReturnMVT = MVT::i32;
2006 MVT MinVT = getRegisterType(ReturnMVT);
2007 return VT.bitsLT(MinVT) ? MinVT : VT;
2010 /// LowerCallResult - Lower the result values of a call into the
2011 /// appropriate copies out of appropriate physical registers.
2014 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2015 CallingConv::ID CallConv, bool isVarArg,
2016 const SmallVectorImpl<ISD::InputArg> &Ins,
2017 SDLoc dl, SelectionDAG &DAG,
2018 SmallVectorImpl<SDValue> &InVals) const {
2020 // Assign locations to each value returned by this call.
2021 SmallVector<CCValAssign, 16> RVLocs;
2022 bool Is64Bit = Subtarget->is64Bit();
2023 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2024 getTargetMachine(), RVLocs, *DAG.getContext());
2025 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2027 // Copy all of the result registers out of their specified physreg.
2028 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2029 CCValAssign &VA = RVLocs[i];
2030 EVT CopyVT = VA.getValVT();
2032 // If this is x86-64, and we disabled SSE, we can't return FP values
2033 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2034 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2035 report_fatal_error("SSE register return with SSE disabled");
2040 // If this is a call to a function that returns an fp value on the floating
2041 // point stack, we must guarantee the value is popped from the stack, so
2042 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2043 // if the return value is not used. We use the FpPOP_RETVAL instruction
2045 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2046 // If we prefer to use the value in xmm registers, copy it out as f80 and
2047 // use a truncate to move it from fp stack reg to xmm reg.
2048 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2049 SDValue Ops[] = { Chain, InFlag };
2050 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2051 MVT::Other, MVT::Glue, Ops), 1);
2052 Val = Chain.getValue(0);
2054 // Round the f80 to the right size, which also moves it to the appropriate
2056 if (CopyVT != VA.getValVT())
2057 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2058 // This truncation won't change the value.
2059 DAG.getIntPtrConstant(1));
2061 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2062 CopyVT, InFlag).getValue(1);
2063 Val = Chain.getValue(0);
2065 InFlag = Chain.getValue(2);
2066 InVals.push_back(Val);
2072 //===----------------------------------------------------------------------===//
2073 // C & StdCall & Fast Calling Convention implementation
2074 //===----------------------------------------------------------------------===//
2075 // StdCall calling convention seems to be standard for many Windows' API
2076 // routines and around. It differs from C calling convention just a little:
2077 // callee should clean up the stack, not caller. Symbols should be also
2078 // decorated in some fancy way :) It doesn't support any vector arguments.
2079 // For info on fast calling convention see Fast Calling Convention (tail call)
2080 // implementation LowerX86_32FastCCCallTo.
2082 /// CallIsStructReturn - Determines whether a call uses struct return
2084 enum StructReturnType {
2089 static StructReturnType
2090 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2092 return NotStructReturn;
2094 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2095 if (!Flags.isSRet())
2096 return NotStructReturn;
2097 if (Flags.isInReg())
2098 return RegStructReturn;
2099 return StackStructReturn;
2102 /// ArgsAreStructReturn - Determines whether a function uses struct
2103 /// return semantics.
2104 static StructReturnType
2105 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2107 return NotStructReturn;
2109 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2110 if (!Flags.isSRet())
2111 return NotStructReturn;
2112 if (Flags.isInReg())
2113 return RegStructReturn;
2114 return StackStructReturn;
2117 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2118 /// by "Src" to address "Dst" with size and alignment information specified by
2119 /// the specific parameter attribute. The copy will be passed as a byval
2120 /// function parameter.
2122 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2123 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2125 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2127 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2128 /*isVolatile*/false, /*AlwaysInline=*/true,
2129 MachinePointerInfo(), MachinePointerInfo());
2132 /// IsTailCallConvention - Return true if the calling convention is one that
2133 /// supports tail call optimization.
2134 static bool IsTailCallConvention(CallingConv::ID CC) {
2135 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2136 CC == CallingConv::HiPE);
2139 /// \brief Return true if the calling convention is a C calling convention.
2140 static bool IsCCallConvention(CallingConv::ID CC) {
2141 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2142 CC == CallingConv::X86_64_SysV);
2145 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2146 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2150 CallingConv::ID CalleeCC = CS.getCallingConv();
2151 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2157 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2158 /// a tailcall target by changing its ABI.
2159 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2160 bool GuaranteedTailCallOpt) {
2161 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2165 X86TargetLowering::LowerMemArgument(SDValue Chain,
2166 CallingConv::ID CallConv,
2167 const SmallVectorImpl<ISD::InputArg> &Ins,
2168 SDLoc dl, SelectionDAG &DAG,
2169 const CCValAssign &VA,
2170 MachineFrameInfo *MFI,
2172 // Create the nodes corresponding to a load from this parameter slot.
2173 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2174 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2175 getTargetMachine().Options.GuaranteedTailCallOpt);
2176 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2179 // If value is passed by pointer we have address passed instead of the value
2181 if (VA.getLocInfo() == CCValAssign::Indirect)
2182 ValVT = VA.getLocVT();
2184 ValVT = VA.getValVT();
2186 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2187 // changed with more analysis.
2188 // In case of tail call optimization mark all arguments mutable. Since they
2189 // could be overwritten by lowering of arguments in case of a tail call.
2190 if (Flags.isByVal()) {
2191 unsigned Bytes = Flags.getByValSize();
2192 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2193 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2194 return DAG.getFrameIndex(FI, getPointerTy());
2196 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2197 VA.getLocMemOffset(), isImmutable);
2198 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2199 return DAG.getLoad(ValVT, dl, Chain, FIN,
2200 MachinePointerInfo::getFixedStack(FI),
2201 false, false, false, 0);
2206 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2207 CallingConv::ID CallConv,
2209 const SmallVectorImpl<ISD::InputArg> &Ins,
2212 SmallVectorImpl<SDValue> &InVals)
2214 MachineFunction &MF = DAG.getMachineFunction();
2215 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2217 const Function* Fn = MF.getFunction();
2218 if (Fn->hasExternalLinkage() &&
2219 Subtarget->isTargetCygMing() &&
2220 Fn->getName() == "main")
2221 FuncInfo->setForceFramePointer(true);
2223 MachineFrameInfo *MFI = MF.getFrameInfo();
2224 bool Is64Bit = Subtarget->is64Bit();
2225 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2227 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2228 "Var args not supported with calling convention fastcc, ghc or hipe");
2230 // Assign locations to all of the incoming arguments.
2231 SmallVector<CCValAssign, 16> ArgLocs;
2232 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2233 ArgLocs, *DAG.getContext());
2235 // Allocate shadow area for Win64
2237 CCInfo.AllocateStack(32, 8);
2239 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2241 unsigned LastVal = ~0U;
2243 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2244 CCValAssign &VA = ArgLocs[i];
2245 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2247 assert(VA.getValNo() != LastVal &&
2248 "Don't support value assigned to multiple locs yet");
2250 LastVal = VA.getValNo();
2252 if (VA.isRegLoc()) {
2253 EVT RegVT = VA.getLocVT();
2254 const TargetRegisterClass *RC;
2255 if (RegVT == MVT::i32)
2256 RC = &X86::GR32RegClass;
2257 else if (Is64Bit && RegVT == MVT::i64)
2258 RC = &X86::GR64RegClass;
2259 else if (RegVT == MVT::f32)
2260 RC = &X86::FR32RegClass;
2261 else if (RegVT == MVT::f64)
2262 RC = &X86::FR64RegClass;
2263 else if (RegVT.is512BitVector())
2264 RC = &X86::VR512RegClass;
2265 else if (RegVT.is256BitVector())
2266 RC = &X86::VR256RegClass;
2267 else if (RegVT.is128BitVector())
2268 RC = &X86::VR128RegClass;
2269 else if (RegVT == MVT::x86mmx)
2270 RC = &X86::VR64RegClass;
2271 else if (RegVT == MVT::i1)
2272 RC = &X86::VK1RegClass;
2273 else if (RegVT == MVT::v8i1)
2274 RC = &X86::VK8RegClass;
2275 else if (RegVT == MVT::v16i1)
2276 RC = &X86::VK16RegClass;
2278 llvm_unreachable("Unknown argument type!");
2280 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2281 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2283 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2284 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2286 if (VA.getLocInfo() == CCValAssign::SExt)
2287 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2288 DAG.getValueType(VA.getValVT()));
2289 else if (VA.getLocInfo() == CCValAssign::ZExt)
2290 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2291 DAG.getValueType(VA.getValVT()));
2292 else if (VA.getLocInfo() == CCValAssign::BCvt)
2293 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2295 if (VA.isExtInLoc()) {
2296 // Handle MMX values passed in XMM regs.
2297 if (RegVT.isVector())
2298 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2300 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2303 assert(VA.isMemLoc());
2304 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2307 // If value is passed via pointer - do a load.
2308 if (VA.getLocInfo() == CCValAssign::Indirect)
2309 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2310 MachinePointerInfo(), false, false, false, 0);
2312 InVals.push_back(ArgValue);
2315 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2316 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2317 // The x86-64 ABIs require that for returning structs by value we copy
2318 // the sret argument into %rax/%eax (depending on ABI) for the return.
2319 // Win32 requires us to put the sret argument to %eax as well.
2320 // Save the argument into a virtual register so that we can access it
2321 // from the return points.
2322 if (Ins[i].Flags.isSRet()) {
2323 unsigned Reg = FuncInfo->getSRetReturnReg();
2325 MVT PtrTy = getPointerTy();
2326 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2327 FuncInfo->setSRetReturnReg(Reg);
2329 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2330 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2336 unsigned StackSize = CCInfo.getNextStackOffset();
2337 // Align stack specially for tail calls.
2338 if (FuncIsMadeTailCallSafe(CallConv,
2339 MF.getTarget().Options.GuaranteedTailCallOpt))
2340 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2342 // If the function takes variable number of arguments, make a frame index for
2343 // the start of the first vararg value... for expansion of llvm.va_start.
2345 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2346 CallConv != CallingConv::X86_ThisCall)) {
2347 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2350 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2352 // FIXME: We should really autogenerate these arrays
2353 static const MCPhysReg GPR64ArgRegsWin64[] = {
2354 X86::RCX, X86::RDX, X86::R8, X86::R9
2356 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2357 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2359 static const MCPhysReg XMMArgRegs64Bit[] = {
2360 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2361 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2363 const MCPhysReg *GPR64ArgRegs;
2364 unsigned NumXMMRegs = 0;
2367 // The XMM registers which might contain var arg parameters are shadowed
2368 // in their paired GPR. So we only need to save the GPR to their home
2370 TotalNumIntRegs = 4;
2371 GPR64ArgRegs = GPR64ArgRegsWin64;
2373 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2374 GPR64ArgRegs = GPR64ArgRegs64Bit;
2376 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2379 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2382 bool NoImplicitFloatOps = Fn->getAttributes().
2383 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2384 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2385 "SSE register cannot be used when SSE is disabled!");
2386 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2387 NoImplicitFloatOps) &&
2388 "SSE register cannot be used when SSE is disabled!");
2389 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2390 !Subtarget->hasSSE1())
2391 // Kernel mode asks for SSE to be disabled, so don't push them
2393 TotalNumXMMRegs = 0;
2396 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2397 // Get to the caller-allocated home save location. Add 8 to account
2398 // for the return address.
2399 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2400 FuncInfo->setRegSaveFrameIndex(
2401 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2402 // Fixup to set vararg frame on shadow area (4 x i64).
2404 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2406 // For X86-64, if there are vararg parameters that are passed via
2407 // registers, then we must store them to their spots on the stack so
2408 // they may be loaded by deferencing the result of va_next.
2409 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2410 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2411 FuncInfo->setRegSaveFrameIndex(
2412 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2416 // Store the integer parameter registers.
2417 SmallVector<SDValue, 8> MemOps;
2418 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2420 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2421 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2422 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2423 DAG.getIntPtrConstant(Offset));
2424 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2425 &X86::GR64RegClass);
2426 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2428 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2429 MachinePointerInfo::getFixedStack(
2430 FuncInfo->getRegSaveFrameIndex(), Offset),
2432 MemOps.push_back(Store);
2436 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2437 // Now store the XMM (fp + vector) parameter registers.
2438 SmallVector<SDValue, 11> SaveXMMOps;
2439 SaveXMMOps.push_back(Chain);
2441 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2442 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2443 SaveXMMOps.push_back(ALVal);
2445 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2446 FuncInfo->getRegSaveFrameIndex()));
2447 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2448 FuncInfo->getVarArgsFPOffset()));
2450 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2451 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2452 &X86::VR128RegClass);
2453 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2454 SaveXMMOps.push_back(Val);
2456 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2457 MVT::Other, SaveXMMOps));
2460 if (!MemOps.empty())
2461 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2465 // Some CCs need callee pop.
2466 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2467 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2468 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2470 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2471 // If this is an sret function, the return should pop the hidden pointer.
2472 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2473 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2474 argsAreStructReturn(Ins) == StackStructReturn)
2475 FuncInfo->setBytesToPopOnReturn(4);
2479 // RegSaveFrameIndex is X86-64 only.
2480 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2481 if (CallConv == CallingConv::X86_FastCall ||
2482 CallConv == CallingConv::X86_ThisCall)
2483 // fastcc functions can't have varargs.
2484 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2487 FuncInfo->setArgumentStackSize(StackSize);
2493 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2494 SDValue StackPtr, SDValue Arg,
2495 SDLoc dl, SelectionDAG &DAG,
2496 const CCValAssign &VA,
2497 ISD::ArgFlagsTy Flags) const {
2498 unsigned LocMemOffset = VA.getLocMemOffset();
2499 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2500 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2501 if (Flags.isByVal())
2502 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2504 return DAG.getStore(Chain, dl, Arg, PtrOff,
2505 MachinePointerInfo::getStack(LocMemOffset),
2509 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2510 /// optimization is performed and it is required.
2512 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2513 SDValue &OutRetAddr, SDValue Chain,
2514 bool IsTailCall, bool Is64Bit,
2515 int FPDiff, SDLoc dl) const {
2516 // Adjust the Return address stack slot.
2517 EVT VT = getPointerTy();
2518 OutRetAddr = getReturnAddressFrameIndex(DAG);
2520 // Load the "old" Return address.
2521 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2522 false, false, false, 0);
2523 return SDValue(OutRetAddr.getNode(), 1);
2526 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2527 /// optimization is performed and it is required (FPDiff!=0).
2528 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2529 SDValue Chain, SDValue RetAddrFrIdx,
2530 EVT PtrVT, unsigned SlotSize,
2531 int FPDiff, SDLoc dl) {
2532 // Store the return address to the appropriate stack slot.
2533 if (!FPDiff) return Chain;
2534 // Calculate the new stack slot for the return address.
2535 int NewReturnAddrFI =
2536 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2538 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2539 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2540 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2546 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2547 SmallVectorImpl<SDValue> &InVals) const {
2548 SelectionDAG &DAG = CLI.DAG;
2550 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2551 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2552 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2553 SDValue Chain = CLI.Chain;
2554 SDValue Callee = CLI.Callee;
2555 CallingConv::ID CallConv = CLI.CallConv;
2556 bool &isTailCall = CLI.IsTailCall;
2557 bool isVarArg = CLI.IsVarArg;
2559 MachineFunction &MF = DAG.getMachineFunction();
2560 bool Is64Bit = Subtarget->is64Bit();
2561 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2562 StructReturnType SR = callIsStructReturn(Outs);
2563 bool IsSibcall = false;
2565 if (MF.getTarget().Options.DisableTailCalls)
2568 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2570 // Force this to be a tail call. The verifier rules are enough to ensure
2571 // that we can lower this successfully without moving the return address
2574 } else if (isTailCall) {
2575 // Check if it's really possible to do a tail call.
2576 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2577 isVarArg, SR != NotStructReturn,
2578 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2579 Outs, OutVals, Ins, DAG);
2581 // Sibcalls are automatically detected tailcalls which do not require
2583 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2590 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2591 "Var args not supported with calling convention fastcc, ghc or hipe");
2593 // Analyze operands of the call, assigning locations to each operand.
2594 SmallVector<CCValAssign, 16> ArgLocs;
2595 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2596 ArgLocs, *DAG.getContext());
2598 // Allocate shadow area for Win64
2600 CCInfo.AllocateStack(32, 8);
2602 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2604 // Get a count of how many bytes are to be pushed on the stack.
2605 unsigned NumBytes = CCInfo.getNextStackOffset();
2607 // This is a sibcall. The memory operands are available in caller's
2608 // own caller's stack.
2610 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2611 IsTailCallConvention(CallConv))
2612 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2615 if (isTailCall && !IsSibcall && !IsMustTail) {
2616 // Lower arguments at fp - stackoffset + fpdiff.
2617 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2618 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2620 FPDiff = NumBytesCallerPushed - NumBytes;
2622 // Set the delta of movement of the returnaddr stackslot.
2623 // But only set if delta is greater than previous delta.
2624 if (FPDiff < X86Info->getTCReturnAddrDelta())
2625 X86Info->setTCReturnAddrDelta(FPDiff);
2628 unsigned NumBytesToPush = NumBytes;
2629 unsigned NumBytesToPop = NumBytes;
2631 // If we have an inalloca argument, all stack space has already been allocated
2632 // for us and be right at the top of the stack. We don't support multiple
2633 // arguments passed in memory when using inalloca.
2634 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2636 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2637 "an inalloca argument must be the only memory argument");
2641 Chain = DAG.getCALLSEQ_START(
2642 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2644 SDValue RetAddrFrIdx;
2645 // Load return address for tail calls.
2646 if (isTailCall && FPDiff)
2647 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2648 Is64Bit, FPDiff, dl);
2650 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2651 SmallVector<SDValue, 8> MemOpChains;
2654 // Walk the register/memloc assignments, inserting copies/loads. In the case
2655 // of tail call optimization arguments are handle later.
2656 const X86RegisterInfo *RegInfo =
2657 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2658 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2659 // Skip inalloca arguments, they have already been written.
2660 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2661 if (Flags.isInAlloca())
2664 CCValAssign &VA = ArgLocs[i];
2665 EVT RegVT = VA.getLocVT();
2666 SDValue Arg = OutVals[i];
2667 bool isByVal = Flags.isByVal();
2669 // Promote the value if needed.
2670 switch (VA.getLocInfo()) {
2671 default: llvm_unreachable("Unknown loc info!");
2672 case CCValAssign::Full: break;
2673 case CCValAssign::SExt:
2674 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2676 case CCValAssign::ZExt:
2677 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2679 case CCValAssign::AExt:
2680 if (RegVT.is128BitVector()) {
2681 // Special case: passing MMX values in XMM registers.
2682 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2683 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2684 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2686 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2688 case CCValAssign::BCvt:
2689 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2691 case CCValAssign::Indirect: {
2692 // Store the argument.
2693 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2694 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2695 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2696 MachinePointerInfo::getFixedStack(FI),
2703 if (VA.isRegLoc()) {
2704 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2705 if (isVarArg && IsWin64) {
2706 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2707 // shadow reg if callee is a varargs function.
2708 unsigned ShadowReg = 0;
2709 switch (VA.getLocReg()) {
2710 case X86::XMM0: ShadowReg = X86::RCX; break;
2711 case X86::XMM1: ShadowReg = X86::RDX; break;
2712 case X86::XMM2: ShadowReg = X86::R8; break;
2713 case X86::XMM3: ShadowReg = X86::R9; break;
2716 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2718 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2719 assert(VA.isMemLoc());
2720 if (!StackPtr.getNode())
2721 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2723 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2724 dl, DAG, VA, Flags));
2728 if (!MemOpChains.empty())
2729 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2731 if (Subtarget->isPICStyleGOT()) {
2732 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2735 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2736 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2738 // If we are tail calling and generating PIC/GOT style code load the
2739 // address of the callee into ECX. The value in ecx is used as target of
2740 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2741 // for tail calls on PIC/GOT architectures. Normally we would just put the
2742 // address of GOT into ebx and then call target@PLT. But for tail calls
2743 // ebx would be restored (since ebx is callee saved) before jumping to the
2746 // Note: The actual moving to ECX is done further down.
2747 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2748 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2749 !G->getGlobal()->hasProtectedVisibility())
2750 Callee = LowerGlobalAddress(Callee, DAG);
2751 else if (isa<ExternalSymbolSDNode>(Callee))
2752 Callee = LowerExternalSymbol(Callee, DAG);
2756 if (Is64Bit && isVarArg && !IsWin64) {
2757 // From AMD64 ABI document:
2758 // For calls that may call functions that use varargs or stdargs
2759 // (prototype-less calls or calls to functions containing ellipsis (...) in
2760 // the declaration) %al is used as hidden argument to specify the number
2761 // of SSE registers used. The contents of %al do not need to match exactly
2762 // the number of registers, but must be an ubound on the number of SSE
2763 // registers used and is in the range 0 - 8 inclusive.
2765 // Count the number of XMM registers allocated.
2766 static const MCPhysReg XMMArgRegs[] = {
2767 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2768 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2770 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2771 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2772 && "SSE registers cannot be used when SSE is disabled");
2774 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2775 DAG.getConstant(NumXMMRegs, MVT::i8)));
2778 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2779 // don't need this because the eligibility check rejects calls that require
2780 // shuffling arguments passed in memory.
2781 if (!IsSibcall && isTailCall) {
2782 // Force all the incoming stack arguments to be loaded from the stack
2783 // before any new outgoing arguments are stored to the stack, because the
2784 // outgoing stack slots may alias the incoming argument stack slots, and
2785 // the alias isn't otherwise explicit. This is slightly more conservative
2786 // than necessary, because it means that each store effectively depends
2787 // on every argument instead of just those arguments it would clobber.
2788 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2790 SmallVector<SDValue, 8> MemOpChains2;
2793 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2794 CCValAssign &VA = ArgLocs[i];
2797 assert(VA.isMemLoc());
2798 SDValue Arg = OutVals[i];
2799 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2800 // Skip inalloca arguments. They don't require any work.
2801 if (Flags.isInAlloca())
2803 // Create frame index.
2804 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2805 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2806 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2807 FIN = DAG.getFrameIndex(FI, getPointerTy());
2809 if (Flags.isByVal()) {
2810 // Copy relative to framepointer.
2811 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2812 if (!StackPtr.getNode())
2813 StackPtr = DAG.getCopyFromReg(Chain, dl,
2814 RegInfo->getStackRegister(),
2816 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2818 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2822 // Store relative to framepointer.
2823 MemOpChains2.push_back(
2824 DAG.getStore(ArgChain, dl, Arg, FIN,
2825 MachinePointerInfo::getFixedStack(FI),
2830 if (!MemOpChains2.empty())
2831 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2833 // Store the return address to the appropriate stack slot.
2834 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2835 getPointerTy(), RegInfo->getSlotSize(),
2839 // Build a sequence of copy-to-reg nodes chained together with token chain
2840 // and flag operands which copy the outgoing args into registers.
2842 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2843 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2844 RegsToPass[i].second, InFlag);
2845 InFlag = Chain.getValue(1);
2848 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2849 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2850 // In the 64-bit large code model, we have to make all calls
2851 // through a register, since the call instruction's 32-bit
2852 // pc-relative offset may not be large enough to hold the whole
2854 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2855 // If the callee is a GlobalAddress node (quite common, every direct call
2856 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2859 // We should use extra load for direct calls to dllimported functions in
2861 const GlobalValue *GV = G->getGlobal();
2862 if (!GV->hasDLLImportStorageClass()) {
2863 unsigned char OpFlags = 0;
2864 bool ExtraLoad = false;
2865 unsigned WrapperKind = ISD::DELETED_NODE;
2867 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2868 // external symbols most go through the PLT in PIC mode. If the symbol
2869 // has hidden or protected visibility, or if it is static or local, then
2870 // we don't need to use the PLT - we can directly call it.
2871 if (Subtarget->isTargetELF() &&
2872 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2873 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2874 OpFlags = X86II::MO_PLT;
2875 } else if (Subtarget->isPICStyleStubAny() &&
2876 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2877 (!Subtarget->getTargetTriple().isMacOSX() ||
2878 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2879 // PC-relative references to external symbols should go through $stub,
2880 // unless we're building with the leopard linker or later, which
2881 // automatically synthesizes these stubs.
2882 OpFlags = X86II::MO_DARWIN_STUB;
2883 } else if (Subtarget->isPICStyleRIPRel() &&
2884 isa<Function>(GV) &&
2885 cast<Function>(GV)->getAttributes().
2886 hasAttribute(AttributeSet::FunctionIndex,
2887 Attribute::NonLazyBind)) {
2888 // If the function is marked as non-lazy, generate an indirect call
2889 // which loads from the GOT directly. This avoids runtime overhead
2890 // at the cost of eager binding (and one extra byte of encoding).
2891 OpFlags = X86II::MO_GOTPCREL;
2892 WrapperKind = X86ISD::WrapperRIP;
2896 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2897 G->getOffset(), OpFlags);
2899 // Add a wrapper if needed.
2900 if (WrapperKind != ISD::DELETED_NODE)
2901 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2902 // Add extra indirection if needed.
2904 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2905 MachinePointerInfo::getGOT(),
2906 false, false, false, 0);
2908 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2909 unsigned char OpFlags = 0;
2911 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2912 // external symbols should go through the PLT.
2913 if (Subtarget->isTargetELF() &&
2914 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2915 OpFlags = X86II::MO_PLT;
2916 } else if (Subtarget->isPICStyleStubAny() &&
2917 (!Subtarget->getTargetTriple().isMacOSX() ||
2918 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2919 // PC-relative references to external symbols should go through $stub,
2920 // unless we're building with the leopard linker or later, which
2921 // automatically synthesizes these stubs.
2922 OpFlags = X86II::MO_DARWIN_STUB;
2925 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2929 // Returns a chain & a flag for retval copy to use.
2930 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2931 SmallVector<SDValue, 8> Ops;
2933 if (!IsSibcall && isTailCall) {
2934 Chain = DAG.getCALLSEQ_END(Chain,
2935 DAG.getIntPtrConstant(NumBytesToPop, true),
2936 DAG.getIntPtrConstant(0, true), InFlag, dl);
2937 InFlag = Chain.getValue(1);
2940 Ops.push_back(Chain);
2941 Ops.push_back(Callee);
2944 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2946 // Add argument registers to the end of the list so that they are known live
2948 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2949 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2950 RegsToPass[i].second.getValueType()));
2952 // Add a register mask operand representing the call-preserved registers.
2953 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2954 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2955 assert(Mask && "Missing call preserved mask for calling convention");
2956 Ops.push_back(DAG.getRegisterMask(Mask));
2958 if (InFlag.getNode())
2959 Ops.push_back(InFlag);
2963 //// If this is the first return lowered for this function, add the regs
2964 //// to the liveout set for the function.
2965 // This isn't right, although it's probably harmless on x86; liveouts
2966 // should be computed from returns not tail calls. Consider a void
2967 // function making a tail call to a function returning int.
2968 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2971 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2972 InFlag = Chain.getValue(1);
2974 // Create the CALLSEQ_END node.
2975 unsigned NumBytesForCalleeToPop;
2976 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2977 getTargetMachine().Options.GuaranteedTailCallOpt))
2978 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2979 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2980 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2981 SR == StackStructReturn)
2982 // If this is a call to a struct-return function, the callee
2983 // pops the hidden struct pointer, so we have to push it back.
2984 // This is common for Darwin/X86, Linux & Mingw32 targets.
2985 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2986 NumBytesForCalleeToPop = 4;
2988 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2990 // Returns a flag for retval copy to use.
2992 Chain = DAG.getCALLSEQ_END(Chain,
2993 DAG.getIntPtrConstant(NumBytesToPop, true),
2994 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2997 InFlag = Chain.getValue(1);
3000 // Handle result values, copying them out of physregs into vregs that we
3002 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3003 Ins, dl, DAG, InVals);
3006 //===----------------------------------------------------------------------===//
3007 // Fast Calling Convention (tail call) implementation
3008 //===----------------------------------------------------------------------===//
3010 // Like std call, callee cleans arguments, convention except that ECX is
3011 // reserved for storing the tail called function address. Only 2 registers are
3012 // free for argument passing (inreg). Tail call optimization is performed
3014 // * tailcallopt is enabled
3015 // * caller/callee are fastcc
3016 // On X86_64 architecture with GOT-style position independent code only local
3017 // (within module) calls are supported at the moment.
3018 // To keep the stack aligned according to platform abi the function
3019 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3020 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3021 // If a tail called function callee has more arguments than the caller the
3022 // caller needs to make sure that there is room to move the RETADDR to. This is
3023 // achieved by reserving an area the size of the argument delta right after the
3024 // original REtADDR, but before the saved framepointer or the spilled registers
3025 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3037 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3038 /// for a 16 byte align requirement.
3040 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3041 SelectionDAG& DAG) const {
3042 MachineFunction &MF = DAG.getMachineFunction();
3043 const TargetMachine &TM = MF.getTarget();
3044 const X86RegisterInfo *RegInfo =
3045 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3046 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3047 unsigned StackAlignment = TFI.getStackAlignment();
3048 uint64_t AlignMask = StackAlignment - 1;
3049 int64_t Offset = StackSize;
3050 unsigned SlotSize = RegInfo->getSlotSize();
3051 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3052 // Number smaller than 12 so just add the difference.
3053 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3055 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3056 Offset = ((~AlignMask) & Offset) + StackAlignment +
3057 (StackAlignment-SlotSize);
3062 /// MatchingStackOffset - Return true if the given stack call argument is
3063 /// already available in the same position (relatively) of the caller's
3064 /// incoming argument stack.
3066 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3067 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3068 const X86InstrInfo *TII) {
3069 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3071 if (Arg.getOpcode() == ISD::CopyFromReg) {
3072 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3073 if (!TargetRegisterInfo::isVirtualRegister(VR))
3075 MachineInstr *Def = MRI->getVRegDef(VR);
3078 if (!Flags.isByVal()) {
3079 if (!TII->isLoadFromStackSlot(Def, FI))
3082 unsigned Opcode = Def->getOpcode();
3083 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3084 Def->getOperand(1).isFI()) {
3085 FI = Def->getOperand(1).getIndex();
3086 Bytes = Flags.getByValSize();
3090 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3091 if (Flags.isByVal())
3092 // ByVal argument is passed in as a pointer but it's now being
3093 // dereferenced. e.g.
3094 // define @foo(%struct.X* %A) {
3095 // tail call @bar(%struct.X* byval %A)
3098 SDValue Ptr = Ld->getBasePtr();
3099 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3102 FI = FINode->getIndex();
3103 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3104 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3105 FI = FINode->getIndex();
3106 Bytes = Flags.getByValSize();
3110 assert(FI != INT_MAX);
3111 if (!MFI->isFixedObjectIndex(FI))
3113 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3116 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3117 /// for tail call optimization. Targets which want to do tail call
3118 /// optimization should implement this function.
3120 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3121 CallingConv::ID CalleeCC,
3123 bool isCalleeStructRet,
3124 bool isCallerStructRet,
3126 const SmallVectorImpl<ISD::OutputArg> &Outs,
3127 const SmallVectorImpl<SDValue> &OutVals,
3128 const SmallVectorImpl<ISD::InputArg> &Ins,
3129 SelectionDAG &DAG) const {
3130 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3133 // If -tailcallopt is specified, make fastcc functions tail-callable.
3134 const MachineFunction &MF = DAG.getMachineFunction();
3135 const Function *CallerF = MF.getFunction();
3137 // If the function return type is x86_fp80 and the callee return type is not,
3138 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3139 // perform a tailcall optimization here.
3140 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3143 CallingConv::ID CallerCC = CallerF->getCallingConv();
3144 bool CCMatch = CallerCC == CalleeCC;
3145 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3146 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3148 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3149 if (IsTailCallConvention(CalleeCC) && CCMatch)
3154 // Look for obvious safe cases to perform tail call optimization that do not
3155 // require ABI changes. This is what gcc calls sibcall.
3157 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3158 // emit a special epilogue.
3159 const X86RegisterInfo *RegInfo =
3160 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3161 if (RegInfo->needsStackRealignment(MF))
3164 // Also avoid sibcall optimization if either caller or callee uses struct
3165 // return semantics.
3166 if (isCalleeStructRet || isCallerStructRet)
3169 // An stdcall/thiscall caller is expected to clean up its arguments; the
3170 // callee isn't going to do that.
3171 // FIXME: this is more restrictive than needed. We could produce a tailcall
3172 // when the stack adjustment matches. For example, with a thiscall that takes
3173 // only one argument.
3174 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3175 CallerCC == CallingConv::X86_ThisCall))
3178 // Do not sibcall optimize vararg calls unless all arguments are passed via
3180 if (isVarArg && !Outs.empty()) {
3182 // Optimizing for varargs on Win64 is unlikely to be safe without
3183 // additional testing.
3184 if (IsCalleeWin64 || IsCallerWin64)
3187 SmallVector<CCValAssign, 16> ArgLocs;
3188 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3189 getTargetMachine(), ArgLocs, *DAG.getContext());
3191 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3192 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3193 if (!ArgLocs[i].isRegLoc())
3197 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3198 // stack. Therefore, if it's not used by the call it is not safe to optimize
3199 // this into a sibcall.
3200 bool Unused = false;
3201 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3208 SmallVector<CCValAssign, 16> RVLocs;
3209 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3210 getTargetMachine(), RVLocs, *DAG.getContext());
3211 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3212 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3213 CCValAssign &VA = RVLocs[i];
3214 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3219 // If the calling conventions do not match, then we'd better make sure the
3220 // results are returned in the same way as what the caller expects.
3222 SmallVector<CCValAssign, 16> RVLocs1;
3223 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3224 getTargetMachine(), RVLocs1, *DAG.getContext());
3225 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3227 SmallVector<CCValAssign, 16> RVLocs2;
3228 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3229 getTargetMachine(), RVLocs2, *DAG.getContext());
3230 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3232 if (RVLocs1.size() != RVLocs2.size())
3234 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3235 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3237 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3239 if (RVLocs1[i].isRegLoc()) {
3240 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3243 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3249 // If the callee takes no arguments then go on to check the results of the
3251 if (!Outs.empty()) {
3252 // Check if stack adjustment is needed. For now, do not do this if any
3253 // argument is passed on the stack.
3254 SmallVector<CCValAssign, 16> ArgLocs;
3255 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3256 getTargetMachine(), ArgLocs, *DAG.getContext());
3258 // Allocate shadow area for Win64
3260 CCInfo.AllocateStack(32, 8);
3262 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3263 if (CCInfo.getNextStackOffset()) {
3264 MachineFunction &MF = DAG.getMachineFunction();
3265 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3268 // Check if the arguments are already laid out in the right way as
3269 // the caller's fixed stack objects.
3270 MachineFrameInfo *MFI = MF.getFrameInfo();
3271 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3272 const X86InstrInfo *TII =
3273 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3274 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3275 CCValAssign &VA = ArgLocs[i];
3276 SDValue Arg = OutVals[i];
3277 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3278 if (VA.getLocInfo() == CCValAssign::Indirect)
3280 if (!VA.isRegLoc()) {
3281 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3288 // If the tailcall address may be in a register, then make sure it's
3289 // possible to register allocate for it. In 32-bit, the call address can
3290 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3291 // callee-saved registers are restored. These happen to be the same
3292 // registers used to pass 'inreg' arguments so watch out for those.
3293 if (!Subtarget->is64Bit() &&
3294 ((!isa<GlobalAddressSDNode>(Callee) &&
3295 !isa<ExternalSymbolSDNode>(Callee)) ||
3296 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3297 unsigned NumInRegs = 0;
3298 // In PIC we need an extra register to formulate the address computation
3300 unsigned MaxInRegs =
3301 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3303 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3304 CCValAssign &VA = ArgLocs[i];
3307 unsigned Reg = VA.getLocReg();
3310 case X86::EAX: case X86::EDX: case X86::ECX:
3311 if (++NumInRegs == MaxInRegs)
3323 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3324 const TargetLibraryInfo *libInfo) const {
3325 return X86::createFastISel(funcInfo, libInfo);
3328 //===----------------------------------------------------------------------===//
3329 // Other Lowering Hooks
3330 //===----------------------------------------------------------------------===//
3332 static bool MayFoldLoad(SDValue Op) {
3333 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3336 static bool MayFoldIntoStore(SDValue Op) {
3337 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3340 static bool isTargetShuffle(unsigned Opcode) {
3342 default: return false;
3343 case X86ISD::PSHUFD:
3344 case X86ISD::PSHUFHW:
3345 case X86ISD::PSHUFLW:
3347 case X86ISD::PALIGNR:
3348 case X86ISD::MOVLHPS:
3349 case X86ISD::MOVLHPD:
3350 case X86ISD::MOVHLPS:
3351 case X86ISD::MOVLPS:
3352 case X86ISD::MOVLPD:
3353 case X86ISD::MOVSHDUP:
3354 case X86ISD::MOVSLDUP:
3355 case X86ISD::MOVDDUP:
3358 case X86ISD::UNPCKL:
3359 case X86ISD::UNPCKH:
3360 case X86ISD::VPERMILP:
3361 case X86ISD::VPERM2X128:
3362 case X86ISD::VPERMI:
3367 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3368 SDValue V1, SelectionDAG &DAG) {
3370 default: llvm_unreachable("Unknown x86 shuffle node");
3371 case X86ISD::MOVSHDUP:
3372 case X86ISD::MOVSLDUP:
3373 case X86ISD::MOVDDUP:
3374 return DAG.getNode(Opc, dl, VT, V1);
3378 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3379 SDValue V1, unsigned TargetMask,
3380 SelectionDAG &DAG) {
3382 default: llvm_unreachable("Unknown x86 shuffle node");
3383 case X86ISD::PSHUFD:
3384 case X86ISD::PSHUFHW:
3385 case X86ISD::PSHUFLW:
3386 case X86ISD::VPERMILP:
3387 case X86ISD::VPERMI:
3388 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3392 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3393 SDValue V1, SDValue V2, unsigned TargetMask,
3394 SelectionDAG &DAG) {
3396 default: llvm_unreachable("Unknown x86 shuffle node");
3397 case X86ISD::PALIGNR:
3399 case X86ISD::VPERM2X128:
3400 return DAG.getNode(Opc, dl, VT, V1, V2,
3401 DAG.getConstant(TargetMask, MVT::i8));
3405 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3406 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3408 default: llvm_unreachable("Unknown x86 shuffle node");
3409 case X86ISD::MOVLHPS:
3410 case X86ISD::MOVLHPD:
3411 case X86ISD::MOVHLPS:
3412 case X86ISD::MOVLPS:
3413 case X86ISD::MOVLPD:
3416 case X86ISD::UNPCKL:
3417 case X86ISD::UNPCKH:
3418 return DAG.getNode(Opc, dl, VT, V1, V2);
3422 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3423 MachineFunction &MF = DAG.getMachineFunction();
3424 const X86RegisterInfo *RegInfo =
3425 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3426 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3427 int ReturnAddrIndex = FuncInfo->getRAIndex();
3429 if (ReturnAddrIndex == 0) {
3430 // Set up a frame object for the return address.
3431 unsigned SlotSize = RegInfo->getSlotSize();
3432 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3435 FuncInfo->setRAIndex(ReturnAddrIndex);
3438 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3441 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3442 bool hasSymbolicDisplacement) {
3443 // Offset should fit into 32 bit immediate field.
3444 if (!isInt<32>(Offset))
3447 // If we don't have a symbolic displacement - we don't have any extra
3449 if (!hasSymbolicDisplacement)
3452 // FIXME: Some tweaks might be needed for medium code model.
3453 if (M != CodeModel::Small && M != CodeModel::Kernel)
3456 // For small code model we assume that latest object is 16MB before end of 31
3457 // bits boundary. We may also accept pretty large negative constants knowing
3458 // that all objects are in the positive half of address space.
3459 if (M == CodeModel::Small && Offset < 16*1024*1024)
3462 // For kernel code model we know that all object resist in the negative half
3463 // of 32bits address space. We may not accept negative offsets, since they may
3464 // be just off and we may accept pretty large positive ones.
3465 if (M == CodeModel::Kernel && Offset > 0)
3471 /// isCalleePop - Determines whether the callee is required to pop its
3472 /// own arguments. Callee pop is necessary to support tail calls.
3473 bool X86::isCalleePop(CallingConv::ID CallingConv,
3474 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3478 switch (CallingConv) {
3481 case CallingConv::X86_StdCall:
3483 case CallingConv::X86_FastCall:
3485 case CallingConv::X86_ThisCall:
3487 case CallingConv::Fast:
3489 case CallingConv::GHC:
3491 case CallingConv::HiPE:
3496 /// \brief Return true if the condition is an unsigned comparison operation.
3497 static bool isX86CCUnsigned(unsigned X86CC) {
3499 default: llvm_unreachable("Invalid integer condition!");
3500 case X86::COND_E: return true;
3501 case X86::COND_G: return false;
3502 case X86::COND_GE: return false;
3503 case X86::COND_L: return false;
3504 case X86::COND_LE: return false;
3505 case X86::COND_NE: return true;
3506 case X86::COND_B: return true;
3507 case X86::COND_A: return true;
3508 case X86::COND_BE: return true;
3509 case X86::COND_AE: return true;
3511 llvm_unreachable("covered switch fell through?!");
3514 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3515 /// specific condition code, returning the condition code and the LHS/RHS of the
3516 /// comparison to make.
3517 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3518 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3520 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3521 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3522 // X > -1 -> X == 0, jump !sign.
3523 RHS = DAG.getConstant(0, RHS.getValueType());
3524 return X86::COND_NS;
3526 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3527 // X < 0 -> X == 0, jump on sign.
3530 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3532 RHS = DAG.getConstant(0, RHS.getValueType());
3533 return X86::COND_LE;
3537 switch (SetCCOpcode) {
3538 default: llvm_unreachable("Invalid integer condition!");
3539 case ISD::SETEQ: return X86::COND_E;
3540 case ISD::SETGT: return X86::COND_G;
3541 case ISD::SETGE: return X86::COND_GE;
3542 case ISD::SETLT: return X86::COND_L;
3543 case ISD::SETLE: return X86::COND_LE;
3544 case ISD::SETNE: return X86::COND_NE;
3545 case ISD::SETULT: return X86::COND_B;
3546 case ISD::SETUGT: return X86::COND_A;
3547 case ISD::SETULE: return X86::COND_BE;
3548 case ISD::SETUGE: return X86::COND_AE;
3552 // First determine if it is required or is profitable to flip the operands.
3554 // If LHS is a foldable load, but RHS is not, flip the condition.
3555 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3556 !ISD::isNON_EXTLoad(RHS.getNode())) {
3557 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3558 std::swap(LHS, RHS);
3561 switch (SetCCOpcode) {
3567 std::swap(LHS, RHS);
3571 // On a floating point condition, the flags are set as follows:
3573 // 0 | 0 | 0 | X > Y
3574 // 0 | 0 | 1 | X < Y
3575 // 1 | 0 | 0 | X == Y
3576 // 1 | 1 | 1 | unordered
3577 switch (SetCCOpcode) {
3578 default: llvm_unreachable("Condcode should be pre-legalized away");
3580 case ISD::SETEQ: return X86::COND_E;
3581 case ISD::SETOLT: // flipped
3583 case ISD::SETGT: return X86::COND_A;
3584 case ISD::SETOLE: // flipped
3586 case ISD::SETGE: return X86::COND_AE;
3587 case ISD::SETUGT: // flipped
3589 case ISD::SETLT: return X86::COND_B;
3590 case ISD::SETUGE: // flipped
3592 case ISD::SETLE: return X86::COND_BE;
3594 case ISD::SETNE: return X86::COND_NE;
3595 case ISD::SETUO: return X86::COND_P;
3596 case ISD::SETO: return X86::COND_NP;
3598 case ISD::SETUNE: return X86::COND_INVALID;
3602 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3603 /// code. Current x86 isa includes the following FP cmov instructions:
3604 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3605 static bool hasFPCMov(unsigned X86CC) {
3621 /// isFPImmLegal - Returns true if the target can instruction select the
3622 /// specified FP immediate natively. If false, the legalizer will
3623 /// materialize the FP immediate as a load from a constant pool.
3624 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3625 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3626 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3632 /// \brief Returns true if it is beneficial to convert a load of a constant
3633 /// to just the constant itself.
3634 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3636 assert(Ty->isIntegerTy());
3638 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3639 if (BitSize == 0 || BitSize > 64)
3644 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3645 /// the specified range (L, H].
3646 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3647 return (Val < 0) || (Val >= Low && Val < Hi);
3650 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3651 /// specified value.
3652 static bool isUndefOrEqual(int Val, int CmpVal) {
3653 return (Val < 0 || Val == CmpVal);
3656 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3657 /// from position Pos and ending in Pos+Size, falls within the specified
3658 /// sequential range (L, L+Pos]. or is undef.
3659 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3660 unsigned Pos, unsigned Size, int Low) {
3661 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3662 if (!isUndefOrEqual(Mask[i], Low))
3667 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3668 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3669 /// the second operand.
3670 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3671 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3672 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3673 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3674 return (Mask[0] < 2 && Mask[1] < 2);
3678 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3679 /// is suitable for input to PSHUFHW.
3680 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3681 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3684 // Lower quadword copied in order or undef.
3685 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3688 // Upper quadword shuffled.
3689 for (unsigned i = 4; i != 8; ++i)
3690 if (!isUndefOrInRange(Mask[i], 4, 8))
3693 if (VT == MVT::v16i16) {
3694 // Lower quadword copied in order or undef.
3695 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3698 // Upper quadword shuffled.
3699 for (unsigned i = 12; i != 16; ++i)
3700 if (!isUndefOrInRange(Mask[i], 12, 16))
3707 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3708 /// is suitable for input to PSHUFLW.
3709 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3710 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3713 // Upper quadword copied in order.
3714 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3717 // Lower quadword shuffled.
3718 for (unsigned i = 0; i != 4; ++i)
3719 if (!isUndefOrInRange(Mask[i], 0, 4))
3722 if (VT == MVT::v16i16) {
3723 // Upper quadword copied in order.
3724 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3727 // Lower quadword shuffled.
3728 for (unsigned i = 8; i != 12; ++i)
3729 if (!isUndefOrInRange(Mask[i], 8, 12))
3736 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3737 /// is suitable for input to PALIGNR.
3738 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3739 const X86Subtarget *Subtarget) {
3740 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3741 (VT.is256BitVector() && !Subtarget->hasInt256()))
3744 unsigned NumElts = VT.getVectorNumElements();
3745 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3746 unsigned NumLaneElts = NumElts/NumLanes;
3748 // Do not handle 64-bit element shuffles with palignr.
3749 if (NumLaneElts == 2)
3752 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3754 for (i = 0; i != NumLaneElts; ++i) {
3759 // Lane is all undef, go to next lane
3760 if (i == NumLaneElts)
3763 int Start = Mask[i+l];
3765 // Make sure its in this lane in one of the sources
3766 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3767 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3770 // If not lane 0, then we must match lane 0
3771 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3774 // Correct second source to be contiguous with first source
3775 if (Start >= (int)NumElts)
3776 Start -= NumElts - NumLaneElts;
3778 // Make sure we're shifting in the right direction.
3779 if (Start <= (int)(i+l))
3784 // Check the rest of the elements to see if they are consecutive.
3785 for (++i; i != NumLaneElts; ++i) {
3786 int Idx = Mask[i+l];
3788 // Make sure its in this lane
3789 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3790 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3793 // If not lane 0, then we must match lane 0
3794 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3797 if (Idx >= (int)NumElts)
3798 Idx -= NumElts - NumLaneElts;
3800 if (!isUndefOrEqual(Idx, Start+i))
3809 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3810 /// the two vector operands have swapped position.
3811 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3812 unsigned NumElems) {
3813 for (unsigned i = 0; i != NumElems; ++i) {
3817 else if (idx < (int)NumElems)
3818 Mask[i] = idx + NumElems;
3820 Mask[i] = idx - NumElems;
3824 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3825 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3826 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3827 /// reverse of what x86 shuffles want.
3828 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3830 unsigned NumElems = VT.getVectorNumElements();
3831 unsigned NumLanes = VT.getSizeInBits()/128;
3832 unsigned NumLaneElems = NumElems/NumLanes;
3834 if (NumLaneElems != 2 && NumLaneElems != 4)
3837 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3838 bool symetricMaskRequired =
3839 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3841 // VSHUFPSY divides the resulting vector into 4 chunks.
3842 // The sources are also splitted into 4 chunks, and each destination
3843 // chunk must come from a different source chunk.
3845 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3846 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3848 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3849 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3851 // VSHUFPDY divides the resulting vector into 4 chunks.
3852 // The sources are also splitted into 4 chunks, and each destination
3853 // chunk must come from a different source chunk.
3855 // SRC1 => X3 X2 X1 X0
3856 // SRC2 => Y3 Y2 Y1 Y0
3858 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3860 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3861 unsigned HalfLaneElems = NumLaneElems/2;
3862 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3863 for (unsigned i = 0; i != NumLaneElems; ++i) {
3864 int Idx = Mask[i+l];
3865 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3866 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3868 // For VSHUFPSY, the mask of the second half must be the same as the
3869 // first but with the appropriate offsets. This works in the same way as
3870 // VPERMILPS works with masks.
3871 if (!symetricMaskRequired || Idx < 0)
3873 if (MaskVal[i] < 0) {
3874 MaskVal[i] = Idx - l;
3877 if ((signed)(Idx - l) != MaskVal[i])
3885 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3886 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3887 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3888 if (!VT.is128BitVector())
3891 unsigned NumElems = VT.getVectorNumElements();
3896 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3897 return isUndefOrEqual(Mask[0], 6) &&
3898 isUndefOrEqual(Mask[1], 7) &&
3899 isUndefOrEqual(Mask[2], 2) &&
3900 isUndefOrEqual(Mask[3], 3);
3903 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3904 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3906 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3907 if (!VT.is128BitVector())
3910 unsigned NumElems = VT.getVectorNumElements();
3915 return isUndefOrEqual(Mask[0], 2) &&
3916 isUndefOrEqual(Mask[1], 3) &&
3917 isUndefOrEqual(Mask[2], 2) &&
3918 isUndefOrEqual(Mask[3], 3);
3921 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3922 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3923 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3924 if (!VT.is128BitVector())
3927 unsigned NumElems = VT.getVectorNumElements();
3929 if (NumElems != 2 && NumElems != 4)
3932 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3933 if (!isUndefOrEqual(Mask[i], i + NumElems))
3936 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3937 if (!isUndefOrEqual(Mask[i], i))
3943 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3944 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3945 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3946 if (!VT.is128BitVector())
3949 unsigned NumElems = VT.getVectorNumElements();
3951 if (NumElems != 2 && NumElems != 4)
3954 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3955 if (!isUndefOrEqual(Mask[i], i))
3958 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3959 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3965 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3966 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3967 /// i. e: If all but one element come from the same vector.
3968 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3969 // TODO: Deal with AVX's VINSERTPS
3970 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3973 unsigned CorrectPosV1 = 0;
3974 unsigned CorrectPosV2 = 0;
3975 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3976 if (Mask[i] == -1) {
3984 else if (Mask[i] == i + 4)
3988 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3989 // We have 3 elements (undefs count as elements from any vector) from one
3990 // vector, and one from another.
3997 // Some special combinations that can be optimized.
4000 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4001 SelectionDAG &DAG) {
4002 MVT VT = SVOp->getSimpleValueType(0);
4005 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4008 ArrayRef<int> Mask = SVOp->getMask();
4010 // These are the special masks that may be optimized.
4011 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4012 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4013 bool MatchEvenMask = true;
4014 bool MatchOddMask = true;
4015 for (int i=0; i<8; ++i) {
4016 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4017 MatchEvenMask = false;
4018 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4019 MatchOddMask = false;
4022 if (!MatchEvenMask && !MatchOddMask)
4025 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4027 SDValue Op0 = SVOp->getOperand(0);
4028 SDValue Op1 = SVOp->getOperand(1);
4030 if (MatchEvenMask) {
4031 // Shift the second operand right to 32 bits.
4032 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4033 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4035 // Shift the first operand left to 32 bits.
4036 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4037 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4039 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4040 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4043 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4044 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4045 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4046 bool HasInt256, bool V2IsSplat = false) {
4048 assert(VT.getSizeInBits() >= 128 &&
4049 "Unsupported vector type for unpckl");
4051 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4053 unsigned NumOf256BitLanes;
4054 unsigned NumElts = VT.getVectorNumElements();
4055 if (VT.is256BitVector()) {
4056 if (NumElts != 4 && NumElts != 8 &&
4057 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4060 NumOf256BitLanes = 1;
4061 } else if (VT.is512BitVector()) {
4062 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4063 "Unsupported vector type for unpckh");
4065 NumOf256BitLanes = 2;
4068 NumOf256BitLanes = 1;
4071 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4072 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4074 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4075 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4076 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4077 int BitI = Mask[l256*NumEltsInStride+l+i];
4078 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4079 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4081 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4083 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4091 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4092 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4093 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4094 bool HasInt256, bool V2IsSplat = false) {
4095 assert(VT.getSizeInBits() >= 128 &&
4096 "Unsupported vector type for unpckh");
4098 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4100 unsigned NumOf256BitLanes;
4101 unsigned NumElts = VT.getVectorNumElements();
4102 if (VT.is256BitVector()) {
4103 if (NumElts != 4 && NumElts != 8 &&
4104 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4107 NumOf256BitLanes = 1;
4108 } else if (VT.is512BitVector()) {
4109 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4110 "Unsupported vector type for unpckh");
4112 NumOf256BitLanes = 2;
4115 NumOf256BitLanes = 1;
4118 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4119 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4121 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4122 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4123 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4124 int BitI = Mask[l256*NumEltsInStride+l+i];
4125 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4126 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4128 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4130 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4138 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4139 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4141 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4142 unsigned NumElts = VT.getVectorNumElements();
4143 bool Is256BitVec = VT.is256BitVector();
4145 if (VT.is512BitVector())
4147 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4148 "Unsupported vector type for unpckh");
4150 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4151 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4154 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4155 // FIXME: Need a better way to get rid of this, there's no latency difference
4156 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4157 // the former later. We should also remove the "_undef" special mask.
4158 if (NumElts == 4 && Is256BitVec)
4161 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4162 // independently on 128-bit lanes.
4163 unsigned NumLanes = VT.getSizeInBits()/128;
4164 unsigned NumLaneElts = NumElts/NumLanes;
4166 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4167 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4168 int BitI = Mask[l+i];
4169 int BitI1 = Mask[l+i+1];
4171 if (!isUndefOrEqual(BitI, j))
4173 if (!isUndefOrEqual(BitI1, j))
4181 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4182 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4184 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4185 unsigned NumElts = VT.getVectorNumElements();
4187 if (VT.is512BitVector())
4190 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4191 "Unsupported vector type for unpckh");
4193 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4194 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4197 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4198 // independently on 128-bit lanes.
4199 unsigned NumLanes = VT.getSizeInBits()/128;
4200 unsigned NumLaneElts = NumElts/NumLanes;
4202 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4203 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4204 int BitI = Mask[l+i];
4205 int BitI1 = Mask[l+i+1];
4206 if (!isUndefOrEqual(BitI, j))
4208 if (!isUndefOrEqual(BitI1, j))
4215 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4216 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4217 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4218 if (!VT.is512BitVector())
4221 unsigned NumElts = VT.getVectorNumElements();
4222 unsigned HalfSize = NumElts/2;
4223 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4224 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4229 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4230 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4238 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4239 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4240 /// MOVSD, and MOVD, i.e. setting the lowest element.
4241 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4242 if (VT.getVectorElementType().getSizeInBits() < 32)
4244 if (!VT.is128BitVector())
4247 unsigned NumElts = VT.getVectorNumElements();
4249 if (!isUndefOrEqual(Mask[0], NumElts))
4252 for (unsigned i = 1; i != NumElts; ++i)
4253 if (!isUndefOrEqual(Mask[i], i))
4259 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4260 /// as permutations between 128-bit chunks or halves. As an example: this
4262 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4263 /// The first half comes from the second half of V1 and the second half from the
4264 /// the second half of V2.
4265 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4266 if (!HasFp256 || !VT.is256BitVector())
4269 // The shuffle result is divided into half A and half B. In total the two
4270 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4271 // B must come from C, D, E or F.
4272 unsigned HalfSize = VT.getVectorNumElements()/2;
4273 bool MatchA = false, MatchB = false;
4275 // Check if A comes from one of C, D, E, F.
4276 for (unsigned Half = 0; Half != 4; ++Half) {
4277 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4283 // Check if B comes from one of C, D, E, F.
4284 for (unsigned Half = 0; Half != 4; ++Half) {
4285 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4291 return MatchA && MatchB;
4294 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4295 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4296 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4297 MVT VT = SVOp->getSimpleValueType(0);
4299 unsigned HalfSize = VT.getVectorNumElements()/2;
4301 unsigned FstHalf = 0, SndHalf = 0;
4302 for (unsigned i = 0; i < HalfSize; ++i) {
4303 if (SVOp->getMaskElt(i) > 0) {
4304 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4308 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4309 if (SVOp->getMaskElt(i) > 0) {
4310 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4315 return (FstHalf | (SndHalf << 4));
4318 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4319 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4320 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4324 unsigned NumElts = VT.getVectorNumElements();
4326 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4327 for (unsigned i = 0; i != NumElts; ++i) {
4330 Imm8 |= Mask[i] << (i*2);
4335 unsigned LaneSize = 4;
4336 SmallVector<int, 4> MaskVal(LaneSize, -1);
4338 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4339 for (unsigned i = 0; i != LaneSize; ++i) {
4340 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4344 if (MaskVal[i] < 0) {
4345 MaskVal[i] = Mask[i+l] - l;
4346 Imm8 |= MaskVal[i] << (i*2);
4349 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4356 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4357 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4358 /// Note that VPERMIL mask matching is different depending whether theunderlying
4359 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4360 /// to the same elements of the low, but to the higher half of the source.
4361 /// In VPERMILPD the two lanes could be shuffled independently of each other
4362 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4363 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4364 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4365 if (VT.getSizeInBits() < 256 || EltSize < 32)
4367 bool symetricMaskRequired = (EltSize == 32);
4368 unsigned NumElts = VT.getVectorNumElements();
4370 unsigned NumLanes = VT.getSizeInBits()/128;
4371 unsigned LaneSize = NumElts/NumLanes;
4372 // 2 or 4 elements in one lane
4374 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4375 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4376 for (unsigned i = 0; i != LaneSize; ++i) {
4377 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4379 if (symetricMaskRequired) {
4380 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4381 ExpectedMaskVal[i] = Mask[i+l] - l;
4384 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4392 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4393 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4394 /// element of vector 2 and the other elements to come from vector 1 in order.
4395 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4396 bool V2IsSplat = false, bool V2IsUndef = false) {
4397 if (!VT.is128BitVector())
4400 unsigned NumOps = VT.getVectorNumElements();
4401 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4404 if (!isUndefOrEqual(Mask[0], 0))
4407 for (unsigned i = 1; i != NumOps; ++i)
4408 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4409 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4410 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4416 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4417 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4418 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4419 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4420 const X86Subtarget *Subtarget) {
4421 if (!Subtarget->hasSSE3())
4424 unsigned NumElems = VT.getVectorNumElements();
4426 if ((VT.is128BitVector() && NumElems != 4) ||
4427 (VT.is256BitVector() && NumElems != 8) ||
4428 (VT.is512BitVector() && NumElems != 16))
4431 // "i+1" is the value the indexed mask element must have
4432 for (unsigned i = 0; i != NumElems; i += 2)
4433 if (!isUndefOrEqual(Mask[i], i+1) ||
4434 !isUndefOrEqual(Mask[i+1], i+1))
4440 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4441 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4442 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4443 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4444 const X86Subtarget *Subtarget) {
4445 if (!Subtarget->hasSSE3())
4448 unsigned NumElems = VT.getVectorNumElements();
4450 if ((VT.is128BitVector() && NumElems != 4) ||
4451 (VT.is256BitVector() && NumElems != 8) ||
4452 (VT.is512BitVector() && NumElems != 16))
4455 // "i" is the value the indexed mask element must have
4456 for (unsigned i = 0; i != NumElems; i += 2)
4457 if (!isUndefOrEqual(Mask[i], i) ||
4458 !isUndefOrEqual(Mask[i+1], i))
4464 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4465 /// specifies a shuffle of elements that is suitable for input to 256-bit
4466 /// version of MOVDDUP.
4467 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4468 if (!HasFp256 || !VT.is256BitVector())
4471 unsigned NumElts = VT.getVectorNumElements();
4475 for (unsigned i = 0; i != NumElts/2; ++i)
4476 if (!isUndefOrEqual(Mask[i], 0))
4478 for (unsigned i = NumElts/2; i != NumElts; ++i)
4479 if (!isUndefOrEqual(Mask[i], NumElts/2))
4484 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4485 /// specifies a shuffle of elements that is suitable for input to 128-bit
4486 /// version of MOVDDUP.
4487 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4488 if (!VT.is128BitVector())
4491 unsigned e = VT.getVectorNumElements() / 2;
4492 for (unsigned i = 0; i != e; ++i)
4493 if (!isUndefOrEqual(Mask[i], i))
4495 for (unsigned i = 0; i != e; ++i)
4496 if (!isUndefOrEqual(Mask[e+i], i))
4501 /// isVEXTRACTIndex - Return true if the specified
4502 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4503 /// suitable for instruction that extract 128 or 256 bit vectors
4504 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4505 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4506 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4509 // The index should be aligned on a vecWidth-bit boundary.
4511 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4513 MVT VT = N->getSimpleValueType(0);
4514 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4515 bool Result = (Index * ElSize) % vecWidth == 0;
4520 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4521 /// operand specifies a subvector insert that is suitable for input to
4522 /// insertion of 128 or 256-bit subvectors
4523 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4524 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4525 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4527 // The index should be aligned on a vecWidth-bit boundary.
4529 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4531 MVT VT = N->getSimpleValueType(0);
4532 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4533 bool Result = (Index * ElSize) % vecWidth == 0;
4538 bool X86::isVINSERT128Index(SDNode *N) {
4539 return isVINSERTIndex(N, 128);
4542 bool X86::isVINSERT256Index(SDNode *N) {
4543 return isVINSERTIndex(N, 256);
4546 bool X86::isVEXTRACT128Index(SDNode *N) {
4547 return isVEXTRACTIndex(N, 128);
4550 bool X86::isVEXTRACT256Index(SDNode *N) {
4551 return isVEXTRACTIndex(N, 256);
4554 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4555 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4556 /// Handles 128-bit and 256-bit.
4557 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4558 MVT VT = N->getSimpleValueType(0);
4560 assert((VT.getSizeInBits() >= 128) &&
4561 "Unsupported vector type for PSHUF/SHUFP");
4563 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4564 // independently on 128-bit lanes.
4565 unsigned NumElts = VT.getVectorNumElements();
4566 unsigned NumLanes = VT.getSizeInBits()/128;
4567 unsigned NumLaneElts = NumElts/NumLanes;
4569 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4570 "Only supports 2, 4 or 8 elements per lane");
4572 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4574 for (unsigned i = 0; i != NumElts; ++i) {
4575 int Elt = N->getMaskElt(i);
4576 if (Elt < 0) continue;
4577 Elt &= NumLaneElts - 1;
4578 unsigned ShAmt = (i << Shift) % 8;
4579 Mask |= Elt << ShAmt;
4585 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4586 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4587 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4588 MVT VT = N->getSimpleValueType(0);
4590 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4591 "Unsupported vector type for PSHUFHW");
4593 unsigned NumElts = VT.getVectorNumElements();
4596 for (unsigned l = 0; l != NumElts; l += 8) {
4597 // 8 nodes per lane, but we only care about the last 4.
4598 for (unsigned i = 0; i < 4; ++i) {
4599 int Elt = N->getMaskElt(l+i+4);
4600 if (Elt < 0) continue;
4601 Elt &= 0x3; // only 2-bits.
4602 Mask |= Elt << (i * 2);
4609 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4610 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4611 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4612 MVT VT = N->getSimpleValueType(0);
4614 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4615 "Unsupported vector type for PSHUFHW");
4617 unsigned NumElts = VT.getVectorNumElements();
4620 for (unsigned l = 0; l != NumElts; l += 8) {
4621 // 8 nodes per lane, but we only care about the first 4.
4622 for (unsigned i = 0; i < 4; ++i) {
4623 int Elt = N->getMaskElt(l+i);
4624 if (Elt < 0) continue;
4625 Elt &= 0x3; // only 2-bits
4626 Mask |= Elt << (i * 2);
4633 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4634 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4635 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4636 MVT VT = SVOp->getSimpleValueType(0);
4637 unsigned EltSize = VT.is512BitVector() ? 1 :
4638 VT.getVectorElementType().getSizeInBits() >> 3;
4640 unsigned NumElts = VT.getVectorNumElements();
4641 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4642 unsigned NumLaneElts = NumElts/NumLanes;
4646 for (i = 0; i != NumElts; ++i) {
4647 Val = SVOp->getMaskElt(i);
4651 if (Val >= (int)NumElts)
4652 Val -= NumElts - NumLaneElts;
4654 assert(Val - i > 0 && "PALIGNR imm should be positive");
4655 return (Val - i) * EltSize;
4658 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4659 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4660 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4661 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4664 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4666 MVT VecVT = N->getOperand(0).getSimpleValueType();
4667 MVT ElVT = VecVT.getVectorElementType();
4669 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4670 return Index / NumElemsPerChunk;
4673 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4674 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4675 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4676 llvm_unreachable("Illegal insert subvector for VINSERT");
4679 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4681 MVT VecVT = N->getSimpleValueType(0);
4682 MVT ElVT = VecVT.getVectorElementType();
4684 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4685 return Index / NumElemsPerChunk;
4688 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4689 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4690 /// and VINSERTI128 instructions.
4691 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4692 return getExtractVEXTRACTImmediate(N, 128);
4695 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4696 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4697 /// and VINSERTI64x4 instructions.
4698 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4699 return getExtractVEXTRACTImmediate(N, 256);
4702 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4703 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4704 /// and VINSERTI128 instructions.
4705 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4706 return getInsertVINSERTImmediate(N, 128);
4709 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4710 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4711 /// and VINSERTI64x4 instructions.
4712 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4713 return getInsertVINSERTImmediate(N, 256);
4716 /// isZero - Returns true if Elt is a constant integer zero
4717 static bool isZero(SDValue V) {
4718 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4719 return C && C->isNullValue();
4722 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4724 bool X86::isZeroNode(SDValue Elt) {
4727 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4728 return CFP->getValueAPF().isPosZero();
4732 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4733 /// their permute mask.
4734 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4735 SelectionDAG &DAG) {
4736 MVT VT = SVOp->getSimpleValueType(0);
4737 unsigned NumElems = VT.getVectorNumElements();
4738 SmallVector<int, 8> MaskVec;
4740 for (unsigned i = 0; i != NumElems; ++i) {
4741 int Idx = SVOp->getMaskElt(i);
4743 if (Idx < (int)NumElems)
4748 MaskVec.push_back(Idx);
4750 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4751 SVOp->getOperand(0), &MaskVec[0]);
4754 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4755 /// match movhlps. The lower half elements should come from upper half of
4756 /// V1 (and in order), and the upper half elements should come from the upper
4757 /// half of V2 (and in order).
4758 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4759 if (!VT.is128BitVector())
4761 if (VT.getVectorNumElements() != 4)
4763 for (unsigned i = 0, e = 2; i != e; ++i)
4764 if (!isUndefOrEqual(Mask[i], i+2))
4766 for (unsigned i = 2; i != 4; ++i)
4767 if (!isUndefOrEqual(Mask[i], i+4))
4772 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4773 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4775 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4776 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4778 N = N->getOperand(0).getNode();
4779 if (!ISD::isNON_EXTLoad(N))
4782 *LD = cast<LoadSDNode>(N);
4786 // Test whether the given value is a vector value which will be legalized
4788 static bool WillBeConstantPoolLoad(SDNode *N) {
4789 if (N->getOpcode() != ISD::BUILD_VECTOR)
4792 // Check for any non-constant elements.
4793 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4794 switch (N->getOperand(i).getNode()->getOpcode()) {
4796 case ISD::ConstantFP:
4803 // Vectors of all-zeros and all-ones are materialized with special
4804 // instructions rather than being loaded.
4805 return !ISD::isBuildVectorAllZeros(N) &&
4806 !ISD::isBuildVectorAllOnes(N);
4809 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4810 /// match movlp{s|d}. The lower half elements should come from lower half of
4811 /// V1 (and in order), and the upper half elements should come from the upper
4812 /// half of V2 (and in order). And since V1 will become the source of the
4813 /// MOVLP, it must be either a vector load or a scalar load to vector.
4814 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4815 ArrayRef<int> Mask, MVT VT) {
4816 if (!VT.is128BitVector())
4819 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4821 // Is V2 is a vector load, don't do this transformation. We will try to use
4822 // load folding shufps op.
4823 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4826 unsigned NumElems = VT.getVectorNumElements();
4828 if (NumElems != 2 && NumElems != 4)
4830 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4831 if (!isUndefOrEqual(Mask[i], i))
4833 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4834 if (!isUndefOrEqual(Mask[i], i+NumElems))
4839 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4841 static bool isSplatVector(SDNode *N) {
4842 if (N->getOpcode() != ISD::BUILD_VECTOR)
4845 SDValue SplatValue = N->getOperand(0);
4846 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4847 if (N->getOperand(i) != SplatValue)
4852 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4853 /// to an zero vector.
4854 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4855 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4856 SDValue V1 = N->getOperand(0);
4857 SDValue V2 = N->getOperand(1);
4858 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4859 for (unsigned i = 0; i != NumElems; ++i) {
4860 int Idx = N->getMaskElt(i);
4861 if (Idx >= (int)NumElems) {
4862 unsigned Opc = V2.getOpcode();
4863 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4865 if (Opc != ISD::BUILD_VECTOR ||
4866 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4868 } else if (Idx >= 0) {
4869 unsigned Opc = V1.getOpcode();
4870 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4872 if (Opc != ISD::BUILD_VECTOR ||
4873 !X86::isZeroNode(V1.getOperand(Idx)))
4880 /// getZeroVector - Returns a vector of specified type with all zero elements.
4882 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4883 SelectionDAG &DAG, SDLoc dl) {
4884 assert(VT.isVector() && "Expected a vector type");
4886 // Always build SSE zero vectors as <4 x i32> bitcasted
4887 // to their dest type. This ensures they get CSE'd.
4889 if (VT.is128BitVector()) { // SSE
4890 if (Subtarget->hasSSE2()) { // SSE2
4891 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4892 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4894 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4895 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4897 } else if (VT.is256BitVector()) { // AVX
4898 if (Subtarget->hasInt256()) { // AVX2
4899 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4900 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4901 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4903 // 256-bit logic and arithmetic instructions in AVX are all
4904 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4905 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4906 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4907 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4909 } else if (VT.is512BitVector()) { // AVX-512
4910 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4911 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4912 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4913 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4914 } else if (VT.getScalarType() == MVT::i1) {
4915 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4916 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4917 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4918 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4920 llvm_unreachable("Unexpected vector type");
4922 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4925 /// getOnesVector - Returns a vector of specified type with all bits set.
4926 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4927 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4928 /// Then bitcast to their original type, ensuring they get CSE'd.
4929 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4931 assert(VT.isVector() && "Expected a vector type");
4933 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4935 if (VT.is256BitVector()) {
4936 if (HasInt256) { // AVX2
4937 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4938 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4940 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4941 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4943 } else if (VT.is128BitVector()) {
4944 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4946 llvm_unreachable("Unexpected vector type");
4948 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4951 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4952 /// that point to V2 points to its first element.
4953 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4954 for (unsigned i = 0; i != NumElems; ++i) {
4955 if (Mask[i] > (int)NumElems) {
4961 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4962 /// operation of specified width.
4963 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4965 unsigned NumElems = VT.getVectorNumElements();
4966 SmallVector<int, 8> Mask;
4967 Mask.push_back(NumElems);
4968 for (unsigned i = 1; i != NumElems; ++i)
4970 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4973 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4974 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4976 unsigned NumElems = VT.getVectorNumElements();
4977 SmallVector<int, 8> Mask;
4978 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4980 Mask.push_back(i + NumElems);
4982 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4985 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4986 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4988 unsigned NumElems = VT.getVectorNumElements();
4989 SmallVector<int, 8> Mask;
4990 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4991 Mask.push_back(i + Half);
4992 Mask.push_back(i + NumElems + Half);
4994 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4997 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4998 // a generic shuffle instruction because the target has no such instructions.
4999 // Generate shuffles which repeat i16 and i8 several times until they can be
5000 // represented by v4f32 and then be manipulated by target suported shuffles.
5001 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5002 MVT VT = V.getSimpleValueType();
5003 int NumElems = VT.getVectorNumElements();
5006 while (NumElems > 4) {
5007 if (EltNo < NumElems/2) {
5008 V = getUnpackl(DAG, dl, VT, V, V);
5010 V = getUnpackh(DAG, dl, VT, V, V);
5011 EltNo -= NumElems/2;
5018 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5019 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5020 MVT VT = V.getSimpleValueType();
5023 if (VT.is128BitVector()) {
5024 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5025 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5026 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5028 } else if (VT.is256BitVector()) {
5029 // To use VPERMILPS to splat scalars, the second half of indicies must
5030 // refer to the higher part, which is a duplication of the lower one,
5031 // because VPERMILPS can only handle in-lane permutations.
5032 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5033 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5035 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5036 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5039 llvm_unreachable("Vector size not supported");
5041 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5044 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5045 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5046 MVT SrcVT = SV->getSimpleValueType(0);
5047 SDValue V1 = SV->getOperand(0);
5050 int EltNo = SV->getSplatIndex();
5051 int NumElems = SrcVT.getVectorNumElements();
5052 bool Is256BitVec = SrcVT.is256BitVector();
5054 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5055 "Unknown how to promote splat for type");
5057 // Extract the 128-bit part containing the splat element and update
5058 // the splat element index when it refers to the higher register.
5060 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5061 if (EltNo >= NumElems/2)
5062 EltNo -= NumElems/2;
5065 // All i16 and i8 vector types can't be used directly by a generic shuffle
5066 // instruction because the target has no such instruction. Generate shuffles
5067 // which repeat i16 and i8 several times until they fit in i32, and then can
5068 // be manipulated by target suported shuffles.
5069 MVT EltVT = SrcVT.getVectorElementType();
5070 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5071 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5073 // Recreate the 256-bit vector and place the same 128-bit vector
5074 // into the low and high part. This is necessary because we want
5075 // to use VPERM* to shuffle the vectors
5077 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5080 return getLegalSplat(DAG, V1, EltNo);
5083 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5084 /// vector of zero or undef vector. This produces a shuffle where the low
5085 /// element of V2 is swizzled into the zero/undef vector, landing at element
5086 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5087 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5089 const X86Subtarget *Subtarget,
5090 SelectionDAG &DAG) {
5091 MVT VT = V2.getSimpleValueType();
5093 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5094 unsigned NumElems = VT.getVectorNumElements();
5095 SmallVector<int, 16> MaskVec;
5096 for (unsigned i = 0; i != NumElems; ++i)
5097 // If this is the insertion idx, put the low elt of V2 here.
5098 MaskVec.push_back(i == Idx ? NumElems : i);
5099 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5102 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5103 /// target specific opcode. Returns true if the Mask could be calculated.
5104 /// Sets IsUnary to true if only uses one source.
5105 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5106 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5107 unsigned NumElems = VT.getVectorNumElements();
5111 switch(N->getOpcode()) {
5113 ImmN = N->getOperand(N->getNumOperands()-1);
5114 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5116 case X86ISD::UNPCKH:
5117 DecodeUNPCKHMask(VT, Mask);
5119 case X86ISD::UNPCKL:
5120 DecodeUNPCKLMask(VT, Mask);
5122 case X86ISD::MOVHLPS:
5123 DecodeMOVHLPSMask(NumElems, Mask);
5125 case X86ISD::MOVLHPS:
5126 DecodeMOVLHPSMask(NumElems, Mask);
5128 case X86ISD::PALIGNR:
5129 ImmN = N->getOperand(N->getNumOperands()-1);
5130 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5132 case X86ISD::PSHUFD:
5133 case X86ISD::VPERMILP:
5134 ImmN = N->getOperand(N->getNumOperands()-1);
5135 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5138 case X86ISD::PSHUFHW:
5139 ImmN = N->getOperand(N->getNumOperands()-1);
5140 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5143 case X86ISD::PSHUFLW:
5144 ImmN = N->getOperand(N->getNumOperands()-1);
5145 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5148 case X86ISD::VPERMI:
5149 ImmN = N->getOperand(N->getNumOperands()-1);
5150 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5154 case X86ISD::MOVSD: {
5155 // The index 0 always comes from the first element of the second source,
5156 // this is why MOVSS and MOVSD are used in the first place. The other
5157 // elements come from the other positions of the first source vector
5158 Mask.push_back(NumElems);
5159 for (unsigned i = 1; i != NumElems; ++i) {
5164 case X86ISD::VPERM2X128:
5165 ImmN = N->getOperand(N->getNumOperands()-1);
5166 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5167 if (Mask.empty()) return false;
5169 case X86ISD::MOVDDUP:
5170 case X86ISD::MOVLHPD:
5171 case X86ISD::MOVLPD:
5172 case X86ISD::MOVLPS:
5173 case X86ISD::MOVSHDUP:
5174 case X86ISD::MOVSLDUP:
5175 // Not yet implemented
5177 default: llvm_unreachable("unknown target shuffle node");
5183 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5184 /// element of the result of the vector shuffle.
5185 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5188 return SDValue(); // Limit search depth.
5190 SDValue V = SDValue(N, 0);
5191 EVT VT = V.getValueType();
5192 unsigned Opcode = V.getOpcode();
5194 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5195 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5196 int Elt = SV->getMaskElt(Index);
5199 return DAG.getUNDEF(VT.getVectorElementType());
5201 unsigned NumElems = VT.getVectorNumElements();
5202 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5203 : SV->getOperand(1);
5204 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5207 // Recurse into target specific vector shuffles to find scalars.
5208 if (isTargetShuffle(Opcode)) {
5209 MVT ShufVT = V.getSimpleValueType();
5210 unsigned NumElems = ShufVT.getVectorNumElements();
5211 SmallVector<int, 16> ShuffleMask;
5214 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5217 int Elt = ShuffleMask[Index];
5219 return DAG.getUNDEF(ShufVT.getVectorElementType());
5221 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5223 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5227 // Actual nodes that may contain scalar elements
5228 if (Opcode == ISD::BITCAST) {
5229 V = V.getOperand(0);
5230 EVT SrcVT = V.getValueType();
5231 unsigned NumElems = VT.getVectorNumElements();
5233 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5237 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5238 return (Index == 0) ? V.getOperand(0)
5239 : DAG.getUNDEF(VT.getVectorElementType());
5241 if (V.getOpcode() == ISD::BUILD_VECTOR)
5242 return V.getOperand(Index);
5247 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5248 /// shuffle operation which come from a consecutively from a zero. The
5249 /// search can start in two different directions, from left or right.
5250 /// We count undefs as zeros until PreferredNum is reached.
5251 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5252 unsigned NumElems, bool ZerosFromLeft,
5254 unsigned PreferredNum = -1U) {
5255 unsigned NumZeros = 0;
5256 for (unsigned i = 0; i != NumElems; ++i) {
5257 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5258 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5262 if (X86::isZeroNode(Elt))
5264 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5265 NumZeros = std::min(NumZeros + 1, PreferredNum);
5273 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5274 /// correspond consecutively to elements from one of the vector operands,
5275 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5277 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5278 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5279 unsigned NumElems, unsigned &OpNum) {
5280 bool SeenV1 = false;
5281 bool SeenV2 = false;
5283 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5284 int Idx = SVOp->getMaskElt(i);
5285 // Ignore undef indicies
5289 if (Idx < (int)NumElems)
5294 // Only accept consecutive elements from the same vector
5295 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5299 OpNum = SeenV1 ? 0 : 1;
5303 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5304 /// logical left shift of a vector.
5305 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5306 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5308 SVOp->getSimpleValueType(0).getVectorNumElements();
5309 unsigned NumZeros = getNumOfConsecutiveZeros(
5310 SVOp, NumElems, false /* check zeros from right */, DAG,
5311 SVOp->getMaskElt(0));
5317 // Considering the elements in the mask that are not consecutive zeros,
5318 // check if they consecutively come from only one of the source vectors.
5320 // V1 = {X, A, B, C} 0
5322 // vector_shuffle V1, V2 <1, 2, 3, X>
5324 if (!isShuffleMaskConsecutive(SVOp,
5325 0, // Mask Start Index
5326 NumElems-NumZeros, // Mask End Index(exclusive)
5327 NumZeros, // Where to start looking in the src vector
5328 NumElems, // Number of elements in vector
5329 OpSrc)) // Which source operand ?
5334 ShVal = SVOp->getOperand(OpSrc);
5338 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5339 /// logical left shift of a vector.
5340 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5341 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5343 SVOp->getSimpleValueType(0).getVectorNumElements();
5344 unsigned NumZeros = getNumOfConsecutiveZeros(
5345 SVOp, NumElems, true /* check zeros from left */, DAG,
5346 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5352 // Considering the elements in the mask that are not consecutive zeros,
5353 // check if they consecutively come from only one of the source vectors.
5355 // 0 { A, B, X, X } = V2
5357 // vector_shuffle V1, V2 <X, X, 4, 5>
5359 if (!isShuffleMaskConsecutive(SVOp,
5360 NumZeros, // Mask Start Index
5361 NumElems, // Mask End Index(exclusive)
5362 0, // Where to start looking in the src vector
5363 NumElems, // Number of elements in vector
5364 OpSrc)) // Which source operand ?
5369 ShVal = SVOp->getOperand(OpSrc);
5373 /// isVectorShift - Returns true if the shuffle can be implemented as a
5374 /// logical left or right shift of a vector.
5375 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5376 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5377 // Although the logic below support any bitwidth size, there are no
5378 // shift instructions which handle more than 128-bit vectors.
5379 if (!SVOp->getSimpleValueType(0).is128BitVector())
5382 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5383 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5389 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5391 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5392 unsigned NumNonZero, unsigned NumZero,
5394 const X86Subtarget* Subtarget,
5395 const TargetLowering &TLI) {
5402 for (unsigned i = 0; i < 16; ++i) {
5403 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5404 if (ThisIsNonZero && First) {
5406 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5408 V = DAG.getUNDEF(MVT::v8i16);
5413 SDValue ThisElt, LastElt;
5414 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5415 if (LastIsNonZero) {
5416 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5417 MVT::i16, Op.getOperand(i-1));
5419 if (ThisIsNonZero) {
5420 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5421 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5422 ThisElt, DAG.getConstant(8, MVT::i8));
5424 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5428 if (ThisElt.getNode())
5429 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5430 DAG.getIntPtrConstant(i/2));
5434 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5437 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5439 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5440 unsigned NumNonZero, unsigned NumZero,
5442 const X86Subtarget* Subtarget,
5443 const TargetLowering &TLI) {
5450 for (unsigned i = 0; i < 8; ++i) {
5451 bool isNonZero = (NonZeros & (1 << i)) != 0;
5455 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5457 V = DAG.getUNDEF(MVT::v8i16);
5460 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5461 MVT::v8i16, V, Op.getOperand(i),
5462 DAG.getIntPtrConstant(i));
5469 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5470 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5471 unsigned NonZeros, unsigned NumNonZero,
5472 unsigned NumZero, SelectionDAG &DAG,
5473 const X86Subtarget *Subtarget,
5474 const TargetLowering &TLI) {
5475 // We know there's at least one non-zero element
5476 unsigned FirstNonZeroIdx = 0;
5477 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5478 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5479 X86::isZeroNode(FirstNonZero)) {
5481 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5484 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5485 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5488 SDValue V = FirstNonZero.getOperand(0);
5489 MVT VVT = V.getSimpleValueType();
5490 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5493 unsigned FirstNonZeroDst =
5494 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5495 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5496 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5497 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5499 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5500 SDValue Elem = Op.getOperand(Idx);
5501 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5504 // TODO: What else can be here? Deal with it.
5505 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5508 // TODO: Some optimizations are still possible here
5509 // ex: Getting one element from a vector, and the rest from another.
5510 if (Elem.getOperand(0) != V)
5513 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5516 else if (IncorrectIdx == -1U) {
5520 // There was already one element with an incorrect index.
5521 // We can't optimize this case to an insertps.
5525 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5527 EVT VT = Op.getSimpleValueType();
5528 unsigned ElementMoveMask = 0;
5529 if (IncorrectIdx == -1U)
5530 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5532 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5534 SDValue InsertpsMask =
5535 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5536 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5542 /// getVShift - Return a vector logical shift node.
5544 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5545 unsigned NumBits, SelectionDAG &DAG,
5546 const TargetLowering &TLI, SDLoc dl) {
5547 assert(VT.is128BitVector() && "Unknown type for VShift");
5548 EVT ShVT = MVT::v2i64;
5549 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5550 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5551 return DAG.getNode(ISD::BITCAST, dl, VT,
5552 DAG.getNode(Opc, dl, ShVT, SrcOp,
5553 DAG.getConstant(NumBits,
5554 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5558 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5560 // Check if the scalar load can be widened into a vector load. And if
5561 // the address is "base + cst" see if the cst can be "absorbed" into
5562 // the shuffle mask.
5563 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5564 SDValue Ptr = LD->getBasePtr();
5565 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5567 EVT PVT = LD->getValueType(0);
5568 if (PVT != MVT::i32 && PVT != MVT::f32)
5573 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5574 FI = FINode->getIndex();
5576 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5577 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5578 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5579 Offset = Ptr.getConstantOperandVal(1);
5580 Ptr = Ptr.getOperand(0);
5585 // FIXME: 256-bit vector instructions don't require a strict alignment,
5586 // improve this code to support it better.
5587 unsigned RequiredAlign = VT.getSizeInBits()/8;
5588 SDValue Chain = LD->getChain();
5589 // Make sure the stack object alignment is at least 16 or 32.
5590 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5591 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5592 if (MFI->isFixedObjectIndex(FI)) {
5593 // Can't change the alignment. FIXME: It's possible to compute
5594 // the exact stack offset and reference FI + adjust offset instead.
5595 // If someone *really* cares about this. That's the way to implement it.
5598 MFI->setObjectAlignment(FI, RequiredAlign);
5602 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5603 // Ptr + (Offset & ~15).
5606 if ((Offset % RequiredAlign) & 3)
5608 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5610 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5611 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5613 int EltNo = (Offset - StartOffset) >> 2;
5614 unsigned NumElems = VT.getVectorNumElements();
5616 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5617 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5618 LD->getPointerInfo().getWithOffset(StartOffset),
5619 false, false, false, 0);
5621 SmallVector<int, 8> Mask;
5622 for (unsigned i = 0; i != NumElems; ++i)
5623 Mask.push_back(EltNo);
5625 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5631 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5632 /// vector of type 'VT', see if the elements can be replaced by a single large
5633 /// load which has the same value as a build_vector whose operands are 'elts'.
5635 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5637 /// FIXME: we'd also like to handle the case where the last elements are zero
5638 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5639 /// There's even a handy isZeroNode for that purpose.
5640 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5641 SDLoc &DL, SelectionDAG &DAG,
5642 bool isAfterLegalize) {
5643 EVT EltVT = VT.getVectorElementType();
5644 unsigned NumElems = Elts.size();
5646 LoadSDNode *LDBase = nullptr;
5647 unsigned LastLoadedElt = -1U;
5649 // For each element in the initializer, see if we've found a load or an undef.
5650 // If we don't find an initial load element, or later load elements are
5651 // non-consecutive, bail out.
5652 for (unsigned i = 0; i < NumElems; ++i) {
5653 SDValue Elt = Elts[i];
5655 if (!Elt.getNode() ||
5656 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5659 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5661 LDBase = cast<LoadSDNode>(Elt.getNode());
5665 if (Elt.getOpcode() == ISD::UNDEF)
5668 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5669 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5674 // If we have found an entire vector of loads and undefs, then return a large
5675 // load of the entire vector width starting at the base pointer. If we found
5676 // consecutive loads for the low half, generate a vzext_load node.
5677 if (LastLoadedElt == NumElems - 1) {
5679 if (isAfterLegalize &&
5680 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5683 SDValue NewLd = SDValue();
5685 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5686 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5687 LDBase->getPointerInfo(),
5688 LDBase->isVolatile(), LDBase->isNonTemporal(),
5689 LDBase->isInvariant(), 0);
5690 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5691 LDBase->getPointerInfo(),
5692 LDBase->isVolatile(), LDBase->isNonTemporal(),
5693 LDBase->isInvariant(), LDBase->getAlignment());
5695 if (LDBase->hasAnyUseOfValue(1)) {
5696 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5698 SDValue(NewLd.getNode(), 1));
5699 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5700 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5701 SDValue(NewLd.getNode(), 1));
5706 if (NumElems == 4 && LastLoadedElt == 1 &&
5707 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5708 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5709 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5711 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5712 LDBase->getPointerInfo(),
5713 LDBase->getAlignment(),
5714 false/*isVolatile*/, true/*ReadMem*/,
5717 // Make sure the newly-created LOAD is in the same position as LDBase in
5718 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5719 // update uses of LDBase's output chain to use the TokenFactor.
5720 if (LDBase->hasAnyUseOfValue(1)) {
5721 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5722 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5723 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5724 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5725 SDValue(ResNode.getNode(), 1));
5728 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5733 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5734 /// to generate a splat value for the following cases:
5735 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5736 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5737 /// a scalar load, or a constant.
5738 /// The VBROADCAST node is returned when a pattern is found,
5739 /// or SDValue() otherwise.
5740 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5741 SelectionDAG &DAG) {
5742 if (!Subtarget->hasFp256())
5745 MVT VT = Op.getSimpleValueType();
5748 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5749 "Unsupported vector type for broadcast.");
5754 switch (Op.getOpcode()) {
5756 // Unknown pattern found.
5759 case ISD::BUILD_VECTOR: {
5760 // The BUILD_VECTOR node must be a splat.
5761 if (!isSplatVector(Op.getNode()))
5764 Ld = Op.getOperand(0);
5765 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5766 Ld.getOpcode() == ISD::ConstantFP);
5768 // The suspected load node has several users. Make sure that all
5769 // of its users are from the BUILD_VECTOR node.
5770 // Constants may have multiple users.
5771 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5776 case ISD::VECTOR_SHUFFLE: {
5777 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5779 // Shuffles must have a splat mask where the first element is
5781 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5784 SDValue Sc = Op.getOperand(0);
5785 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5786 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5788 if (!Subtarget->hasInt256())
5791 // Use the register form of the broadcast instruction available on AVX2.
5792 if (VT.getSizeInBits() >= 256)
5793 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5794 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5797 Ld = Sc.getOperand(0);
5798 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5799 Ld.getOpcode() == ISD::ConstantFP);
5801 // The scalar_to_vector node and the suspected
5802 // load node must have exactly one user.
5803 // Constants may have multiple users.
5805 // AVX-512 has register version of the broadcast
5806 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5807 Ld.getValueType().getSizeInBits() >= 32;
5808 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5815 bool IsGE256 = (VT.getSizeInBits() >= 256);
5817 // Handle the broadcasting a single constant scalar from the constant pool
5818 // into a vector. On Sandybridge it is still better to load a constant vector
5819 // from the constant pool and not to broadcast it from a scalar.
5820 if (ConstSplatVal && Subtarget->hasInt256()) {
5821 EVT CVT = Ld.getValueType();
5822 assert(!CVT.isVector() && "Must not broadcast a vector type");
5823 unsigned ScalarSize = CVT.getSizeInBits();
5825 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5826 const Constant *C = nullptr;
5827 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5828 C = CI->getConstantIntValue();
5829 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5830 C = CF->getConstantFPValue();
5832 assert(C && "Invalid constant type");
5834 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5835 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5836 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5837 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5838 MachinePointerInfo::getConstantPool(),
5839 false, false, false, Alignment);
5841 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5845 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5846 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5848 // Handle AVX2 in-register broadcasts.
5849 if (!IsLoad && Subtarget->hasInt256() &&
5850 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5851 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5853 // The scalar source must be a normal load.
5857 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5858 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5860 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5861 // double since there is no vbroadcastsd xmm
5862 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5863 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5864 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5867 // Unsupported broadcast.
5871 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5872 /// underlying vector and index.
5874 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5876 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5878 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5879 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5882 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5884 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5886 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5887 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5890 // In this case the vector is the extract_subvector expression and the index
5891 // is 2, as specified by the shuffle.
5892 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5893 SDValue ShuffleVec = SVOp->getOperand(0);
5894 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5895 assert(ShuffleVecVT.getVectorElementType() ==
5896 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5898 int ShuffleIdx = SVOp->getMaskElt(Idx);
5899 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5900 ExtractedFromVec = ShuffleVec;
5906 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5907 MVT VT = Op.getSimpleValueType();
5909 // Skip if insert_vec_elt is not supported.
5910 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5911 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5915 unsigned NumElems = Op.getNumOperands();
5919 SmallVector<unsigned, 4> InsertIndices;
5920 SmallVector<int, 8> Mask(NumElems, -1);
5922 for (unsigned i = 0; i != NumElems; ++i) {
5923 unsigned Opc = Op.getOperand(i).getOpcode();
5925 if (Opc == ISD::UNDEF)
5928 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5929 // Quit if more than 1 elements need inserting.
5930 if (InsertIndices.size() > 1)
5933 InsertIndices.push_back(i);
5937 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5938 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5939 // Quit if non-constant index.
5940 if (!isa<ConstantSDNode>(ExtIdx))
5942 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5944 // Quit if extracted from vector of different type.
5945 if (ExtractedFromVec.getValueType() != VT)
5948 if (!VecIn1.getNode())
5949 VecIn1 = ExtractedFromVec;
5950 else if (VecIn1 != ExtractedFromVec) {
5951 if (!VecIn2.getNode())
5952 VecIn2 = ExtractedFromVec;
5953 else if (VecIn2 != ExtractedFromVec)
5954 // Quit if more than 2 vectors to shuffle
5958 if (ExtractedFromVec == VecIn1)
5960 else if (ExtractedFromVec == VecIn2)
5961 Mask[i] = Idx + NumElems;
5964 if (!VecIn1.getNode())
5967 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5968 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5969 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5970 unsigned Idx = InsertIndices[i];
5971 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5972 DAG.getIntPtrConstant(Idx));
5978 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5980 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5982 MVT VT = Op.getSimpleValueType();
5983 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5984 "Unexpected type in LowerBUILD_VECTORvXi1!");
5987 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5988 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5989 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5990 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5993 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5994 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5995 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5996 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5999 bool AllContants = true;
6000 uint64_t Immediate = 0;
6001 int NonConstIdx = -1;
6002 bool IsSplat = true;
6003 unsigned NumNonConsts = 0;
6004 unsigned NumConsts = 0;
6005 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6006 SDValue In = Op.getOperand(idx);
6007 if (In.getOpcode() == ISD::UNDEF)
6009 if (!isa<ConstantSDNode>(In)) {
6010 AllContants = false;
6016 if (cast<ConstantSDNode>(In)->getZExtValue())
6017 Immediate |= (1ULL << idx);
6019 if (In != Op.getOperand(0))
6024 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6025 DAG.getConstant(Immediate, MVT::i16));
6026 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6027 DAG.getIntPtrConstant(0));
6030 if (NumNonConsts == 1 && NonConstIdx != 0) {
6033 SDValue VecAsImm = DAG.getConstant(Immediate,
6034 MVT::getIntegerVT(VT.getSizeInBits()));
6035 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6038 DstVec = DAG.getUNDEF(VT);
6039 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6040 Op.getOperand(NonConstIdx),
6041 DAG.getIntPtrConstant(NonConstIdx));
6043 if (!IsSplat && (NonConstIdx != 0))
6044 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6045 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6048 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6049 DAG.getConstant(-1, SelectVT),
6050 DAG.getConstant(0, SelectVT));
6052 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6053 DAG.getConstant((Immediate | 1), SelectVT),
6054 DAG.getConstant(Immediate, SelectVT));
6055 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6058 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6059 const X86Subtarget *Subtarget) {
6060 EVT VT = N->getValueType(0);
6062 // Try to match a horizontal ADD or SUB.
6063 if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) ||
6064 ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) ||
6065 ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6066 VT == MVT::v16i16) && Subtarget->hasAVX())) {
6067 unsigned NumOperands = N->getNumOperands();
6068 unsigned Opcode = N->getOperand(0)->getOpcode();
6069 bool isCommutable = false;
6070 bool CanFold = false;
6075 isCommutable = true;
6082 // Verify that operands have the same opcode; also, the opcode can only
6083 // be either of: ADD, FADD, SUB, FSUB.
6084 SDValue InVec0, InVec1;
6085 for (unsigned i = 0, e = NumOperands; i != e && CanFold; ++i) {
6086 SDValue Op = N->getOperand(i);
6087 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6092 SDValue Op0 = Op.getOperand(0);
6093 SDValue Op1 = Op.getOperand(1);
6095 // Try to match the following pattern:
6096 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6097 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6098 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6099 Op0.getOperand(0) == Op1.getOperand(0) &&
6100 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6101 isa<ConstantSDNode>(Op1.getOperand(1)));
6105 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6106 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6107 unsigned ExpectedIndex = (i * 2) % NumOperands;
6110 InVec0 = Op0.getOperand(0);
6111 else if (i * 2 == NumOperands)
6112 InVec1 = Op0.getOperand(0);
6114 SDValue Expected = (i * 2 < NumOperands) ? InVec0 : InVec1;
6115 if (I0 == ExpectedIndex)
6116 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6117 else if (isCommutable && I1 == ExpectedIndex) {
6118 // Try to see if we can match the following dag sequence:
6119 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6120 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6127 default : llvm_unreachable("Unexpected opcode found!");
6128 case ISD::ADD : NewOpcode = X86ISD::HADD; break;
6129 case ISD::FADD : NewOpcode = X86ISD::FHADD; break;
6130 case ISD::SUB : NewOpcode = X86ISD::HSUB; break;
6131 case ISD::FSUB : NewOpcode = X86ISD::FHSUB; break;
6134 if (VT.is256BitVector()) {
6137 // Convert this sequence into two horizontal add/sub followed
6138 // by a concat vector.
6139 SDValue InVec0_LO = Extract128BitVector(InVec0, 0, DAG, dl);
6141 Extract128BitVector(InVec0, NumOperands/2, DAG, dl);
6142 SDValue InVec1_LO = Extract128BitVector(InVec1, 0, DAG, dl);
6144 Extract128BitVector(InVec1, NumOperands/2, DAG, dl);
6145 EVT NewVT = InVec0_LO.getValueType();
6147 SDValue LO = DAG.getNode(NewOpcode, dl, NewVT, InVec0_LO, InVec0_HI);
6148 SDValue HI = DAG.getNode(NewOpcode, dl, NewVT, InVec1_LO, InVec1_HI);
6149 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LO, HI);
6152 return DAG.getNode(NewOpcode, SDLoc(N), VT, InVec0, InVec1);
6160 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6163 MVT VT = Op.getSimpleValueType();
6164 MVT ExtVT = VT.getVectorElementType();
6165 unsigned NumElems = Op.getNumOperands();
6167 // Generate vectors for predicate vectors.
6168 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6169 return LowerBUILD_VECTORvXi1(Op, DAG);
6171 // Vectors containing all zeros can be matched by pxor and xorps later
6172 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6173 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6174 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6175 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6178 return getZeroVector(VT, Subtarget, DAG, dl);
6181 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6182 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6183 // vpcmpeqd on 256-bit vectors.
6184 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6185 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6188 if (!VT.is512BitVector())
6189 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6192 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6193 if (Broadcast.getNode())
6196 unsigned EVTBits = ExtVT.getSizeInBits();
6198 unsigned NumZero = 0;
6199 unsigned NumNonZero = 0;
6200 unsigned NonZeros = 0;
6201 bool IsAllConstants = true;
6202 SmallSet<SDValue, 8> Values;
6203 for (unsigned i = 0; i < NumElems; ++i) {
6204 SDValue Elt = Op.getOperand(i);
6205 if (Elt.getOpcode() == ISD::UNDEF)
6208 if (Elt.getOpcode() != ISD::Constant &&
6209 Elt.getOpcode() != ISD::ConstantFP)
6210 IsAllConstants = false;
6211 if (X86::isZeroNode(Elt))
6214 NonZeros |= (1 << i);
6219 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6220 if (NumNonZero == 0)
6221 return DAG.getUNDEF(VT);
6223 // Special case for single non-zero, non-undef, element.
6224 if (NumNonZero == 1) {
6225 unsigned Idx = countTrailingZeros(NonZeros);
6226 SDValue Item = Op.getOperand(Idx);
6228 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6229 // the value are obviously zero, truncate the value to i32 and do the
6230 // insertion that way. Only do this if the value is non-constant or if the
6231 // value is a constant being inserted into element 0. It is cheaper to do
6232 // a constant pool load than it is to do a movd + shuffle.
6233 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6234 (!IsAllConstants || Idx == 0)) {
6235 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6237 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6238 EVT VecVT = MVT::v4i32;
6239 unsigned VecElts = 4;
6241 // Truncate the value (which may itself be a constant) to i32, and
6242 // convert it to a vector with movd (S2V+shuffle to zero extend).
6243 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6244 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6245 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6247 // Now we have our 32-bit value zero extended in the low element of
6248 // a vector. If Idx != 0, swizzle it into place.
6250 SmallVector<int, 4> Mask;
6251 Mask.push_back(Idx);
6252 for (unsigned i = 1; i != VecElts; ++i)
6254 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6257 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6261 // If we have a constant or non-constant insertion into the low element of
6262 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6263 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6264 // depending on what the source datatype is.
6267 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6269 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6270 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6271 if (VT.is256BitVector() || VT.is512BitVector()) {
6272 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6273 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6274 Item, DAG.getIntPtrConstant(0));
6276 assert(VT.is128BitVector() && "Expected an SSE value type!");
6277 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6278 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6279 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6282 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6283 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6284 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6285 if (VT.is256BitVector()) {
6286 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6287 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6289 assert(VT.is128BitVector() && "Expected an SSE value type!");
6290 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6292 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6296 // Is it a vector logical left shift?
6297 if (NumElems == 2 && Idx == 1 &&
6298 X86::isZeroNode(Op.getOperand(0)) &&
6299 !X86::isZeroNode(Op.getOperand(1))) {
6300 unsigned NumBits = VT.getSizeInBits();
6301 return getVShift(true, VT,
6302 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6303 VT, Op.getOperand(1)),
6304 NumBits/2, DAG, *this, dl);
6307 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6310 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6311 // is a non-constant being inserted into an element other than the low one,
6312 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6313 // movd/movss) to move this into the low element, then shuffle it into
6315 if (EVTBits == 32) {
6316 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6318 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6319 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6320 SmallVector<int, 8> MaskVec;
6321 for (unsigned i = 0; i != NumElems; ++i)
6322 MaskVec.push_back(i == Idx ? 0 : 1);
6323 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6327 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6328 if (Values.size() == 1) {
6329 if (EVTBits == 32) {
6330 // Instead of a shuffle like this:
6331 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6332 // Check if it's possible to issue this instead.
6333 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6334 unsigned Idx = countTrailingZeros(NonZeros);
6335 SDValue Item = Op.getOperand(Idx);
6336 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6337 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6342 // A vector full of immediates; various special cases are already
6343 // handled, so this is best done with a single constant-pool load.
6347 // For AVX-length vectors, build the individual 128-bit pieces and use
6348 // shuffles to put them in place.
6349 if (VT.is256BitVector() || VT.is512BitVector()) {
6350 SmallVector<SDValue, 64> V;
6351 for (unsigned i = 0; i != NumElems; ++i)
6352 V.push_back(Op.getOperand(i));
6354 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6356 // Build both the lower and upper subvector.
6357 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6358 makeArrayRef(&V[0], NumElems/2));
6359 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6360 makeArrayRef(&V[NumElems / 2], NumElems/2));
6362 // Recreate the wider vector with the lower and upper part.
6363 if (VT.is256BitVector())
6364 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6365 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6368 // Let legalizer expand 2-wide build_vectors.
6369 if (EVTBits == 64) {
6370 if (NumNonZero == 1) {
6371 // One half is zero or undef.
6372 unsigned Idx = countTrailingZeros(NonZeros);
6373 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6374 Op.getOperand(Idx));
6375 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6380 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6381 if (EVTBits == 8 && NumElems == 16) {
6382 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6384 if (V.getNode()) return V;
6387 if (EVTBits == 16 && NumElems == 8) {
6388 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6390 if (V.getNode()) return V;
6393 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6394 if (EVTBits == 32 && NumElems == 4) {
6395 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6396 NumZero, DAG, Subtarget, *this);
6401 // If element VT is == 32 bits, turn it into a number of shuffles.
6402 SmallVector<SDValue, 8> V(NumElems);
6403 if (NumElems == 4 && NumZero > 0) {
6404 for (unsigned i = 0; i < 4; ++i) {
6405 bool isZero = !(NonZeros & (1 << i));
6407 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6409 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6412 for (unsigned i = 0; i < 2; ++i) {
6413 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6416 V[i] = V[i*2]; // Must be a zero vector.
6419 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6422 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6425 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6430 bool Reverse1 = (NonZeros & 0x3) == 2;
6431 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6435 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6436 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6438 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6441 if (Values.size() > 1 && VT.is128BitVector()) {
6442 // Check for a build vector of consecutive loads.
6443 for (unsigned i = 0; i < NumElems; ++i)
6444 V[i] = Op.getOperand(i);
6446 // Check for elements which are consecutive loads.
6447 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6451 // Check for a build vector from mostly shuffle plus few inserting.
6452 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6456 // For SSE 4.1, use insertps to put the high elements into the low element.
6457 if (getSubtarget()->hasSSE41()) {
6459 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6460 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6462 Result = DAG.getUNDEF(VT);
6464 for (unsigned i = 1; i < NumElems; ++i) {
6465 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6466 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6467 Op.getOperand(i), DAG.getIntPtrConstant(i));
6472 // Otherwise, expand into a number of unpckl*, start by extending each of
6473 // our (non-undef) elements to the full vector width with the element in the
6474 // bottom slot of the vector (which generates no code for SSE).
6475 for (unsigned i = 0; i < NumElems; ++i) {
6476 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6477 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6479 V[i] = DAG.getUNDEF(VT);
6482 // Next, we iteratively mix elements, e.g. for v4f32:
6483 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6484 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6485 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6486 unsigned EltStride = NumElems >> 1;
6487 while (EltStride != 0) {
6488 for (unsigned i = 0; i < EltStride; ++i) {
6489 // If V[i+EltStride] is undef and this is the first round of mixing,
6490 // then it is safe to just drop this shuffle: V[i] is already in the
6491 // right place, the one element (since it's the first round) being
6492 // inserted as undef can be dropped. This isn't safe for successive
6493 // rounds because they will permute elements within both vectors.
6494 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6495 EltStride == NumElems/2)
6498 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6507 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6508 // to create 256-bit vectors from two other 128-bit ones.
6509 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6511 MVT ResVT = Op.getSimpleValueType();
6513 assert((ResVT.is256BitVector() ||
6514 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6516 SDValue V1 = Op.getOperand(0);
6517 SDValue V2 = Op.getOperand(1);
6518 unsigned NumElems = ResVT.getVectorNumElements();
6519 if(ResVT.is256BitVector())
6520 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6522 if (Op.getNumOperands() == 4) {
6523 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6524 ResVT.getVectorNumElements()/2);
6525 SDValue V3 = Op.getOperand(2);
6526 SDValue V4 = Op.getOperand(3);
6527 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6528 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6530 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6533 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6534 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6535 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6536 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6537 Op.getNumOperands() == 4)));
6539 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6540 // from two other 128-bit ones.
6542 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6543 return LowerAVXCONCAT_VECTORS(Op, DAG);
6546 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6547 bool hasInt256, unsigned *MaskOut = nullptr) {
6548 MVT EltVT = VT.getVectorElementType();
6550 // There is no blend with immediate in AVX-512.
6551 if (VT.is512BitVector())
6554 if (!hasSSE41 || EltVT == MVT::i8)
6556 if (!hasInt256 && VT == MVT::v16i16)
6559 unsigned MaskValue = 0;
6560 unsigned NumElems = VT.getVectorNumElements();
6561 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6562 unsigned NumLanes = (NumElems - 1) / 8 + 1;
6563 unsigned NumElemsInLane = NumElems / NumLanes;
6565 // Blend for v16i16 should be symetric for the both lanes.
6566 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6568 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6569 int EltIdx = MaskVals[i];
6571 if ((EltIdx < 0 || EltIdx == (int)i) &&
6572 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6575 if (((unsigned)EltIdx == (i + NumElems)) &&
6576 (SndLaneEltIdx < 0 ||
6577 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6578 MaskValue |= (1 << i);
6584 *MaskOut = MaskValue;
6588 // Try to lower a shuffle node into a simple blend instruction.
6589 // This function assumes isBlendMask returns true for this
6590 // SuffleVectorSDNode
6591 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6593 const X86Subtarget *Subtarget,
6594 SelectionDAG &DAG) {
6595 MVT VT = SVOp->getSimpleValueType(0);
6596 MVT EltVT = VT.getVectorElementType();
6597 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6598 Subtarget->hasInt256() && "Trying to lower a "
6599 "VECTOR_SHUFFLE to a Blend but "
6600 "with the wrong mask"));
6601 SDValue V1 = SVOp->getOperand(0);
6602 SDValue V2 = SVOp->getOperand(1);
6604 unsigned NumElems = VT.getVectorNumElements();
6606 // Convert i32 vectors to floating point if it is not AVX2.
6607 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6609 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6610 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6612 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6613 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6616 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6617 DAG.getConstant(MaskValue, MVT::i32));
6618 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6621 /// In vector type \p VT, return true if the element at index \p InputIdx
6622 /// falls on a different 128-bit lane than \p OutputIdx.
6623 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6624 unsigned OutputIdx) {
6625 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6626 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6629 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6630 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6631 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6632 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6634 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6635 SelectionDAG &DAG) {
6636 MVT VT = V1.getSimpleValueType();
6637 assert(VT.is128BitVector() || VT.is256BitVector());
6639 MVT EltVT = VT.getVectorElementType();
6640 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6641 unsigned NumElts = VT.getVectorNumElements();
6643 SmallVector<SDValue, 32> PshufbMask;
6644 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6645 int InputIdx = MaskVals[OutputIdx];
6646 unsigned InputByteIdx;
6648 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6649 InputByteIdx = 0x80;
6651 // Cross lane is not allowed.
6652 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6654 InputByteIdx = InputIdx * EltSizeInBytes;
6655 // Index is an byte offset within the 128-bit lane.
6656 InputByteIdx &= 0xf;
6659 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6660 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6661 if (InputByteIdx != 0x80)
6666 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6668 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6669 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6670 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6673 // v8i16 shuffles - Prefer shuffles in the following order:
6674 // 1. [all] pshuflw, pshufhw, optional move
6675 // 2. [ssse3] 1 x pshufb
6676 // 3. [ssse3] 2 x pshufb + 1 x por
6677 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6679 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6680 SelectionDAG &DAG) {
6681 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6682 SDValue V1 = SVOp->getOperand(0);
6683 SDValue V2 = SVOp->getOperand(1);
6685 SmallVector<int, 8> MaskVals;
6687 // Determine if more than 1 of the words in each of the low and high quadwords
6688 // of the result come from the same quadword of one of the two inputs. Undef
6689 // mask values count as coming from any quadword, for better codegen.
6691 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6692 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6693 unsigned LoQuad[] = { 0, 0, 0, 0 };
6694 unsigned HiQuad[] = { 0, 0, 0, 0 };
6695 // Indices of quads used.
6696 std::bitset<4> InputQuads;
6697 for (unsigned i = 0; i < 8; ++i) {
6698 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6699 int EltIdx = SVOp->getMaskElt(i);
6700 MaskVals.push_back(EltIdx);
6709 InputQuads.set(EltIdx / 4);
6712 int BestLoQuad = -1;
6713 unsigned MaxQuad = 1;
6714 for (unsigned i = 0; i < 4; ++i) {
6715 if (LoQuad[i] > MaxQuad) {
6717 MaxQuad = LoQuad[i];
6721 int BestHiQuad = -1;
6723 for (unsigned i = 0; i < 4; ++i) {
6724 if (HiQuad[i] > MaxQuad) {
6726 MaxQuad = HiQuad[i];
6730 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6731 // of the two input vectors, shuffle them into one input vector so only a
6732 // single pshufb instruction is necessary. If there are more than 2 input
6733 // quads, disable the next transformation since it does not help SSSE3.
6734 bool V1Used = InputQuads[0] || InputQuads[1];
6735 bool V2Used = InputQuads[2] || InputQuads[3];
6736 if (Subtarget->hasSSSE3()) {
6737 if (InputQuads.count() == 2 && V1Used && V2Used) {
6738 BestLoQuad = InputQuads[0] ? 0 : 1;
6739 BestHiQuad = InputQuads[2] ? 2 : 3;
6741 if (InputQuads.count() > 2) {
6747 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6748 // the shuffle mask. If a quad is scored as -1, that means that it contains
6749 // words from all 4 input quadwords.
6751 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6753 BestLoQuad < 0 ? 0 : BestLoQuad,
6754 BestHiQuad < 0 ? 1 : BestHiQuad
6756 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6757 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6758 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6759 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6761 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6762 // source words for the shuffle, to aid later transformations.
6763 bool AllWordsInNewV = true;
6764 bool InOrder[2] = { true, true };
6765 for (unsigned i = 0; i != 8; ++i) {
6766 int idx = MaskVals[i];
6768 InOrder[i/4] = false;
6769 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6771 AllWordsInNewV = false;
6775 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6776 if (AllWordsInNewV) {
6777 for (int i = 0; i != 8; ++i) {
6778 int idx = MaskVals[i];
6781 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6782 if ((idx != i) && idx < 4)
6784 if ((idx != i) && idx > 3)
6793 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6794 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6795 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6796 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6797 unsigned TargetMask = 0;
6798 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6799 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6800 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6801 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6802 getShufflePSHUFLWImmediate(SVOp);
6803 V1 = NewV.getOperand(0);
6804 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6808 // Promote splats to a larger type which usually leads to more efficient code.
6809 // FIXME: Is this true if pshufb is available?
6810 if (SVOp->isSplat())
6811 return PromoteSplat(SVOp, DAG);
6813 // If we have SSSE3, and all words of the result are from 1 input vector,
6814 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6815 // is present, fall back to case 4.
6816 if (Subtarget->hasSSSE3()) {
6817 SmallVector<SDValue,16> pshufbMask;
6819 // If we have elements from both input vectors, set the high bit of the
6820 // shuffle mask element to zero out elements that come from V2 in the V1
6821 // mask, and elements that come from V1 in the V2 mask, so that the two
6822 // results can be OR'd together.
6823 bool TwoInputs = V1Used && V2Used;
6824 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6826 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6828 // Calculate the shuffle mask for the second input, shuffle it, and
6829 // OR it with the first shuffled input.
6830 CommuteVectorShuffleMask(MaskVals, 8);
6831 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6832 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6833 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6836 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6837 // and update MaskVals with new element order.
6838 std::bitset<8> InOrder;
6839 if (BestLoQuad >= 0) {
6840 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6841 for (int i = 0; i != 4; ++i) {
6842 int idx = MaskVals[i];
6845 } else if ((idx / 4) == BestLoQuad) {
6850 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6853 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6854 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6855 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6857 getShufflePSHUFLWImmediate(SVOp), DAG);
6861 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6862 // and update MaskVals with the new element order.
6863 if (BestHiQuad >= 0) {
6864 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6865 for (unsigned i = 4; i != 8; ++i) {
6866 int idx = MaskVals[i];
6869 } else if ((idx / 4) == BestHiQuad) {
6870 MaskV[i] = (idx & 3) + 4;
6874 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6877 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6878 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6879 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6881 getShufflePSHUFHWImmediate(SVOp), DAG);
6885 // In case BestHi & BestLo were both -1, which means each quadword has a word
6886 // from each of the four input quadwords, calculate the InOrder bitvector now
6887 // before falling through to the insert/extract cleanup.
6888 if (BestLoQuad == -1 && BestHiQuad == -1) {
6890 for (int i = 0; i != 8; ++i)
6891 if (MaskVals[i] < 0 || MaskVals[i] == i)
6895 // The other elements are put in the right place using pextrw and pinsrw.
6896 for (unsigned i = 0; i != 8; ++i) {
6899 int EltIdx = MaskVals[i];
6902 SDValue ExtOp = (EltIdx < 8) ?
6903 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6904 DAG.getIntPtrConstant(EltIdx)) :
6905 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6906 DAG.getIntPtrConstant(EltIdx - 8));
6907 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6908 DAG.getIntPtrConstant(i));
6913 /// \brief v16i16 shuffles
6915 /// FIXME: We only support generation of a single pshufb currently. We can
6916 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6917 /// well (e.g 2 x pshufb + 1 x por).
6919 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6920 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6921 SDValue V1 = SVOp->getOperand(0);
6922 SDValue V2 = SVOp->getOperand(1);
6925 if (V2.getOpcode() != ISD::UNDEF)
6928 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6929 return getPSHUFB(MaskVals, V1, dl, DAG);
6932 // v16i8 shuffles - Prefer shuffles in the following order:
6933 // 1. [ssse3] 1 x pshufb
6934 // 2. [ssse3] 2 x pshufb + 1 x por
6935 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6936 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6937 const X86Subtarget* Subtarget,
6938 SelectionDAG &DAG) {
6939 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6940 SDValue V1 = SVOp->getOperand(0);
6941 SDValue V2 = SVOp->getOperand(1);
6943 ArrayRef<int> MaskVals = SVOp->getMask();
6945 // Promote splats to a larger type which usually leads to more efficient code.
6946 // FIXME: Is this true if pshufb is available?
6947 if (SVOp->isSplat())
6948 return PromoteSplat(SVOp, DAG);
6950 // If we have SSSE3, case 1 is generated when all result bytes come from
6951 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6952 // present, fall back to case 3.
6954 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6955 if (Subtarget->hasSSSE3()) {
6956 SmallVector<SDValue,16> pshufbMask;
6958 // If all result elements are from one input vector, then only translate
6959 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6961 // Otherwise, we have elements from both input vectors, and must zero out
6962 // elements that come from V2 in the first mask, and V1 in the second mask
6963 // so that we can OR them together.
6964 for (unsigned i = 0; i != 16; ++i) {
6965 int EltIdx = MaskVals[i];
6966 if (EltIdx < 0 || EltIdx >= 16)
6968 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6970 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6971 DAG.getNode(ISD::BUILD_VECTOR, dl,
6972 MVT::v16i8, pshufbMask));
6974 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6975 // the 2nd operand if it's undefined or zero.
6976 if (V2.getOpcode() == ISD::UNDEF ||
6977 ISD::isBuildVectorAllZeros(V2.getNode()))
6980 // Calculate the shuffle mask for the second input, shuffle it, and
6981 // OR it with the first shuffled input.
6983 for (unsigned i = 0; i != 16; ++i) {
6984 int EltIdx = MaskVals[i];
6985 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6986 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6988 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6989 DAG.getNode(ISD::BUILD_VECTOR, dl,
6990 MVT::v16i8, pshufbMask));
6991 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6994 // No SSSE3 - Calculate in place words and then fix all out of place words
6995 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6996 // the 16 different words that comprise the two doublequadword input vectors.
6997 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6998 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
7000 for (int i = 0; i != 8; ++i) {
7001 int Elt0 = MaskVals[i*2];
7002 int Elt1 = MaskVals[i*2+1];
7004 // This word of the result is all undef, skip it.
7005 if (Elt0 < 0 && Elt1 < 0)
7008 // This word of the result is already in the correct place, skip it.
7009 if ((Elt0 == i*2) && (Elt1 == i*2+1))
7012 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
7013 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
7016 // If Elt0 and Elt1 are defined, are consecutive, and can be load
7017 // using a single extract together, load it and store it.
7018 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7019 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7020 DAG.getIntPtrConstant(Elt1 / 2));
7021 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7022 DAG.getIntPtrConstant(i));
7026 // If Elt1 is defined, extract it from the appropriate source. If the
7027 // source byte is not also odd, shift the extracted word left 8 bits
7028 // otherwise clear the bottom 8 bits if we need to do an or.
7030 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7031 DAG.getIntPtrConstant(Elt1 / 2));
7032 if ((Elt1 & 1) == 0)
7033 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7035 TLI.getShiftAmountTy(InsElt.getValueType())));
7037 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7038 DAG.getConstant(0xFF00, MVT::i16));
7040 // If Elt0 is defined, extract it from the appropriate source. If the
7041 // source byte is not also even, shift the extracted word right 8 bits. If
7042 // Elt1 was also defined, OR the extracted values together before
7043 // inserting them in the result.
7045 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7046 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7047 if ((Elt0 & 1) != 0)
7048 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7050 TLI.getShiftAmountTy(InsElt0.getValueType())));
7052 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7053 DAG.getConstant(0x00FF, MVT::i16));
7054 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7057 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7058 DAG.getIntPtrConstant(i));
7060 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7063 // v32i8 shuffles - Translate to VPSHUFB if possible.
7065 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7066 const X86Subtarget *Subtarget,
7067 SelectionDAG &DAG) {
7068 MVT VT = SVOp->getSimpleValueType(0);
7069 SDValue V1 = SVOp->getOperand(0);
7070 SDValue V2 = SVOp->getOperand(1);
7072 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7074 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7075 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7076 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7078 // VPSHUFB may be generated if
7079 // (1) one of input vector is undefined or zeroinitializer.
7080 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7081 // And (2) the mask indexes don't cross the 128-bit lane.
7082 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7083 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7086 if (V1IsAllZero && !V2IsAllZero) {
7087 CommuteVectorShuffleMask(MaskVals, 32);
7090 return getPSHUFB(MaskVals, V1, dl, DAG);
7093 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7094 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7095 /// done when every pair / quad of shuffle mask elements point to elements in
7096 /// the right sequence. e.g.
7097 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7099 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7100 SelectionDAG &DAG) {
7101 MVT VT = SVOp->getSimpleValueType(0);
7103 unsigned NumElems = VT.getVectorNumElements();
7106 switch (VT.SimpleTy) {
7107 default: llvm_unreachable("Unexpected!");
7110 return SDValue(SVOp, 0);
7111 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
7112 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
7113 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
7114 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
7115 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7116 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
7119 SmallVector<int, 8> MaskVec;
7120 for (unsigned i = 0; i != NumElems; i += Scale) {
7122 for (unsigned j = 0; j != Scale; ++j) {
7123 int EltIdx = SVOp->getMaskElt(i+j);
7127 StartIdx = (EltIdx / Scale);
7128 if (EltIdx != (int)(StartIdx*Scale + j))
7131 MaskVec.push_back(StartIdx);
7134 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7135 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7136 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7139 /// getVZextMovL - Return a zero-extending vector move low node.
7141 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7142 SDValue SrcOp, SelectionDAG &DAG,
7143 const X86Subtarget *Subtarget, SDLoc dl) {
7144 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7145 LoadSDNode *LD = nullptr;
7146 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7147 LD = dyn_cast<LoadSDNode>(SrcOp);
7149 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7151 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7152 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7153 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7154 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7155 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7157 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7158 return DAG.getNode(ISD::BITCAST, dl, VT,
7159 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7160 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7168 return DAG.getNode(ISD::BITCAST, dl, VT,
7169 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7170 DAG.getNode(ISD::BITCAST, dl,
7174 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7175 /// which could not be matched by any known target speficic shuffle
7177 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7179 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7180 if (NewOp.getNode())
7183 MVT VT = SVOp->getSimpleValueType(0);
7185 unsigned NumElems = VT.getVectorNumElements();
7186 unsigned NumLaneElems = NumElems / 2;
7189 MVT EltVT = VT.getVectorElementType();
7190 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7193 SmallVector<int, 16> Mask;
7194 for (unsigned l = 0; l < 2; ++l) {
7195 // Build a shuffle mask for the output, discovering on the fly which
7196 // input vectors to use as shuffle operands (recorded in InputUsed).
7197 // If building a suitable shuffle vector proves too hard, then bail
7198 // out with UseBuildVector set.
7199 bool UseBuildVector = false;
7200 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7201 unsigned LaneStart = l * NumLaneElems;
7202 for (unsigned i = 0; i != NumLaneElems; ++i) {
7203 // The mask element. This indexes into the input.
7204 int Idx = SVOp->getMaskElt(i+LaneStart);
7206 // the mask element does not index into any input vector.
7211 // The input vector this mask element indexes into.
7212 int Input = Idx / NumLaneElems;
7214 // Turn the index into an offset from the start of the input vector.
7215 Idx -= Input * NumLaneElems;
7217 // Find or create a shuffle vector operand to hold this input.
7219 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7220 if (InputUsed[OpNo] == Input)
7221 // This input vector is already an operand.
7223 if (InputUsed[OpNo] < 0) {
7224 // Create a new operand for this input vector.
7225 InputUsed[OpNo] = Input;
7230 if (OpNo >= array_lengthof(InputUsed)) {
7231 // More than two input vectors used! Give up on trying to create a
7232 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7233 UseBuildVector = true;
7237 // Add the mask index for the new shuffle vector.
7238 Mask.push_back(Idx + OpNo * NumLaneElems);
7241 if (UseBuildVector) {
7242 SmallVector<SDValue, 16> SVOps;
7243 for (unsigned i = 0; i != NumLaneElems; ++i) {
7244 // The mask element. This indexes into the input.
7245 int Idx = SVOp->getMaskElt(i+LaneStart);
7247 SVOps.push_back(DAG.getUNDEF(EltVT));
7251 // The input vector this mask element indexes into.
7252 int Input = Idx / NumElems;
7254 // Turn the index into an offset from the start of the input vector.
7255 Idx -= Input * NumElems;
7257 // Extract the vector element by hand.
7258 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7259 SVOp->getOperand(Input),
7260 DAG.getIntPtrConstant(Idx)));
7263 // Construct the output using a BUILD_VECTOR.
7264 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7265 } else if (InputUsed[0] < 0) {
7266 // No input vectors were used! The result is undefined.
7267 Output[l] = DAG.getUNDEF(NVT);
7269 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7270 (InputUsed[0] % 2) * NumLaneElems,
7272 // If only one input was used, use an undefined vector for the other.
7273 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7274 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7275 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7276 // At least one input vector was used. Create a new shuffle vector.
7277 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7283 // Concatenate the result back
7284 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7287 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7288 /// 4 elements, and match them with several different shuffle types.
7290 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7291 SDValue V1 = SVOp->getOperand(0);
7292 SDValue V2 = SVOp->getOperand(1);
7294 MVT VT = SVOp->getSimpleValueType(0);
7296 assert(VT.is128BitVector() && "Unsupported vector size");
7298 std::pair<int, int> Locs[4];
7299 int Mask1[] = { -1, -1, -1, -1 };
7300 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7304 for (unsigned i = 0; i != 4; ++i) {
7305 int Idx = PermMask[i];
7307 Locs[i] = std::make_pair(-1, -1);
7309 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7311 Locs[i] = std::make_pair(0, NumLo);
7315 Locs[i] = std::make_pair(1, NumHi);
7317 Mask1[2+NumHi] = Idx;
7323 if (NumLo <= 2 && NumHi <= 2) {
7324 // If no more than two elements come from either vector. This can be
7325 // implemented with two shuffles. First shuffle gather the elements.
7326 // The second shuffle, which takes the first shuffle as both of its
7327 // vector operands, put the elements into the right order.
7328 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7330 int Mask2[] = { -1, -1, -1, -1 };
7332 for (unsigned i = 0; i != 4; ++i)
7333 if (Locs[i].first != -1) {
7334 unsigned Idx = (i < 2) ? 0 : 4;
7335 Idx += Locs[i].first * 2 + Locs[i].second;
7339 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7342 if (NumLo == 3 || NumHi == 3) {
7343 // Otherwise, we must have three elements from one vector, call it X, and
7344 // one element from the other, call it Y. First, use a shufps to build an
7345 // intermediate vector with the one element from Y and the element from X
7346 // that will be in the same half in the final destination (the indexes don't
7347 // matter). Then, use a shufps to build the final vector, taking the half
7348 // containing the element from Y from the intermediate, and the other half
7351 // Normalize it so the 3 elements come from V1.
7352 CommuteVectorShuffleMask(PermMask, 4);
7356 // Find the element from V2.
7358 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7359 int Val = PermMask[HiIndex];
7366 Mask1[0] = PermMask[HiIndex];
7368 Mask1[2] = PermMask[HiIndex^1];
7370 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7373 Mask1[0] = PermMask[0];
7374 Mask1[1] = PermMask[1];
7375 Mask1[2] = HiIndex & 1 ? 6 : 4;
7376 Mask1[3] = HiIndex & 1 ? 4 : 6;
7377 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7380 Mask1[0] = HiIndex & 1 ? 2 : 0;
7381 Mask1[1] = HiIndex & 1 ? 0 : 2;
7382 Mask1[2] = PermMask[2];
7383 Mask1[3] = PermMask[3];
7388 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7391 // Break it into (shuffle shuffle_hi, shuffle_lo).
7392 int LoMask[] = { -1, -1, -1, -1 };
7393 int HiMask[] = { -1, -1, -1, -1 };
7395 int *MaskPtr = LoMask;
7396 unsigned MaskIdx = 0;
7399 for (unsigned i = 0; i != 4; ++i) {
7406 int Idx = PermMask[i];
7408 Locs[i] = std::make_pair(-1, -1);
7409 } else if (Idx < 4) {
7410 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7411 MaskPtr[LoIdx] = Idx;
7414 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7415 MaskPtr[HiIdx] = Idx;
7420 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7421 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7422 int MaskOps[] = { -1, -1, -1, -1 };
7423 for (unsigned i = 0; i != 4; ++i)
7424 if (Locs[i].first != -1)
7425 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7426 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7429 static bool MayFoldVectorLoad(SDValue V) {
7430 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7431 V = V.getOperand(0);
7433 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7434 V = V.getOperand(0);
7435 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7436 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7437 // BUILD_VECTOR (load), undef
7438 V = V.getOperand(0);
7440 return MayFoldLoad(V);
7444 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7445 MVT VT = Op.getSimpleValueType();
7447 // Canonizalize to v2f64.
7448 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7449 return DAG.getNode(ISD::BITCAST, dl, VT,
7450 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7455 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7457 SDValue V1 = Op.getOperand(0);
7458 SDValue V2 = Op.getOperand(1);
7459 MVT VT = Op.getSimpleValueType();
7461 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7463 if (HasSSE2 && VT == MVT::v2f64)
7464 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7466 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7467 return DAG.getNode(ISD::BITCAST, dl, VT,
7468 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7469 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7470 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7474 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7475 SDValue V1 = Op.getOperand(0);
7476 SDValue V2 = Op.getOperand(1);
7477 MVT VT = Op.getSimpleValueType();
7479 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7480 "unsupported shuffle type");
7482 if (V2.getOpcode() == ISD::UNDEF)
7486 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7490 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7491 SDValue V1 = Op.getOperand(0);
7492 SDValue V2 = Op.getOperand(1);
7493 MVT VT = Op.getSimpleValueType();
7494 unsigned NumElems = VT.getVectorNumElements();
7496 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7497 // operand of these instructions is only memory, so check if there's a
7498 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7500 bool CanFoldLoad = false;
7502 // Trivial case, when V2 comes from a load.
7503 if (MayFoldVectorLoad(V2))
7506 // When V1 is a load, it can be folded later into a store in isel, example:
7507 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7509 // (MOVLPSmr addr:$src1, VR128:$src2)
7510 // So, recognize this potential and also use MOVLPS or MOVLPD
7511 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7514 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7516 if (HasSSE2 && NumElems == 2)
7517 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7520 // If we don't care about the second element, proceed to use movss.
7521 if (SVOp->getMaskElt(1) != -1)
7522 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7525 // movl and movlp will both match v2i64, but v2i64 is never matched by
7526 // movl earlier because we make it strict to avoid messing with the movlp load
7527 // folding logic (see the code above getMOVLP call). Match it here then,
7528 // this is horrible, but will stay like this until we move all shuffle
7529 // matching to x86 specific nodes. Note that for the 1st condition all
7530 // types are matched with movsd.
7532 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7533 // as to remove this logic from here, as much as possible
7534 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7535 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7536 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7539 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7541 // Invert the operand order and use SHUFPS to match it.
7542 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7543 getShuffleSHUFImmediate(SVOp), DAG);
7546 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7547 SelectionDAG &DAG) {
7549 MVT VT = Load->getSimpleValueType(0);
7550 MVT EVT = VT.getVectorElementType();
7551 SDValue Addr = Load->getOperand(1);
7552 SDValue NewAddr = DAG.getNode(
7553 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7554 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7557 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7558 DAG.getMachineFunction().getMachineMemOperand(
7559 Load->getMemOperand(), 0, EVT.getStoreSize()));
7563 // It is only safe to call this function if isINSERTPSMask is true for
7564 // this shufflevector mask.
7565 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7566 SelectionDAG &DAG) {
7567 // Generate an insertps instruction when inserting an f32 from memory onto a
7568 // v4f32 or when copying a member from one v4f32 to another.
7569 // We also use it for transferring i32 from one register to another,
7570 // since it simply copies the same bits.
7571 // If we're transferring an i32 from memory to a specific element in a
7572 // register, we output a generic DAG that will match the PINSRD
7574 MVT VT = SVOp->getSimpleValueType(0);
7575 MVT EVT = VT.getVectorElementType();
7576 SDValue V1 = SVOp->getOperand(0);
7577 SDValue V2 = SVOp->getOperand(1);
7578 auto Mask = SVOp->getMask();
7579 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7580 "unsupported vector type for insertps/pinsrd");
7582 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7583 auto FromV2Predicate = [](const int &i) { return i >= 4; };
7584 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7592 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7595 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7596 "More than one element from V1 and from V2, or no elements from one "
7597 "of the vectors. This case should not have returned true from "
7602 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7605 if (MayFoldLoad(From)) {
7606 // Trivial case, when From comes from a load and is only used by the
7607 // shuffle. Make it use insertps from the vector that we need from that
7610 NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7611 if (!NewLoad.getNode())
7614 if (EVT == MVT::f32) {
7615 // Create this as a scalar to vector to match the instruction pattern.
7616 SDValue LoadScalarToVector =
7617 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7618 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7619 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7621 } else { // EVT == MVT::i32
7622 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7623 // instruction, to match the PINSRD instruction, which loads an i32 to a
7624 // certain vector element.
7625 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7626 DAG.getConstant(DestIndex, MVT::i32));
7630 // Vector-element-to-vector
7631 unsigned SrcIndex = Mask[DestIndex] % 4;
7632 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7633 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7636 // Reduce a vector shuffle to zext.
7637 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7638 SelectionDAG &DAG) {
7639 // PMOVZX is only available from SSE41.
7640 if (!Subtarget->hasSSE41())
7643 MVT VT = Op.getSimpleValueType();
7645 // Only AVX2 support 256-bit vector integer extending.
7646 if (!Subtarget->hasInt256() && VT.is256BitVector())
7649 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7651 SDValue V1 = Op.getOperand(0);
7652 SDValue V2 = Op.getOperand(1);
7653 unsigned NumElems = VT.getVectorNumElements();
7655 // Extending is an unary operation and the element type of the source vector
7656 // won't be equal to or larger than i64.
7657 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7658 VT.getVectorElementType() == MVT::i64)
7661 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7662 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7663 while ((1U << Shift) < NumElems) {
7664 if (SVOp->getMaskElt(1U << Shift) == 1)
7667 // The maximal ratio is 8, i.e. from i8 to i64.
7672 // Check the shuffle mask.
7673 unsigned Mask = (1U << Shift) - 1;
7674 for (unsigned i = 0; i != NumElems; ++i) {
7675 int EltIdx = SVOp->getMaskElt(i);
7676 if ((i & Mask) != 0 && EltIdx != -1)
7678 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7682 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7683 MVT NeVT = MVT::getIntegerVT(NBits);
7684 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7686 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7689 // Simplify the operand as it's prepared to be fed into shuffle.
7690 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7691 if (V1.getOpcode() == ISD::BITCAST &&
7692 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7693 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7694 V1.getOperand(0).getOperand(0)
7695 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7696 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7697 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7698 ConstantSDNode *CIdx =
7699 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7700 // If it's foldable, i.e. normal load with single use, we will let code
7701 // selection to fold it. Otherwise, we will short the conversion sequence.
7702 if (CIdx && CIdx->getZExtValue() == 0 &&
7703 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7704 MVT FullVT = V.getSimpleValueType();
7705 MVT V1VT = V1.getSimpleValueType();
7706 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7707 // The "ext_vec_elt" node is wider than the result node.
7708 // In this case we should extract subvector from V.
7709 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7710 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7711 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7712 FullVT.getVectorNumElements()/Ratio);
7713 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7714 DAG.getIntPtrConstant(0));
7716 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7720 return DAG.getNode(ISD::BITCAST, DL, VT,
7721 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7724 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7725 SelectionDAG &DAG) {
7726 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7727 MVT VT = Op.getSimpleValueType();
7729 SDValue V1 = Op.getOperand(0);
7730 SDValue V2 = Op.getOperand(1);
7732 if (isZeroShuffle(SVOp))
7733 return getZeroVector(VT, Subtarget, DAG, dl);
7735 // Handle splat operations
7736 if (SVOp->isSplat()) {
7737 // Use vbroadcast whenever the splat comes from a foldable load
7738 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7739 if (Broadcast.getNode())
7743 // Check integer expanding shuffles.
7744 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7745 if (NewOp.getNode())
7748 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7750 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7752 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7753 if (NewOp.getNode())
7754 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7755 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7756 // FIXME: Figure out a cleaner way to do this.
7757 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7758 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7759 if (NewOp.getNode()) {
7760 MVT NewVT = NewOp.getSimpleValueType();
7761 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7762 NewVT, true, false))
7763 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7766 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7767 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7768 if (NewOp.getNode()) {
7769 MVT NewVT = NewOp.getSimpleValueType();
7770 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7771 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7780 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7781 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7782 SDValue V1 = Op.getOperand(0);
7783 SDValue V2 = Op.getOperand(1);
7784 MVT VT = Op.getSimpleValueType();
7786 unsigned NumElems = VT.getVectorNumElements();
7787 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7788 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7789 bool V1IsSplat = false;
7790 bool V2IsSplat = false;
7791 bool HasSSE2 = Subtarget->hasSSE2();
7792 bool HasFp256 = Subtarget->hasFp256();
7793 bool HasInt256 = Subtarget->hasInt256();
7794 MachineFunction &MF = DAG.getMachineFunction();
7795 bool OptForSize = MF.getFunction()->getAttributes().
7796 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7798 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7800 if (V1IsUndef && V2IsUndef)
7801 return DAG.getUNDEF(VT);
7803 // When we create a shuffle node we put the UNDEF node to second operand,
7804 // but in some cases the first operand may be transformed to UNDEF.
7805 // In this case we should just commute the node.
7807 return CommuteVectorShuffle(SVOp, DAG);
7809 // Vector shuffle lowering takes 3 steps:
7811 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7812 // narrowing and commutation of operands should be handled.
7813 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7815 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7816 // so the shuffle can be broken into other shuffles and the legalizer can
7817 // try the lowering again.
7819 // The general idea is that no vector_shuffle operation should be left to
7820 // be matched during isel, all of them must be converted to a target specific
7823 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7824 // narrowing and commutation of operands should be handled. The actual code
7825 // doesn't include all of those, work in progress...
7826 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7827 if (NewOp.getNode())
7830 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7832 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7833 // unpckh_undef). Only use pshufd if speed is more important than size.
7834 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7835 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7836 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7837 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7839 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7840 V2IsUndef && MayFoldVectorLoad(V1))
7841 return getMOVDDup(Op, dl, V1, DAG);
7843 if (isMOVHLPS_v_undef_Mask(M, VT))
7844 return getMOVHighToLow(Op, dl, DAG);
7846 // Use to match splats
7847 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7848 (VT == MVT::v2f64 || VT == MVT::v2i64))
7849 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7851 if (isPSHUFDMask(M, VT)) {
7852 // The actual implementation will match the mask in the if above and then
7853 // during isel it can match several different instructions, not only pshufd
7854 // as its name says, sad but true, emulate the behavior for now...
7855 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7856 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7858 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7860 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7861 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7863 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7864 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7867 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7871 if (isPALIGNRMask(M, VT, Subtarget))
7872 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7873 getShufflePALIGNRImmediate(SVOp),
7876 // Check if this can be converted into a logical shift.
7877 bool isLeft = false;
7880 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7881 if (isShift && ShVal.hasOneUse()) {
7882 // If the shifted value has multiple uses, it may be cheaper to use
7883 // v_set0 + movlhps or movhlps, etc.
7884 MVT EltVT = VT.getVectorElementType();
7885 ShAmt *= EltVT.getSizeInBits();
7886 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7889 if (isMOVLMask(M, VT)) {
7890 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7891 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7892 if (!isMOVLPMask(M, VT)) {
7893 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7894 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7896 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7897 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7901 // FIXME: fold these into legal mask.
7902 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7903 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7905 if (isMOVHLPSMask(M, VT))
7906 return getMOVHighToLow(Op, dl, DAG);
7908 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7909 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7911 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7912 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7914 if (isMOVLPMask(M, VT))
7915 return getMOVLP(Op, dl, DAG, HasSSE2);
7917 if (ShouldXformToMOVHLPS(M, VT) ||
7918 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7919 return CommuteVectorShuffle(SVOp, DAG);
7922 // No better options. Use a vshldq / vsrldq.
7923 MVT EltVT = VT.getVectorElementType();
7924 ShAmt *= EltVT.getSizeInBits();
7925 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7928 bool Commuted = false;
7929 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7930 // 1,1,1,1 -> v8i16 though.
7931 V1IsSplat = isSplatVector(V1.getNode());
7932 V2IsSplat = isSplatVector(V2.getNode());
7934 // Canonicalize the splat or undef, if present, to be on the RHS.
7935 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7936 CommuteVectorShuffleMask(M, NumElems);
7938 std::swap(V1IsSplat, V2IsSplat);
7942 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7943 // Shuffling low element of v1 into undef, just return v1.
7946 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7947 // the instruction selector will not match, so get a canonical MOVL with
7948 // swapped operands to undo the commute.
7949 return getMOVL(DAG, dl, VT, V2, V1);
7952 if (isUNPCKLMask(M, VT, HasInt256))
7953 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7955 if (isUNPCKHMask(M, VT, HasInt256))
7956 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7959 // Normalize mask so all entries that point to V2 points to its first
7960 // element then try to match unpck{h|l} again. If match, return a
7961 // new vector_shuffle with the corrected mask.p
7962 SmallVector<int, 8> NewMask(M.begin(), M.end());
7963 NormalizeMask(NewMask, NumElems);
7964 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7965 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7966 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7967 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7971 // Commute is back and try unpck* again.
7972 // FIXME: this seems wrong.
7973 CommuteVectorShuffleMask(M, NumElems);
7975 std::swap(V1IsSplat, V2IsSplat);
7977 if (isUNPCKLMask(M, VT, HasInt256))
7978 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7980 if (isUNPCKHMask(M, VT, HasInt256))
7981 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7984 // Normalize the node to match x86 shuffle ops if needed
7985 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7986 return CommuteVectorShuffle(SVOp, DAG);
7988 // The checks below are all present in isShuffleMaskLegal, but they are
7989 // inlined here right now to enable us to directly emit target specific
7990 // nodes, and remove one by one until they don't return Op anymore.
7992 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7993 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7994 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7995 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7998 if (isPSHUFHWMask(M, VT, HasInt256))
7999 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
8000 getShufflePSHUFHWImmediate(SVOp),
8003 if (isPSHUFLWMask(M, VT, HasInt256))
8004 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
8005 getShufflePSHUFLWImmediate(SVOp),
8008 if (isSHUFPMask(M, VT))
8009 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
8010 getShuffleSHUFImmediate(SVOp), DAG);
8012 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8013 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8014 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8015 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8017 //===--------------------------------------------------------------------===//
8018 // Generate target specific nodes for 128 or 256-bit shuffles only
8019 // supported in the AVX instruction set.
8022 // Handle VMOVDDUPY permutations
8023 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8024 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8026 // Handle VPERMILPS/D* permutations
8027 if (isVPERMILPMask(M, VT)) {
8028 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8029 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8030 getShuffleSHUFImmediate(SVOp), DAG);
8031 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8032 getShuffleSHUFImmediate(SVOp), DAG);
8036 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8037 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8038 Idx*(NumElems/2), DAG, dl);
8040 // Handle VPERM2F128/VPERM2I128 permutations
8041 if (isVPERM2X128Mask(M, VT, HasFp256))
8042 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8043 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8046 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8048 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8050 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8051 return getINSERTPS(SVOp, dl, DAG);
8054 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8055 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8057 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8058 VT.is512BitVector()) {
8059 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8060 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8061 SmallVector<SDValue, 16> permclMask;
8062 for (unsigned i = 0; i != NumElems; ++i) {
8063 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8066 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8068 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8069 return DAG.getNode(X86ISD::VPERMV, dl, VT,
8070 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8071 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8072 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8075 //===--------------------------------------------------------------------===//
8076 // Since no target specific shuffle was selected for this generic one,
8077 // lower it into other known shuffles. FIXME: this isn't true yet, but
8078 // this is the plan.
8081 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8082 if (VT == MVT::v8i16) {
8083 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8084 if (NewOp.getNode())
8088 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8089 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8090 if (NewOp.getNode())
8094 if (VT == MVT::v16i8) {
8095 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8096 if (NewOp.getNode())
8100 if (VT == MVT::v32i8) {
8101 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8102 if (NewOp.getNode())
8106 // Handle all 128-bit wide vectors with 4 elements, and match them with
8107 // several different shuffle types.
8108 if (NumElems == 4 && VT.is128BitVector())
8109 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8111 // Handle general 256-bit shuffles
8112 if (VT.is256BitVector())
8113 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8118 // This function assumes its argument is a BUILD_VECTOR of constants or
8119 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8121 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8122 unsigned &MaskValue) {
8124 unsigned NumElems = BuildVector->getNumOperands();
8125 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8126 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8127 unsigned NumElemsInLane = NumElems / NumLanes;
8129 // Blend for v16i16 should be symetric for the both lanes.
8130 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8131 SDValue EltCond = BuildVector->getOperand(i);
8132 SDValue SndLaneEltCond =
8133 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8135 int Lane1Cond = -1, Lane2Cond = -1;
8136 if (isa<ConstantSDNode>(EltCond))
8137 Lane1Cond = !isZero(EltCond);
8138 if (isa<ConstantSDNode>(SndLaneEltCond))
8139 Lane2Cond = !isZero(SndLaneEltCond);
8141 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8142 // Lane1Cond != 0, means we want the first argument.
8143 // Lane1Cond == 0, means we want the second argument.
8144 // The encoding of this argument is 0 for the first argument, 1
8145 // for the second. Therefore, invert the condition.
8146 MaskValue |= !Lane1Cond << i;
8147 else if (Lane1Cond < 0)
8148 MaskValue |= !Lane2Cond << i;
8155 // Try to lower a vselect node into a simple blend instruction.
8156 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8157 SelectionDAG &DAG) {
8158 SDValue Cond = Op.getOperand(0);
8159 SDValue LHS = Op.getOperand(1);
8160 SDValue RHS = Op.getOperand(2);
8162 MVT VT = Op.getSimpleValueType();
8163 MVT EltVT = VT.getVectorElementType();
8164 unsigned NumElems = VT.getVectorNumElements();
8166 // There is no blend with immediate in AVX-512.
8167 if (VT.is512BitVector())
8170 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8172 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8175 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8178 // Check the mask for BLEND and build the value.
8179 unsigned MaskValue = 0;
8180 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8183 // Convert i32 vectors to floating point if it is not AVX2.
8184 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8186 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8187 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8189 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8190 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8193 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8194 DAG.getConstant(MaskValue, MVT::i32));
8195 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8198 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8199 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8200 if (BlendOp.getNode())
8203 // Some types for vselect were previously set to Expand, not Legal or
8204 // Custom. Return an empty SDValue so we fall-through to Expand, after
8205 // the Custom lowering phase.
8206 MVT VT = Op.getSimpleValueType();
8207 switch (VT.SimpleTy) {
8215 // We couldn't create a "Blend with immediate" node.
8216 // This node should still be legal, but we'll have to emit a blendv*
8221 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8222 MVT VT = Op.getSimpleValueType();
8225 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8228 if (VT.getSizeInBits() == 8) {
8229 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8230 Op.getOperand(0), Op.getOperand(1));
8231 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8232 DAG.getValueType(VT));
8233 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8236 if (VT.getSizeInBits() == 16) {
8237 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8238 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8240 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8241 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8242 DAG.getNode(ISD::BITCAST, dl,
8246 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8247 Op.getOperand(0), Op.getOperand(1));
8248 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8249 DAG.getValueType(VT));
8250 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8253 if (VT == MVT::f32) {
8254 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8255 // the result back to FR32 register. It's only worth matching if the
8256 // result has a single use which is a store or a bitcast to i32. And in
8257 // the case of a store, it's not worth it if the index is a constant 0,
8258 // because a MOVSSmr can be used instead, which is smaller and faster.
8259 if (!Op.hasOneUse())
8261 SDNode *User = *Op.getNode()->use_begin();
8262 if ((User->getOpcode() != ISD::STORE ||
8263 (isa<ConstantSDNode>(Op.getOperand(1)) &&
8264 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8265 (User->getOpcode() != ISD::BITCAST ||
8266 User->getValueType(0) != MVT::i32))
8268 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8269 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8272 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8275 if (VT == MVT::i32 || VT == MVT::i64) {
8276 // ExtractPS/pextrq works with constant index.
8277 if (isa<ConstantSDNode>(Op.getOperand(1)))
8283 /// Extract one bit from mask vector, like v16i1 or v8i1.
8284 /// AVX-512 feature.
8286 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8287 SDValue Vec = Op.getOperand(0);
8289 MVT VecVT = Vec.getSimpleValueType();
8290 SDValue Idx = Op.getOperand(1);
8291 MVT EltVT = Op.getSimpleValueType();
8293 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8295 // variable index can't be handled in mask registers,
8296 // extend vector to VR512
8297 if (!isa<ConstantSDNode>(Idx)) {
8298 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8299 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8300 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8301 ExtVT.getVectorElementType(), Ext, Idx);
8302 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8305 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8306 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8307 unsigned MaxSift = rc->getSize()*8 - 1;
8308 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8309 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8310 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8311 DAG.getConstant(MaxSift, MVT::i8));
8312 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8313 DAG.getIntPtrConstant(0));
8317 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8318 SelectionDAG &DAG) const {
8320 SDValue Vec = Op.getOperand(0);
8321 MVT VecVT = Vec.getSimpleValueType();
8322 SDValue Idx = Op.getOperand(1);
8324 if (Op.getSimpleValueType() == MVT::i1)
8325 return ExtractBitFromMaskVector(Op, DAG);
8327 if (!isa<ConstantSDNode>(Idx)) {
8328 if (VecVT.is512BitVector() ||
8329 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8330 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8333 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8334 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8335 MaskEltVT.getSizeInBits());
8337 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8338 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8339 getZeroVector(MaskVT, Subtarget, DAG, dl),
8340 Idx, DAG.getConstant(0, getPointerTy()));
8341 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8342 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8343 Perm, DAG.getConstant(0, getPointerTy()));
8348 // If this is a 256-bit vector result, first extract the 128-bit vector and
8349 // then extract the element from the 128-bit vector.
8350 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8352 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8353 // Get the 128-bit vector.
8354 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8355 MVT EltVT = VecVT.getVectorElementType();
8357 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8359 //if (IdxVal >= NumElems/2)
8360 // IdxVal -= NumElems/2;
8361 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8362 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8363 DAG.getConstant(IdxVal, MVT::i32));
8366 assert(VecVT.is128BitVector() && "Unexpected vector length");
8368 if (Subtarget->hasSSE41()) {
8369 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8374 MVT VT = Op.getSimpleValueType();
8375 // TODO: handle v16i8.
8376 if (VT.getSizeInBits() == 16) {
8377 SDValue Vec = Op.getOperand(0);
8378 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8380 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8381 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8382 DAG.getNode(ISD::BITCAST, dl,
8385 // Transform it so it match pextrw which produces a 32-bit result.
8386 MVT EltVT = MVT::i32;
8387 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8388 Op.getOperand(0), Op.getOperand(1));
8389 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8390 DAG.getValueType(VT));
8391 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8394 if (VT.getSizeInBits() == 32) {
8395 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8399 // SHUFPS the element to the lowest double word, then movss.
8400 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8401 MVT VVT = Op.getOperand(0).getSimpleValueType();
8402 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8403 DAG.getUNDEF(VVT), Mask);
8404 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8405 DAG.getIntPtrConstant(0));
8408 if (VT.getSizeInBits() == 64) {
8409 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8410 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8411 // to match extract_elt for f64.
8412 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8416 // UNPCKHPD the element to the lowest double word, then movsd.
8417 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8418 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8419 int Mask[2] = { 1, -1 };
8420 MVT VVT = Op.getOperand(0).getSimpleValueType();
8421 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8422 DAG.getUNDEF(VVT), Mask);
8423 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8424 DAG.getIntPtrConstant(0));
8430 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8431 MVT VT = Op.getSimpleValueType();
8432 MVT EltVT = VT.getVectorElementType();
8435 SDValue N0 = Op.getOperand(0);
8436 SDValue N1 = Op.getOperand(1);
8437 SDValue N2 = Op.getOperand(2);
8439 if (!VT.is128BitVector())
8442 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8443 isa<ConstantSDNode>(N2)) {
8445 if (VT == MVT::v8i16)
8446 Opc = X86ISD::PINSRW;
8447 else if (VT == MVT::v16i8)
8448 Opc = X86ISD::PINSRB;
8450 Opc = X86ISD::PINSRB;
8452 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8454 if (N1.getValueType() != MVT::i32)
8455 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8456 if (N2.getValueType() != MVT::i32)
8457 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8458 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8461 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8462 // Bits [7:6] of the constant are the source select. This will always be
8463 // zero here. The DAG Combiner may combine an extract_elt index into these
8464 // bits. For example (insert (extract, 3), 2) could be matched by putting
8465 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8466 // Bits [5:4] of the constant are the destination select. This is the
8467 // value of the incoming immediate.
8468 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8469 // combine either bitwise AND or insert of float 0.0 to set these bits.
8470 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8471 // Create this as a scalar to vector..
8472 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8473 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8476 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8477 // PINSR* works with constant index.
8483 /// Insert one bit to mask vector, like v16i1 or v8i1.
8484 /// AVX-512 feature.
8486 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8488 SDValue Vec = Op.getOperand(0);
8489 SDValue Elt = Op.getOperand(1);
8490 SDValue Idx = Op.getOperand(2);
8491 MVT VecVT = Vec.getSimpleValueType();
8493 if (!isa<ConstantSDNode>(Idx)) {
8494 // Non constant index. Extend source and destination,
8495 // insert element and then truncate the result.
8496 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8497 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8498 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8499 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8500 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8501 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8504 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8505 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8506 if (Vec.getOpcode() == ISD::UNDEF)
8507 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8508 DAG.getConstant(IdxVal, MVT::i8));
8509 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8510 unsigned MaxSift = rc->getSize()*8 - 1;
8511 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8512 DAG.getConstant(MaxSift, MVT::i8));
8513 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8514 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8515 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8518 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8519 MVT VT = Op.getSimpleValueType();
8520 MVT EltVT = VT.getVectorElementType();
8522 if (EltVT == MVT::i1)
8523 return InsertBitToMaskVector(Op, DAG);
8526 SDValue N0 = Op.getOperand(0);
8527 SDValue N1 = Op.getOperand(1);
8528 SDValue N2 = Op.getOperand(2);
8530 // If this is a 256-bit vector result, first extract the 128-bit vector,
8531 // insert the element into the extracted half and then place it back.
8532 if (VT.is256BitVector() || VT.is512BitVector()) {
8533 if (!isa<ConstantSDNode>(N2))
8536 // Get the desired 128-bit vector half.
8537 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8538 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8540 // Insert the element into the desired half.
8541 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8542 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8544 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8545 DAG.getConstant(IdxIn128, MVT::i32));
8547 // Insert the changed part back to the 256-bit vector
8548 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8551 if (Subtarget->hasSSE41())
8552 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8554 if (EltVT == MVT::i8)
8557 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8558 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8559 // as its second argument.
8560 if (N1.getValueType() != MVT::i32)
8561 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8562 if (N2.getValueType() != MVT::i32)
8563 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8564 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8569 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8571 MVT OpVT = Op.getSimpleValueType();
8573 // If this is a 256-bit vector result, first insert into a 128-bit
8574 // vector and then insert into the 256-bit vector.
8575 if (!OpVT.is128BitVector()) {
8576 // Insert into a 128-bit vector.
8577 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8578 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8579 OpVT.getVectorNumElements() / SizeFactor);
8581 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8583 // Insert the 128-bit vector.
8584 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8587 if (OpVT == MVT::v1i64 &&
8588 Op.getOperand(0).getValueType() == MVT::i64)
8589 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8591 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8592 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8593 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8594 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8597 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8598 // a simple subregister reference or explicit instructions to grab
8599 // upper bits of a vector.
8600 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8601 SelectionDAG &DAG) {
8603 SDValue In = Op.getOperand(0);
8604 SDValue Idx = Op.getOperand(1);
8605 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8606 MVT ResVT = Op.getSimpleValueType();
8607 MVT InVT = In.getSimpleValueType();
8609 if (Subtarget->hasFp256()) {
8610 if (ResVT.is128BitVector() &&
8611 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8612 isa<ConstantSDNode>(Idx)) {
8613 return Extract128BitVector(In, IdxVal, DAG, dl);
8615 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8616 isa<ConstantSDNode>(Idx)) {
8617 return Extract256BitVector(In, IdxVal, DAG, dl);
8623 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8624 // simple superregister reference or explicit instructions to insert
8625 // the upper bits of a vector.
8626 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8627 SelectionDAG &DAG) {
8628 if (Subtarget->hasFp256()) {
8629 SDLoc dl(Op.getNode());
8630 SDValue Vec = Op.getNode()->getOperand(0);
8631 SDValue SubVec = Op.getNode()->getOperand(1);
8632 SDValue Idx = Op.getNode()->getOperand(2);
8634 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8635 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8636 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8637 isa<ConstantSDNode>(Idx)) {
8638 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8639 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8642 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8643 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8644 isa<ConstantSDNode>(Idx)) {
8645 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8646 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8652 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8653 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8654 // one of the above mentioned nodes. It has to be wrapped because otherwise
8655 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8656 // be used to form addressing mode. These wrapped nodes will be selected
8659 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8660 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8662 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8664 unsigned char OpFlag = 0;
8665 unsigned WrapperKind = X86ISD::Wrapper;
8666 CodeModel::Model M = getTargetMachine().getCodeModel();
8668 if (Subtarget->isPICStyleRIPRel() &&
8669 (M == CodeModel::Small || M == CodeModel::Kernel))
8670 WrapperKind = X86ISD::WrapperRIP;
8671 else if (Subtarget->isPICStyleGOT())
8672 OpFlag = X86II::MO_GOTOFF;
8673 else if (Subtarget->isPICStyleStubPIC())
8674 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8676 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8678 CP->getOffset(), OpFlag);
8680 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8681 // With PIC, the address is actually $g + Offset.
8683 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8684 DAG.getNode(X86ISD::GlobalBaseReg,
8685 SDLoc(), getPointerTy()),
8692 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8693 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8695 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8697 unsigned char OpFlag = 0;
8698 unsigned WrapperKind = X86ISD::Wrapper;
8699 CodeModel::Model M = getTargetMachine().getCodeModel();
8701 if (Subtarget->isPICStyleRIPRel() &&
8702 (M == CodeModel::Small || M == CodeModel::Kernel))
8703 WrapperKind = X86ISD::WrapperRIP;
8704 else if (Subtarget->isPICStyleGOT())
8705 OpFlag = X86II::MO_GOTOFF;
8706 else if (Subtarget->isPICStyleStubPIC())
8707 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8709 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8712 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8714 // With PIC, the address is actually $g + Offset.
8716 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8717 DAG.getNode(X86ISD::GlobalBaseReg,
8718 SDLoc(), getPointerTy()),
8725 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8726 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8728 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8730 unsigned char OpFlag = 0;
8731 unsigned WrapperKind = X86ISD::Wrapper;
8732 CodeModel::Model M = getTargetMachine().getCodeModel();
8734 if (Subtarget->isPICStyleRIPRel() &&
8735 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8736 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8737 OpFlag = X86II::MO_GOTPCREL;
8738 WrapperKind = X86ISD::WrapperRIP;
8739 } else if (Subtarget->isPICStyleGOT()) {
8740 OpFlag = X86II::MO_GOT;
8741 } else if (Subtarget->isPICStyleStubPIC()) {
8742 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8743 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8744 OpFlag = X86II::MO_DARWIN_NONLAZY;
8747 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8750 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8752 // With PIC, the address is actually $g + Offset.
8753 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8754 !Subtarget->is64Bit()) {
8755 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8756 DAG.getNode(X86ISD::GlobalBaseReg,
8757 SDLoc(), getPointerTy()),
8761 // For symbols that require a load from a stub to get the address, emit the
8763 if (isGlobalStubReference(OpFlag))
8764 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8765 MachinePointerInfo::getGOT(), false, false, false, 0);
8771 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8772 // Create the TargetBlockAddressAddress node.
8773 unsigned char OpFlags =
8774 Subtarget->ClassifyBlockAddressReference();
8775 CodeModel::Model M = getTargetMachine().getCodeModel();
8776 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8777 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8779 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8782 if (Subtarget->isPICStyleRIPRel() &&
8783 (M == CodeModel::Small || M == CodeModel::Kernel))
8784 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8786 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8788 // With PIC, the address is actually $g + Offset.
8789 if (isGlobalRelativeToPICBase(OpFlags)) {
8790 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8791 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8799 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8800 int64_t Offset, SelectionDAG &DAG) const {
8801 // Create the TargetGlobalAddress node, folding in the constant
8802 // offset if it is legal.
8803 unsigned char OpFlags =
8804 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8805 CodeModel::Model M = getTargetMachine().getCodeModel();
8807 if (OpFlags == X86II::MO_NO_FLAG &&
8808 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8809 // A direct static reference to a global.
8810 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8813 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8816 if (Subtarget->isPICStyleRIPRel() &&
8817 (M == CodeModel::Small || M == CodeModel::Kernel))
8818 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8820 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8822 // With PIC, the address is actually $g + Offset.
8823 if (isGlobalRelativeToPICBase(OpFlags)) {
8824 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8825 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8829 // For globals that require a load from a stub to get the address, emit the
8831 if (isGlobalStubReference(OpFlags))
8832 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8833 MachinePointerInfo::getGOT(), false, false, false, 0);
8835 // If there was a non-zero offset that we didn't fold, create an explicit
8838 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8839 DAG.getConstant(Offset, getPointerTy()));
8845 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8846 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8847 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8848 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8852 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8853 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8854 unsigned char OperandFlags, bool LocalDynamic = false) {
8855 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8856 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8858 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8859 GA->getValueType(0),
8863 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8867 SDValue Ops[] = { Chain, TGA, *InFlag };
8868 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8870 SDValue Ops[] = { Chain, TGA };
8871 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8874 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8875 MFI->setAdjustsStack(true);
8877 SDValue Flag = Chain.getValue(1);
8878 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8881 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8883 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8886 SDLoc dl(GA); // ? function entry point might be better
8887 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8888 DAG.getNode(X86ISD::GlobalBaseReg,
8889 SDLoc(), PtrVT), InFlag);
8890 InFlag = Chain.getValue(1);
8892 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8895 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8897 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8899 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8900 X86::RAX, X86II::MO_TLSGD);
8903 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8909 // Get the start address of the TLS block for this module.
8910 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8911 .getInfo<X86MachineFunctionInfo>();
8912 MFI->incNumLocalDynamicTLSAccesses();
8916 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8917 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8920 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8921 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8922 InFlag = Chain.getValue(1);
8923 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8924 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8927 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8931 unsigned char OperandFlags = X86II::MO_DTPOFF;
8932 unsigned WrapperKind = X86ISD::Wrapper;
8933 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8934 GA->getValueType(0),
8935 GA->getOffset(), OperandFlags);
8936 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8938 // Add x@dtpoff with the base.
8939 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8942 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8943 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8944 const EVT PtrVT, TLSModel::Model model,
8945 bool is64Bit, bool isPIC) {
8948 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8949 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8950 is64Bit ? 257 : 256));
8952 SDValue ThreadPointer =
8953 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8954 MachinePointerInfo(Ptr), false, false, false, 0);
8956 unsigned char OperandFlags = 0;
8957 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8959 unsigned WrapperKind = X86ISD::Wrapper;
8960 if (model == TLSModel::LocalExec) {
8961 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8962 } else if (model == TLSModel::InitialExec) {
8964 OperandFlags = X86II::MO_GOTTPOFF;
8965 WrapperKind = X86ISD::WrapperRIP;
8967 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8970 llvm_unreachable("Unexpected model");
8973 // emit "addl x@ntpoff,%eax" (local exec)
8974 // or "addl x@indntpoff,%eax" (initial exec)
8975 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8977 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8978 GA->getOffset(), OperandFlags);
8979 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8981 if (model == TLSModel::InitialExec) {
8982 if (isPIC && !is64Bit) {
8983 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8984 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8988 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8989 MachinePointerInfo::getGOT(), false, false, false, 0);
8992 // The address of the thread local variable is the add of the thread
8993 // pointer with the offset of the variable.
8994 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8998 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
9000 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
9001 const GlobalValue *GV = GA->getGlobal();
9003 if (Subtarget->isTargetELF()) {
9004 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
9007 case TLSModel::GeneralDynamic:
9008 if (Subtarget->is64Bit())
9009 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
9010 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
9011 case TLSModel::LocalDynamic:
9012 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
9013 Subtarget->is64Bit());
9014 case TLSModel::InitialExec:
9015 case TLSModel::LocalExec:
9016 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
9017 Subtarget->is64Bit(),
9018 getTargetMachine().getRelocationModel() == Reloc::PIC_);
9020 llvm_unreachable("Unknown TLS model.");
9023 if (Subtarget->isTargetDarwin()) {
9024 // Darwin only has one model of TLS. Lower to that.
9025 unsigned char OpFlag = 0;
9026 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9027 X86ISD::WrapperRIP : X86ISD::Wrapper;
9029 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9031 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
9032 !Subtarget->is64Bit();
9034 OpFlag = X86II::MO_TLVP_PIC_BASE;
9036 OpFlag = X86II::MO_TLVP;
9038 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9039 GA->getValueType(0),
9040 GA->getOffset(), OpFlag);
9041 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9043 // With PIC32, the address is actually $g + Offset.
9045 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9046 DAG.getNode(X86ISD::GlobalBaseReg,
9047 SDLoc(), getPointerTy()),
9050 // Lowering the machine isd will make sure everything is in the right
9052 SDValue Chain = DAG.getEntryNode();
9053 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9054 SDValue Args[] = { Chain, Offset };
9055 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9057 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9058 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9059 MFI->setAdjustsStack(true);
9061 // And our return value (tls address) is in the standard call return value
9063 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9064 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9068 if (Subtarget->isTargetKnownWindowsMSVC() ||
9069 Subtarget->isTargetWindowsGNU()) {
9070 // Just use the implicit TLS architecture
9071 // Need to generate someting similar to:
9072 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9074 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
9075 // mov rcx, qword [rdx+rcx*8]
9076 // mov eax, .tls$:tlsvar
9077 // [rax+rcx] contains the address
9078 // Windows 64bit: gs:0x58
9079 // Windows 32bit: fs:__tls_array
9082 SDValue Chain = DAG.getEntryNode();
9084 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9085 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9086 // use its literal value of 0x2C.
9087 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9088 ? Type::getInt8PtrTy(*DAG.getContext(),
9090 : Type::getInt32PtrTy(*DAG.getContext(),
9094 Subtarget->is64Bit()
9095 ? DAG.getIntPtrConstant(0x58)
9096 : (Subtarget->isTargetWindowsGNU()
9097 ? DAG.getIntPtrConstant(0x2C)
9098 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9100 SDValue ThreadPointer =
9101 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9102 MachinePointerInfo(Ptr), false, false, false, 0);
9104 // Load the _tls_index variable
9105 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9106 if (Subtarget->is64Bit())
9107 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9108 IDX, MachinePointerInfo(), MVT::i32,
9111 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9112 false, false, false, 0);
9114 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9116 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9118 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9119 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9120 false, false, false, 0);
9122 // Get the offset of start of .tls section
9123 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9124 GA->getValueType(0),
9125 GA->getOffset(), X86II::MO_SECREL);
9126 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9128 // The address of the thread local variable is the add of the thread
9129 // pointer with the offset of the variable.
9130 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9133 llvm_unreachable("TLS not implemented for this target.");
9136 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9137 /// and take a 2 x i32 value to shift plus a shift amount.
9138 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9139 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9140 MVT VT = Op.getSimpleValueType();
9141 unsigned VTBits = VT.getSizeInBits();
9143 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9144 SDValue ShOpLo = Op.getOperand(0);
9145 SDValue ShOpHi = Op.getOperand(1);
9146 SDValue ShAmt = Op.getOperand(2);
9147 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9148 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9150 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9151 DAG.getConstant(VTBits - 1, MVT::i8));
9152 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9153 DAG.getConstant(VTBits - 1, MVT::i8))
9154 : DAG.getConstant(0, VT);
9157 if (Op.getOpcode() == ISD::SHL_PARTS) {
9158 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9159 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9161 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9162 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9165 // If the shift amount is larger or equal than the width of a part we can't
9166 // rely on the results of shld/shrd. Insert a test and select the appropriate
9167 // values for large shift amounts.
9168 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9169 DAG.getConstant(VTBits, MVT::i8));
9170 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9171 AndNode, DAG.getConstant(0, MVT::i8));
9174 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9175 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9176 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9178 if (Op.getOpcode() == ISD::SHL_PARTS) {
9179 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9180 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9182 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9183 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9186 SDValue Ops[2] = { Lo, Hi };
9187 return DAG.getMergeValues(Ops, dl);
9190 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9191 SelectionDAG &DAG) const {
9192 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9194 if (SrcVT.isVector())
9197 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9198 "Unknown SINT_TO_FP to lower!");
9200 // These are really Legal; return the operand so the caller accepts it as
9202 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9204 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9205 Subtarget->is64Bit()) {
9210 unsigned Size = SrcVT.getSizeInBits()/8;
9211 MachineFunction &MF = DAG.getMachineFunction();
9212 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9213 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9214 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9216 MachinePointerInfo::getFixedStack(SSFI),
9218 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9221 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9223 SelectionDAG &DAG) const {
9227 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9229 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9231 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9233 unsigned ByteSize = SrcVT.getSizeInBits()/8;
9235 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9236 MachineMemOperand *MMO;
9238 int SSFI = FI->getIndex();
9240 DAG.getMachineFunction()
9241 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9242 MachineMemOperand::MOLoad, ByteSize, ByteSize);
9244 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9245 StackSlot = StackSlot.getOperand(1);
9247 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9248 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9250 Tys, Ops, SrcVT, MMO);
9253 Chain = Result.getValue(1);
9254 SDValue InFlag = Result.getValue(2);
9256 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9257 // shouldn't be necessary except that RFP cannot be live across
9258 // multiple blocks. When stackifier is fixed, they can be uncoupled.
9259 MachineFunction &MF = DAG.getMachineFunction();
9260 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9261 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9262 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9263 Tys = DAG.getVTList(MVT::Other);
9265 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9267 MachineMemOperand *MMO =
9268 DAG.getMachineFunction()
9269 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9270 MachineMemOperand::MOStore, SSFISize, SSFISize);
9272 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9273 Ops, Op.getValueType(), MMO);
9274 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9275 MachinePointerInfo::getFixedStack(SSFI),
9276 false, false, false, 0);
9282 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9283 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9284 SelectionDAG &DAG) const {
9285 // This algorithm is not obvious. Here it is what we're trying to output:
9288 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9289 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9293 pshufd $0x4e, %xmm0, %xmm1
9299 LLVMContext *Context = DAG.getContext();
9301 // Build some magic constants.
9302 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9303 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9304 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9306 SmallVector<Constant*,2> CV1;
9308 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9309 APInt(64, 0x4330000000000000ULL))));
9311 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9312 APInt(64, 0x4530000000000000ULL))));
9313 Constant *C1 = ConstantVector::get(CV1);
9314 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9316 // Load the 64-bit value into an XMM register.
9317 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9319 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9320 MachinePointerInfo::getConstantPool(),
9321 false, false, false, 16);
9322 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9323 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9326 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9327 MachinePointerInfo::getConstantPool(),
9328 false, false, false, 16);
9329 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9330 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9333 if (Subtarget->hasSSE3()) {
9334 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9335 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9337 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9338 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9340 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9341 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9345 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9346 DAG.getIntPtrConstant(0));
9349 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9350 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9351 SelectionDAG &DAG) const {
9353 // FP constant to bias correct the final result.
9354 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9357 // Load the 32-bit value into an XMM register.
9358 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9361 // Zero out the upper parts of the register.
9362 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9364 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9365 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9366 DAG.getIntPtrConstant(0));
9368 // Or the load with the bias.
9369 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9370 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9371 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9373 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9374 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9375 MVT::v2f64, Bias)));
9376 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9377 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9378 DAG.getIntPtrConstant(0));
9380 // Subtract the bias.
9381 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9383 // Handle final rounding.
9384 EVT DestVT = Op.getValueType();
9386 if (DestVT.bitsLT(MVT::f64))
9387 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9388 DAG.getIntPtrConstant(0));
9389 if (DestVT.bitsGT(MVT::f64))
9390 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9392 // Handle final rounding.
9396 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9397 SelectionDAG &DAG) const {
9398 SDValue N0 = Op.getOperand(0);
9399 MVT SVT = N0.getSimpleValueType();
9402 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9403 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9404 "Custom UINT_TO_FP is not supported!");
9406 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9407 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9408 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9411 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9412 SelectionDAG &DAG) const {
9413 SDValue N0 = Op.getOperand(0);
9416 if (Op.getValueType().isVector())
9417 return lowerUINT_TO_FP_vec(Op, DAG);
9419 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9420 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9421 // the optimization here.
9422 if (DAG.SignBitIsZero(N0))
9423 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9425 MVT SrcVT = N0.getSimpleValueType();
9426 MVT DstVT = Op.getSimpleValueType();
9427 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9428 return LowerUINT_TO_FP_i64(Op, DAG);
9429 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9430 return LowerUINT_TO_FP_i32(Op, DAG);
9431 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9434 // Make a 64-bit buffer, and use it to build an FILD.
9435 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9436 if (SrcVT == MVT::i32) {
9437 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9438 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9439 getPointerTy(), StackSlot, WordOff);
9440 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9441 StackSlot, MachinePointerInfo(),
9443 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9444 OffsetSlot, MachinePointerInfo(),
9446 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9450 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9451 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9452 StackSlot, MachinePointerInfo(),
9454 // For i64 source, we need to add the appropriate power of 2 if the input
9455 // was negative. This is the same as the optimization in
9456 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9457 // we must be careful to do the computation in x87 extended precision, not
9458 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9459 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9460 MachineMemOperand *MMO =
9461 DAG.getMachineFunction()
9462 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9463 MachineMemOperand::MOLoad, 8, 8);
9465 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9466 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9467 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9470 APInt FF(32, 0x5F800000ULL);
9472 // Check whether the sign bit is set.
9473 SDValue SignSet = DAG.getSetCC(dl,
9474 getSetCCResultType(*DAG.getContext(), MVT::i64),
9475 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9478 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9479 SDValue FudgePtr = DAG.getConstantPool(
9480 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9483 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9484 SDValue Zero = DAG.getIntPtrConstant(0);
9485 SDValue Four = DAG.getIntPtrConstant(4);
9486 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9488 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9490 // Load the value out, extending it from f32 to f80.
9491 // FIXME: Avoid the extend by constructing the right constant pool?
9492 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9493 FudgePtr, MachinePointerInfo::getConstantPool(),
9494 MVT::f32, false, false, 4);
9495 // Extend everything to 80 bits to force it to be done on x87.
9496 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9497 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9500 std::pair<SDValue,SDValue>
9501 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9502 bool IsSigned, bool IsReplace) const {
9505 EVT DstTy = Op.getValueType();
9507 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9508 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9512 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9513 DstTy.getSimpleVT() >= MVT::i16 &&
9514 "Unknown FP_TO_INT to lower!");
9516 // These are really Legal.
9517 if (DstTy == MVT::i32 &&
9518 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9519 return std::make_pair(SDValue(), SDValue());
9520 if (Subtarget->is64Bit() &&
9521 DstTy == MVT::i64 &&
9522 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9523 return std::make_pair(SDValue(), SDValue());
9525 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9526 // stack slot, or into the FTOL runtime function.
9527 MachineFunction &MF = DAG.getMachineFunction();
9528 unsigned MemSize = DstTy.getSizeInBits()/8;
9529 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9530 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9533 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9534 Opc = X86ISD::WIN_FTOL;
9536 switch (DstTy.getSimpleVT().SimpleTy) {
9537 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9538 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9539 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9540 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9543 SDValue Chain = DAG.getEntryNode();
9544 SDValue Value = Op.getOperand(0);
9545 EVT TheVT = Op.getOperand(0).getValueType();
9546 // FIXME This causes a redundant load/store if the SSE-class value is already
9547 // in memory, such as if it is on the callstack.
9548 if (isScalarFPTypeInSSEReg(TheVT)) {
9549 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9550 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9551 MachinePointerInfo::getFixedStack(SSFI),
9553 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9555 Chain, StackSlot, DAG.getValueType(TheVT)
9558 MachineMemOperand *MMO =
9559 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9560 MachineMemOperand::MOLoad, MemSize, MemSize);
9561 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9562 Chain = Value.getValue(1);
9563 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9564 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9567 MachineMemOperand *MMO =
9568 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9569 MachineMemOperand::MOStore, MemSize, MemSize);
9571 if (Opc != X86ISD::WIN_FTOL) {
9572 // Build the FP_TO_INT*_IN_MEM
9573 SDValue Ops[] = { Chain, Value, StackSlot };
9574 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9576 return std::make_pair(FIST, StackSlot);
9578 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9579 DAG.getVTList(MVT::Other, MVT::Glue),
9581 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9582 MVT::i32, ftol.getValue(1));
9583 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9584 MVT::i32, eax.getValue(2));
9585 SDValue Ops[] = { eax, edx };
9586 SDValue pair = IsReplace
9587 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9588 : DAG.getMergeValues(Ops, DL);
9589 return std::make_pair(pair, SDValue());
9593 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9594 const X86Subtarget *Subtarget) {
9595 MVT VT = Op->getSimpleValueType(0);
9596 SDValue In = Op->getOperand(0);
9597 MVT InVT = In.getSimpleValueType();
9600 // Optimize vectors in AVX mode:
9603 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9604 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9605 // Concat upper and lower parts.
9608 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9609 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9610 // Concat upper and lower parts.
9613 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9614 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9615 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9618 if (Subtarget->hasInt256())
9619 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9621 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9622 SDValue Undef = DAG.getUNDEF(InVT);
9623 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9624 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9625 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9627 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9628 VT.getVectorNumElements()/2);
9630 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9631 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9633 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9636 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9637 SelectionDAG &DAG) {
9638 MVT VT = Op->getSimpleValueType(0);
9639 SDValue In = Op->getOperand(0);
9640 MVT InVT = In.getSimpleValueType();
9642 unsigned int NumElts = VT.getVectorNumElements();
9643 if (NumElts != 8 && NumElts != 16)
9646 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9647 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9649 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9650 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9651 // Now we have only mask extension
9652 assert(InVT.getVectorElementType() == MVT::i1);
9653 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9654 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9655 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9656 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9657 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9658 MachinePointerInfo::getConstantPool(),
9659 false, false, false, Alignment);
9661 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9662 if (VT.is512BitVector())
9664 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9667 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9668 SelectionDAG &DAG) {
9669 if (Subtarget->hasFp256()) {
9670 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9678 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9679 SelectionDAG &DAG) {
9681 MVT VT = Op.getSimpleValueType();
9682 SDValue In = Op.getOperand(0);
9683 MVT SVT = In.getSimpleValueType();
9685 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9686 return LowerZERO_EXTEND_AVX512(Op, DAG);
9688 if (Subtarget->hasFp256()) {
9689 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9694 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9695 VT.getVectorNumElements() != SVT.getVectorNumElements());
9699 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9701 MVT VT = Op.getSimpleValueType();
9702 SDValue In = Op.getOperand(0);
9703 MVT InVT = In.getSimpleValueType();
9705 if (VT == MVT::i1) {
9706 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9707 "Invalid scalar TRUNCATE operation");
9708 if (InVT == MVT::i32)
9710 if (InVT.getSizeInBits() == 64)
9711 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9712 else if (InVT.getSizeInBits() < 32)
9713 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9714 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9716 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9717 "Invalid TRUNCATE operation");
9719 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9720 if (VT.getVectorElementType().getSizeInBits() >=8)
9721 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9723 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9724 unsigned NumElts = InVT.getVectorNumElements();
9725 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9726 if (InVT.getSizeInBits() < 512) {
9727 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9728 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9732 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9733 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9734 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9735 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9736 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9737 MachinePointerInfo::getConstantPool(),
9738 false, false, false, Alignment);
9739 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9740 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9741 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9744 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9745 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9746 if (Subtarget->hasInt256()) {
9747 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9748 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9749 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9751 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9752 DAG.getIntPtrConstant(0));
9755 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9756 DAG.getIntPtrConstant(0));
9757 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9758 DAG.getIntPtrConstant(2));
9759 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9760 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9761 static const int ShufMask[] = {0, 2, 4, 6};
9762 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9765 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9766 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9767 if (Subtarget->hasInt256()) {
9768 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9770 SmallVector<SDValue,32> pshufbMask;
9771 for (unsigned i = 0; i < 2; ++i) {
9772 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9773 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9774 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9775 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9776 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9777 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9778 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9779 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9780 for (unsigned j = 0; j < 8; ++j)
9781 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9783 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9784 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9785 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9787 static const int ShufMask[] = {0, 2, -1, -1};
9788 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9790 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9791 DAG.getIntPtrConstant(0));
9792 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9795 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9796 DAG.getIntPtrConstant(0));
9798 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9799 DAG.getIntPtrConstant(4));
9801 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9802 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9805 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9806 -1, -1, -1, -1, -1, -1, -1, -1};
9808 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9809 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9810 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9812 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9813 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9815 // The MOVLHPS Mask:
9816 static const int ShufMask2[] = {0, 1, 4, 5};
9817 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9818 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9821 // Handle truncation of V256 to V128 using shuffles.
9822 if (!VT.is128BitVector() || !InVT.is256BitVector())
9825 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9827 unsigned NumElems = VT.getVectorNumElements();
9828 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9830 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9831 // Prepare truncation shuffle mask
9832 for (unsigned i = 0; i != NumElems; ++i)
9834 SDValue V = DAG.getVectorShuffle(NVT, DL,
9835 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9836 DAG.getUNDEF(NVT), &MaskVec[0]);
9837 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9838 DAG.getIntPtrConstant(0));
9841 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9842 SelectionDAG &DAG) const {
9843 assert(!Op.getSimpleValueType().isVector());
9845 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9846 /*IsSigned=*/ true, /*IsReplace=*/ false);
9847 SDValue FIST = Vals.first, StackSlot = Vals.second;
9848 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9849 if (!FIST.getNode()) return Op;
9851 if (StackSlot.getNode())
9853 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9854 FIST, StackSlot, MachinePointerInfo(),
9855 false, false, false, 0);
9857 // The node is the result.
9861 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9862 SelectionDAG &DAG) const {
9863 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9864 /*IsSigned=*/ false, /*IsReplace=*/ false);
9865 SDValue FIST = Vals.first, StackSlot = Vals.second;
9866 assert(FIST.getNode() && "Unexpected failure");
9868 if (StackSlot.getNode())
9870 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9871 FIST, StackSlot, MachinePointerInfo(),
9872 false, false, false, 0);
9874 // The node is the result.
9878 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9880 MVT VT = Op.getSimpleValueType();
9881 SDValue In = Op.getOperand(0);
9882 MVT SVT = In.getSimpleValueType();
9884 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9886 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9887 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9888 In, DAG.getUNDEF(SVT)));
9891 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9892 LLVMContext *Context = DAG.getContext();
9894 MVT VT = Op.getSimpleValueType();
9896 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9897 if (VT.isVector()) {
9898 EltVT = VT.getVectorElementType();
9899 NumElts = VT.getVectorNumElements();
9902 if (EltVT == MVT::f64)
9903 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9904 APInt(64, ~(1ULL << 63))));
9906 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9907 APInt(32, ~(1U << 31))));
9908 C = ConstantVector::getSplat(NumElts, C);
9909 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9910 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9911 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9912 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9913 MachinePointerInfo::getConstantPool(),
9914 false, false, false, Alignment);
9915 if (VT.isVector()) {
9916 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9917 return DAG.getNode(ISD::BITCAST, dl, VT,
9918 DAG.getNode(ISD::AND, dl, ANDVT,
9919 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9921 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9923 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9926 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9927 LLVMContext *Context = DAG.getContext();
9929 MVT VT = Op.getSimpleValueType();
9931 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9932 if (VT.isVector()) {
9933 EltVT = VT.getVectorElementType();
9934 NumElts = VT.getVectorNumElements();
9937 if (EltVT == MVT::f64)
9938 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9939 APInt(64, 1ULL << 63)));
9941 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9942 APInt(32, 1U << 31)));
9943 C = ConstantVector::getSplat(NumElts, C);
9944 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9945 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9946 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9947 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9948 MachinePointerInfo::getConstantPool(),
9949 false, false, false, Alignment);
9950 if (VT.isVector()) {
9951 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9952 return DAG.getNode(ISD::BITCAST, dl, VT,
9953 DAG.getNode(ISD::XOR, dl, XORVT,
9954 DAG.getNode(ISD::BITCAST, dl, XORVT,
9956 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9959 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9962 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9963 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9964 LLVMContext *Context = DAG.getContext();
9965 SDValue Op0 = Op.getOperand(0);
9966 SDValue Op1 = Op.getOperand(1);
9968 MVT VT = Op.getSimpleValueType();
9969 MVT SrcVT = Op1.getSimpleValueType();
9971 // If second operand is smaller, extend it first.
9972 if (SrcVT.bitsLT(VT)) {
9973 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9976 // And if it is bigger, shrink it first.
9977 if (SrcVT.bitsGT(VT)) {
9978 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9982 // At this point the operands and the result should have the same
9983 // type, and that won't be f80 since that is not custom lowered.
9985 // First get the sign bit of second operand.
9986 SmallVector<Constant*,4> CV;
9987 if (SrcVT == MVT::f64) {
9988 const fltSemantics &Sem = APFloat::IEEEdouble;
9989 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9990 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9992 const fltSemantics &Sem = APFloat::IEEEsingle;
9993 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9994 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9995 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9996 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9998 Constant *C = ConstantVector::get(CV);
9999 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10000 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
10001 MachinePointerInfo::getConstantPool(),
10002 false, false, false, 16);
10003 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
10005 // Shift sign bit right or left if the two operands have different types.
10006 if (SrcVT.bitsGT(VT)) {
10007 // Op0 is MVT::f32, Op1 is MVT::f64.
10008 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
10009 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
10010 DAG.getConstant(32, MVT::i32));
10011 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
10012 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
10013 DAG.getIntPtrConstant(0));
10016 // Clear first operand sign bit.
10018 if (VT == MVT::f64) {
10019 const fltSemantics &Sem = APFloat::IEEEdouble;
10020 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10021 APInt(64, ~(1ULL << 63)))));
10022 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10024 const fltSemantics &Sem = APFloat::IEEEsingle;
10025 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10026 APInt(32, ~(1U << 31)))));
10027 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10028 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10029 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10031 C = ConstantVector::get(CV);
10032 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10033 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10034 MachinePointerInfo::getConstantPool(),
10035 false, false, false, 16);
10036 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10038 // Or the value with the sign bit.
10039 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10042 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10043 SDValue N0 = Op.getOperand(0);
10045 MVT VT = Op.getSimpleValueType();
10047 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10048 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10049 DAG.getConstant(1, VT));
10050 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10053 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10055 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10056 SelectionDAG &DAG) {
10057 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10059 if (!Subtarget->hasSSE41())
10062 if (!Op->hasOneUse())
10065 SDNode *N = Op.getNode();
10068 SmallVector<SDValue, 8> Opnds;
10069 DenseMap<SDValue, unsigned> VecInMap;
10070 SmallVector<SDValue, 8> VecIns;
10071 EVT VT = MVT::Other;
10073 // Recognize a special case where a vector is casted into wide integer to
10075 Opnds.push_back(N->getOperand(0));
10076 Opnds.push_back(N->getOperand(1));
10078 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10079 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10080 // BFS traverse all OR'd operands.
10081 if (I->getOpcode() == ISD::OR) {
10082 Opnds.push_back(I->getOperand(0));
10083 Opnds.push_back(I->getOperand(1));
10084 // Re-evaluate the number of nodes to be traversed.
10085 e += 2; // 2 more nodes (LHS and RHS) are pushed.
10089 // Quit if a non-EXTRACT_VECTOR_ELT
10090 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10093 // Quit if without a constant index.
10094 SDValue Idx = I->getOperand(1);
10095 if (!isa<ConstantSDNode>(Idx))
10098 SDValue ExtractedFromVec = I->getOperand(0);
10099 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10100 if (M == VecInMap.end()) {
10101 VT = ExtractedFromVec.getValueType();
10102 // Quit if not 128/256-bit vector.
10103 if (!VT.is128BitVector() && !VT.is256BitVector())
10105 // Quit if not the same type.
10106 if (VecInMap.begin() != VecInMap.end() &&
10107 VT != VecInMap.begin()->first.getValueType())
10109 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10110 VecIns.push_back(ExtractedFromVec);
10112 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10115 assert((VT.is128BitVector() || VT.is256BitVector()) &&
10116 "Not extracted from 128-/256-bit vector.");
10118 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10120 for (DenseMap<SDValue, unsigned>::const_iterator
10121 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10122 // Quit if not all elements are used.
10123 if (I->second != FullMask)
10127 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10129 // Cast all vectors into TestVT for PTEST.
10130 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10131 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10133 // If more than one full vectors are evaluated, OR them first before PTEST.
10134 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10135 // Each iteration will OR 2 nodes and append the result until there is only
10136 // 1 node left, i.e. the final OR'd value of all vectors.
10137 SDValue LHS = VecIns[Slot];
10138 SDValue RHS = VecIns[Slot + 1];
10139 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10142 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10143 VecIns.back(), VecIns.back());
10146 /// \brief return true if \c Op has a use that doesn't just read flags.
10147 static bool hasNonFlagsUse(SDValue Op) {
10148 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10150 SDNode *User = *UI;
10151 unsigned UOpNo = UI.getOperandNo();
10152 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10153 // Look pass truncate.
10154 UOpNo = User->use_begin().getOperandNo();
10155 User = *User->use_begin();
10158 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10159 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10165 /// Emit nodes that will be selected as "test Op0,Op0", or something
10167 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10168 SelectionDAG &DAG) const {
10169 if (Op.getValueType() == MVT::i1)
10170 // KORTEST instruction should be selected
10171 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10172 DAG.getConstant(0, Op.getValueType()));
10174 // CF and OF aren't always set the way we want. Determine which
10175 // of these we need.
10176 bool NeedCF = false;
10177 bool NeedOF = false;
10180 case X86::COND_A: case X86::COND_AE:
10181 case X86::COND_B: case X86::COND_BE:
10184 case X86::COND_G: case X86::COND_GE:
10185 case X86::COND_L: case X86::COND_LE:
10186 case X86::COND_O: case X86::COND_NO: {
10187 // Check if we really need to set the
10188 // Overflow flag. If NoSignedWrap is present
10189 // that is not actually needed.
10190 switch (Op->getOpcode()) {
10195 const BinaryWithFlagsSDNode *BinNode =
10196 cast<BinaryWithFlagsSDNode>(Op.getNode());
10197 if (BinNode->hasNoSignedWrap())
10207 // See if we can use the EFLAGS value from the operand instead of
10208 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10209 // we prove that the arithmetic won't overflow, we can't use OF or CF.
10210 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10211 // Emit a CMP with 0, which is the TEST pattern.
10212 //if (Op.getValueType() == MVT::i1)
10213 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10214 // DAG.getConstant(0, MVT::i1));
10215 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10216 DAG.getConstant(0, Op.getValueType()));
10218 unsigned Opcode = 0;
10219 unsigned NumOperands = 0;
10221 // Truncate operations may prevent the merge of the SETCC instruction
10222 // and the arithmetic instruction before it. Attempt to truncate the operands
10223 // of the arithmetic instruction and use a reduced bit-width instruction.
10224 bool NeedTruncation = false;
10225 SDValue ArithOp = Op;
10226 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10227 SDValue Arith = Op->getOperand(0);
10228 // Both the trunc and the arithmetic op need to have one user each.
10229 if (Arith->hasOneUse())
10230 switch (Arith.getOpcode()) {
10237 NeedTruncation = true;
10243 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10244 // which may be the result of a CAST. We use the variable 'Op', which is the
10245 // non-casted variable when we check for possible users.
10246 switch (ArithOp.getOpcode()) {
10248 // Due to an isel shortcoming, be conservative if this add is likely to be
10249 // selected as part of a load-modify-store instruction. When the root node
10250 // in a match is a store, isel doesn't know how to remap non-chain non-flag
10251 // uses of other nodes in the match, such as the ADD in this case. This
10252 // leads to the ADD being left around and reselected, with the result being
10253 // two adds in the output. Alas, even if none our users are stores, that
10254 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
10255 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
10256 // climbing the DAG back to the root, and it doesn't seem to be worth the
10258 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10259 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10260 if (UI->getOpcode() != ISD::CopyToReg &&
10261 UI->getOpcode() != ISD::SETCC &&
10262 UI->getOpcode() != ISD::STORE)
10265 if (ConstantSDNode *C =
10266 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10267 // An add of one will be selected as an INC.
10268 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10269 Opcode = X86ISD::INC;
10274 // An add of negative one (subtract of one) will be selected as a DEC.
10275 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10276 Opcode = X86ISD::DEC;
10282 // Otherwise use a regular EFLAGS-setting add.
10283 Opcode = X86ISD::ADD;
10288 // If we have a constant logical shift that's only used in a comparison
10289 // against zero turn it into an equivalent AND. This allows turning it into
10290 // a TEST instruction later.
10291 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10292 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10293 EVT VT = Op.getValueType();
10294 unsigned BitWidth = VT.getSizeInBits();
10295 unsigned ShAmt = Op->getConstantOperandVal(1);
10296 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10298 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10299 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10300 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10301 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10303 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10304 DAG.getConstant(Mask, VT));
10305 DAG.ReplaceAllUsesWith(Op, New);
10311 // If the primary and result isn't used, don't bother using X86ISD::AND,
10312 // because a TEST instruction will be better.
10313 if (!hasNonFlagsUse(Op))
10319 // Due to the ISEL shortcoming noted above, be conservative if this op is
10320 // likely to be selected as part of a load-modify-store instruction.
10321 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10322 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10323 if (UI->getOpcode() == ISD::STORE)
10326 // Otherwise use a regular EFLAGS-setting instruction.
10327 switch (ArithOp.getOpcode()) {
10328 default: llvm_unreachable("unexpected operator!");
10329 case ISD::SUB: Opcode = X86ISD::SUB; break;
10330 case ISD::XOR: Opcode = X86ISD::XOR; break;
10331 case ISD::AND: Opcode = X86ISD::AND; break;
10333 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10334 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10335 if (EFLAGS.getNode())
10338 Opcode = X86ISD::OR;
10352 return SDValue(Op.getNode(), 1);
10358 // If we found that truncation is beneficial, perform the truncation and
10360 if (NeedTruncation) {
10361 EVT VT = Op.getValueType();
10362 SDValue WideVal = Op->getOperand(0);
10363 EVT WideVT = WideVal.getValueType();
10364 unsigned ConvertedOp = 0;
10365 // Use a target machine opcode to prevent further DAGCombine
10366 // optimizations that may separate the arithmetic operations
10367 // from the setcc node.
10368 switch (WideVal.getOpcode()) {
10370 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10371 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10372 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10373 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10374 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10378 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10379 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10380 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10381 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10382 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10388 // Emit a CMP with 0, which is the TEST pattern.
10389 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10390 DAG.getConstant(0, Op.getValueType()));
10392 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10393 SmallVector<SDValue, 4> Ops;
10394 for (unsigned i = 0; i != NumOperands; ++i)
10395 Ops.push_back(Op.getOperand(i));
10397 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10398 DAG.ReplaceAllUsesWith(Op, New);
10399 return SDValue(New.getNode(), 1);
10402 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10404 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10405 SDLoc dl, SelectionDAG &DAG) const {
10406 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10407 if (C->getAPIntValue() == 0)
10408 return EmitTest(Op0, X86CC, dl, DAG);
10410 if (Op0.getValueType() == MVT::i1)
10411 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10414 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10415 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10416 // Do the comparison at i32 if it's smaller, besides the Atom case.
10417 // This avoids subregister aliasing issues. Keep the smaller reference
10418 // if we're optimizing for size, however, as that'll allow better folding
10419 // of memory operations.
10420 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10421 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10422 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10423 !Subtarget->isAtom()) {
10424 unsigned ExtendOp =
10425 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10426 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10427 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10429 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10430 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10431 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10433 return SDValue(Sub.getNode(), 1);
10435 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10438 /// Convert a comparison if required by the subtarget.
10439 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10440 SelectionDAG &DAG) const {
10441 // If the subtarget does not support the FUCOMI instruction, floating-point
10442 // comparisons have to be converted.
10443 if (Subtarget->hasCMov() ||
10444 Cmp.getOpcode() != X86ISD::CMP ||
10445 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10446 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10449 // The instruction selector will select an FUCOM instruction instead of
10450 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10451 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10452 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10454 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10455 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10456 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10457 DAG.getConstant(8, MVT::i8));
10458 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10459 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10462 static bool isAllOnes(SDValue V) {
10463 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10464 return C && C->isAllOnesValue();
10467 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10468 /// if it's possible.
10469 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10470 SDLoc dl, SelectionDAG &DAG) const {
10471 SDValue Op0 = And.getOperand(0);
10472 SDValue Op1 = And.getOperand(1);
10473 if (Op0.getOpcode() == ISD::TRUNCATE)
10474 Op0 = Op0.getOperand(0);
10475 if (Op1.getOpcode() == ISD::TRUNCATE)
10476 Op1 = Op1.getOperand(0);
10479 if (Op1.getOpcode() == ISD::SHL)
10480 std::swap(Op0, Op1);
10481 if (Op0.getOpcode() == ISD::SHL) {
10482 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10483 if (And00C->getZExtValue() == 1) {
10484 // If we looked past a truncate, check that it's only truncating away
10486 unsigned BitWidth = Op0.getValueSizeInBits();
10487 unsigned AndBitWidth = And.getValueSizeInBits();
10488 if (BitWidth > AndBitWidth) {
10490 DAG.computeKnownBits(Op0, Zeros, Ones);
10491 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10495 RHS = Op0.getOperand(1);
10497 } else if (Op1.getOpcode() == ISD::Constant) {
10498 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10499 uint64_t AndRHSVal = AndRHS->getZExtValue();
10500 SDValue AndLHS = Op0;
10502 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10503 LHS = AndLHS.getOperand(0);
10504 RHS = AndLHS.getOperand(1);
10507 // Use BT if the immediate can't be encoded in a TEST instruction.
10508 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10510 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10514 if (LHS.getNode()) {
10515 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10516 // instruction. Since the shift amount is in-range-or-undefined, we know
10517 // that doing a bittest on the i32 value is ok. We extend to i32 because
10518 // the encoding for the i16 version is larger than the i32 version.
10519 // Also promote i16 to i32 for performance / code size reason.
10520 if (LHS.getValueType() == MVT::i8 ||
10521 LHS.getValueType() == MVT::i16)
10522 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10524 // If the operand types disagree, extend the shift amount to match. Since
10525 // BT ignores high bits (like shifts) we can use anyextend.
10526 if (LHS.getValueType() != RHS.getValueType())
10527 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10529 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10530 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10531 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10532 DAG.getConstant(Cond, MVT::i8), BT);
10538 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10540 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10545 // SSE Condition code mapping:
10554 switch (SetCCOpcode) {
10555 default: llvm_unreachable("Unexpected SETCC condition");
10557 case ISD::SETEQ: SSECC = 0; break;
10559 case ISD::SETGT: Swap = true; // Fallthrough
10561 case ISD::SETOLT: SSECC = 1; break;
10563 case ISD::SETGE: Swap = true; // Fallthrough
10565 case ISD::SETOLE: SSECC = 2; break;
10566 case ISD::SETUO: SSECC = 3; break;
10568 case ISD::SETNE: SSECC = 4; break;
10569 case ISD::SETULE: Swap = true; // Fallthrough
10570 case ISD::SETUGE: SSECC = 5; break;
10571 case ISD::SETULT: Swap = true; // Fallthrough
10572 case ISD::SETUGT: SSECC = 6; break;
10573 case ISD::SETO: SSECC = 7; break;
10575 case ISD::SETONE: SSECC = 8; break;
10578 std::swap(Op0, Op1);
10583 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10584 // ones, and then concatenate the result back.
10585 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10586 MVT VT = Op.getSimpleValueType();
10588 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10589 "Unsupported value type for operation");
10591 unsigned NumElems = VT.getVectorNumElements();
10593 SDValue CC = Op.getOperand(2);
10595 // Extract the LHS vectors
10596 SDValue LHS = Op.getOperand(0);
10597 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10598 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10600 // Extract the RHS vectors
10601 SDValue RHS = Op.getOperand(1);
10602 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10603 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10605 // Issue the operation on the smaller types and concatenate the result back
10606 MVT EltVT = VT.getVectorElementType();
10607 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10608 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10609 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10610 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10613 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10614 const X86Subtarget *Subtarget) {
10615 SDValue Op0 = Op.getOperand(0);
10616 SDValue Op1 = Op.getOperand(1);
10617 SDValue CC = Op.getOperand(2);
10618 MVT VT = Op.getSimpleValueType();
10621 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10622 Op.getValueType().getScalarType() == MVT::i1 &&
10623 "Cannot set masked compare for this operation");
10625 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10627 bool Unsigned = false;
10630 switch (SetCCOpcode) {
10631 default: llvm_unreachable("Unexpected SETCC condition");
10632 case ISD::SETNE: SSECC = 4; break;
10633 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10634 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10635 case ISD::SETLT: Swap = true; //fall-through
10636 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10637 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10638 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10639 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10640 case ISD::SETULE: Unsigned = true; //fall-through
10641 case ISD::SETLE: SSECC = 2; break;
10645 std::swap(Op0, Op1);
10647 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10648 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10649 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10650 DAG.getConstant(SSECC, MVT::i8));
10653 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10654 /// operand \p Op1. If non-trivial (for example because it's not constant)
10655 /// return an empty value.
10656 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10658 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10662 MVT VT = Op1.getSimpleValueType();
10663 MVT EVT = VT.getVectorElementType();
10664 unsigned n = VT.getVectorNumElements();
10665 SmallVector<SDValue, 8> ULTOp1;
10667 for (unsigned i = 0; i < n; ++i) {
10668 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10669 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10672 // Avoid underflow.
10673 APInt Val = Elt->getAPIntValue();
10677 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10680 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10683 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10684 SelectionDAG &DAG) {
10685 SDValue Op0 = Op.getOperand(0);
10686 SDValue Op1 = Op.getOperand(1);
10687 SDValue CC = Op.getOperand(2);
10688 MVT VT = Op.getSimpleValueType();
10689 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10690 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10695 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10696 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10699 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10700 unsigned Opc = X86ISD::CMPP;
10701 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10702 assert(VT.getVectorNumElements() <= 16);
10703 Opc = X86ISD::CMPM;
10705 // In the two special cases we can't handle, emit two comparisons.
10708 unsigned CombineOpc;
10709 if (SetCCOpcode == ISD::SETUEQ) {
10710 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10712 assert(SetCCOpcode == ISD::SETONE);
10713 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10716 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10717 DAG.getConstant(CC0, MVT::i8));
10718 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10719 DAG.getConstant(CC1, MVT::i8));
10720 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10722 // Handle all other FP comparisons here.
10723 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10724 DAG.getConstant(SSECC, MVT::i8));
10727 // Break 256-bit integer vector compare into smaller ones.
10728 if (VT.is256BitVector() && !Subtarget->hasInt256())
10729 return Lower256IntVSETCC(Op, DAG);
10731 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10732 EVT OpVT = Op1.getValueType();
10733 if (Subtarget->hasAVX512()) {
10734 if (Op1.getValueType().is512BitVector() ||
10735 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10736 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10738 // In AVX-512 architecture setcc returns mask with i1 elements,
10739 // But there is no compare instruction for i8 and i16 elements.
10740 // We are not talking about 512-bit operands in this case, these
10741 // types are illegal.
10743 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10744 OpVT.getVectorElementType().getSizeInBits() >= 8))
10745 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10746 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10749 // We are handling one of the integer comparisons here. Since SSE only has
10750 // GT and EQ comparisons for integer, swapping operands and multiple
10751 // operations may be required for some comparisons.
10753 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10754 bool Subus = false;
10756 switch (SetCCOpcode) {
10757 default: llvm_unreachable("Unexpected SETCC condition");
10758 case ISD::SETNE: Invert = true;
10759 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10760 case ISD::SETLT: Swap = true;
10761 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10762 case ISD::SETGE: Swap = true;
10763 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10764 Invert = true; break;
10765 case ISD::SETULT: Swap = true;
10766 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10767 FlipSigns = true; break;
10768 case ISD::SETUGE: Swap = true;
10769 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10770 FlipSigns = true; Invert = true; break;
10773 // Special case: Use min/max operations for SETULE/SETUGE
10774 MVT VET = VT.getVectorElementType();
10776 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10777 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10780 switch (SetCCOpcode) {
10782 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10783 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10786 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10789 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10790 if (!MinMax && hasSubus) {
10791 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10793 // t = psubus Op0, Op1
10794 // pcmpeq t, <0..0>
10795 switch (SetCCOpcode) {
10797 case ISD::SETULT: {
10798 // If the comparison is against a constant we can turn this into a
10799 // setule. With psubus, setule does not require a swap. This is
10800 // beneficial because the constant in the register is no longer
10801 // destructed as the destination so it can be hoisted out of a loop.
10802 // Only do this pre-AVX since vpcmp* is no longer destructive.
10803 if (Subtarget->hasAVX())
10805 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10806 if (ULEOp1.getNode()) {
10808 Subus = true; Invert = false; Swap = false;
10812 // Psubus is better than flip-sign because it requires no inversion.
10813 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10814 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10818 Opc = X86ISD::SUBUS;
10824 std::swap(Op0, Op1);
10826 // Check that the operation in question is available (most are plain SSE2,
10827 // but PCMPGTQ and PCMPEQQ have different requirements).
10828 if (VT == MVT::v2i64) {
10829 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10830 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10832 // First cast everything to the right type.
10833 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10834 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10836 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10837 // bits of the inputs before performing those operations. The lower
10838 // compare is always unsigned.
10841 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10843 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10844 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10845 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10846 Sign, Zero, Sign, Zero);
10848 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10849 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10851 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10852 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10853 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10855 // Create masks for only the low parts/high parts of the 64 bit integers.
10856 static const int MaskHi[] = { 1, 1, 3, 3 };
10857 static const int MaskLo[] = { 0, 0, 2, 2 };
10858 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10859 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10860 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10862 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10863 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10866 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10868 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10871 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10872 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10873 // pcmpeqd + pshufd + pand.
10874 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10876 // First cast everything to the right type.
10877 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10878 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10881 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10883 // Make sure the lower and upper halves are both all-ones.
10884 static const int Mask[] = { 1, 0, 3, 2 };
10885 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10886 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10889 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10891 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10895 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10896 // bits of the inputs before performing those operations.
10898 EVT EltVT = VT.getVectorElementType();
10899 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10900 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10901 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10904 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10906 // If the logical-not of the result is required, perform that now.
10908 Result = DAG.getNOT(dl, Result, VT);
10911 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10914 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10915 getZeroVector(VT, Subtarget, DAG, dl));
10920 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10922 MVT VT = Op.getSimpleValueType();
10924 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10926 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10927 && "SetCC type must be 8-bit or 1-bit integer");
10928 SDValue Op0 = Op.getOperand(0);
10929 SDValue Op1 = Op.getOperand(1);
10931 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10933 // Optimize to BT if possible.
10934 // Lower (X & (1 << N)) == 0 to BT(X, N).
10935 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10936 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10937 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10938 Op1.getOpcode() == ISD::Constant &&
10939 cast<ConstantSDNode>(Op1)->isNullValue() &&
10940 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10941 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10942 if (NewSetCC.getNode())
10946 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10948 if (Op1.getOpcode() == ISD::Constant &&
10949 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10950 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10951 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10953 // If the input is a setcc, then reuse the input setcc or use a new one with
10954 // the inverted condition.
10955 if (Op0.getOpcode() == X86ISD::SETCC) {
10956 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10957 bool Invert = (CC == ISD::SETNE) ^
10958 cast<ConstantSDNode>(Op1)->isNullValue();
10962 CCode = X86::GetOppositeBranchCondition(CCode);
10963 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10964 DAG.getConstant(CCode, MVT::i8),
10965 Op0.getOperand(1));
10967 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10971 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10972 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10973 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10975 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10976 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10979 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10980 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10981 if (X86CC == X86::COND_INVALID)
10984 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10985 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10986 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10987 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10989 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10993 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10994 static bool isX86LogicalCmp(SDValue Op) {
10995 unsigned Opc = Op.getNode()->getOpcode();
10996 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10997 Opc == X86ISD::SAHF)
10999 if (Op.getResNo() == 1 &&
11000 (Opc == X86ISD::ADD ||
11001 Opc == X86ISD::SUB ||
11002 Opc == X86ISD::ADC ||
11003 Opc == X86ISD::SBB ||
11004 Opc == X86ISD::SMUL ||
11005 Opc == X86ISD::UMUL ||
11006 Opc == X86ISD::INC ||
11007 Opc == X86ISD::DEC ||
11008 Opc == X86ISD::OR ||
11009 Opc == X86ISD::XOR ||
11010 Opc == X86ISD::AND))
11013 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
11019 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11020 if (V.getOpcode() != ISD::TRUNCATE)
11023 SDValue VOp0 = V.getOperand(0);
11024 unsigned InBits = VOp0.getValueSizeInBits();
11025 unsigned Bits = V.getValueSizeInBits();
11026 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11029 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11030 bool addTest = true;
11031 SDValue Cond = Op.getOperand(0);
11032 SDValue Op1 = Op.getOperand(1);
11033 SDValue Op2 = Op.getOperand(2);
11035 EVT VT = Op1.getValueType();
11038 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11039 // are available. Otherwise fp cmovs get lowered into a less efficient branch
11040 // sequence later on.
11041 if (Cond.getOpcode() == ISD::SETCC &&
11042 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11043 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11044 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11045 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11046 int SSECC = translateX86FSETCC(
11047 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11050 if (Subtarget->hasAVX512()) {
11051 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11052 DAG.getConstant(SSECC, MVT::i8));
11053 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11055 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11056 DAG.getConstant(SSECC, MVT::i8));
11057 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11058 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11059 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11063 if (Cond.getOpcode() == ISD::SETCC) {
11064 SDValue NewCond = LowerSETCC(Cond, DAG);
11065 if (NewCond.getNode())
11069 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11070 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11071 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11072 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11073 if (Cond.getOpcode() == X86ISD::SETCC &&
11074 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11075 isZero(Cond.getOperand(1).getOperand(1))) {
11076 SDValue Cmp = Cond.getOperand(1);
11078 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11080 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11081 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11082 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11084 SDValue CmpOp0 = Cmp.getOperand(0);
11085 // Apply further optimizations for special cases
11086 // (select (x != 0), -1, 0) -> neg & sbb
11087 // (select (x == 0), 0, -1) -> neg & sbb
11088 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11089 if (YC->isNullValue() &&
11090 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11091 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11092 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11093 DAG.getConstant(0, CmpOp0.getValueType()),
11095 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11096 DAG.getConstant(X86::COND_B, MVT::i8),
11097 SDValue(Neg.getNode(), 1));
11101 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11102 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11103 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11105 SDValue Res = // Res = 0 or -1.
11106 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11107 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11109 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11110 Res = DAG.getNOT(DL, Res, Res.getValueType());
11112 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11113 if (!N2C || !N2C->isNullValue())
11114 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11119 // Look past (and (setcc_carry (cmp ...)), 1).
11120 if (Cond.getOpcode() == ISD::AND &&
11121 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11122 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11123 if (C && C->getAPIntValue() == 1)
11124 Cond = Cond.getOperand(0);
11127 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11128 // setting operand in place of the X86ISD::SETCC.
11129 unsigned CondOpcode = Cond.getOpcode();
11130 if (CondOpcode == X86ISD::SETCC ||
11131 CondOpcode == X86ISD::SETCC_CARRY) {
11132 CC = Cond.getOperand(0);
11134 SDValue Cmp = Cond.getOperand(1);
11135 unsigned Opc = Cmp.getOpcode();
11136 MVT VT = Op.getSimpleValueType();
11138 bool IllegalFPCMov = false;
11139 if (VT.isFloatingPoint() && !VT.isVector() &&
11140 !isScalarFPTypeInSSEReg(VT)) // FPStack?
11141 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11143 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11144 Opc == X86ISD::BT) { // FIXME
11148 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11149 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11150 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11151 Cond.getOperand(0).getValueType() != MVT::i8)) {
11152 SDValue LHS = Cond.getOperand(0);
11153 SDValue RHS = Cond.getOperand(1);
11154 unsigned X86Opcode;
11157 switch (CondOpcode) {
11158 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11159 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11160 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11161 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11162 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11163 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11164 default: llvm_unreachable("unexpected overflowing operator");
11166 if (CondOpcode == ISD::UMULO)
11167 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11170 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11172 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11174 if (CondOpcode == ISD::UMULO)
11175 Cond = X86Op.getValue(2);
11177 Cond = X86Op.getValue(1);
11179 CC = DAG.getConstant(X86Cond, MVT::i8);
11184 // Look pass the truncate if the high bits are known zero.
11185 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11186 Cond = Cond.getOperand(0);
11188 // We know the result of AND is compared against zero. Try to match
11190 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11191 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11192 if (NewSetCC.getNode()) {
11193 CC = NewSetCC.getOperand(0);
11194 Cond = NewSetCC.getOperand(1);
11201 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11202 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11205 // a < b ? -1 : 0 -> RES = ~setcc_carry
11206 // a < b ? 0 : -1 -> RES = setcc_carry
11207 // a >= b ? -1 : 0 -> RES = setcc_carry
11208 // a >= b ? 0 : -1 -> RES = ~setcc_carry
11209 if (Cond.getOpcode() == X86ISD::SUB) {
11210 Cond = ConvertCmpIfNecessary(Cond, DAG);
11211 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11213 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11214 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11215 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11216 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11217 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11218 return DAG.getNOT(DL, Res, Res.getValueType());
11223 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11224 // widen the cmov and push the truncate through. This avoids introducing a new
11225 // branch during isel and doesn't add any extensions.
11226 if (Op.getValueType() == MVT::i8 &&
11227 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11228 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11229 if (T1.getValueType() == T2.getValueType() &&
11230 // Blacklist CopyFromReg to avoid partial register stalls.
11231 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11232 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11233 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11234 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11238 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11239 // condition is true.
11240 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11241 SDValue Ops[] = { Op2, Op1, CC, Cond };
11242 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11245 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11246 MVT VT = Op->getSimpleValueType(0);
11247 SDValue In = Op->getOperand(0);
11248 MVT InVT = In.getSimpleValueType();
11251 unsigned int NumElts = VT.getVectorNumElements();
11252 if (NumElts != 8 && NumElts != 16)
11255 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11256 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11258 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11259 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11261 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11262 Constant *C = ConstantInt::get(*DAG.getContext(),
11263 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11265 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11266 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11267 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11268 MachinePointerInfo::getConstantPool(),
11269 false, false, false, Alignment);
11270 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11271 if (VT.is512BitVector())
11273 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11276 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11277 SelectionDAG &DAG) {
11278 MVT VT = Op->getSimpleValueType(0);
11279 SDValue In = Op->getOperand(0);
11280 MVT InVT = In.getSimpleValueType();
11283 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11284 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11286 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11287 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11288 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11291 if (Subtarget->hasInt256())
11292 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11294 // Optimize vectors in AVX mode
11295 // Sign extend v8i16 to v8i32 and
11298 // Divide input vector into two parts
11299 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11300 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11301 // concat the vectors to original VT
11303 unsigned NumElems = InVT.getVectorNumElements();
11304 SDValue Undef = DAG.getUNDEF(InVT);
11306 SmallVector<int,8> ShufMask1(NumElems, -1);
11307 for (unsigned i = 0; i != NumElems/2; ++i)
11310 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11312 SmallVector<int,8> ShufMask2(NumElems, -1);
11313 for (unsigned i = 0; i != NumElems/2; ++i)
11314 ShufMask2[i] = i + NumElems/2;
11316 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11318 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11319 VT.getVectorNumElements()/2);
11321 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11322 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11324 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11327 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11328 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11329 // from the AND / OR.
11330 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11331 Opc = Op.getOpcode();
11332 if (Opc != ISD::OR && Opc != ISD::AND)
11334 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11335 Op.getOperand(0).hasOneUse() &&
11336 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11337 Op.getOperand(1).hasOneUse());
11340 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11341 // 1 and that the SETCC node has a single use.
11342 static bool isXor1OfSetCC(SDValue Op) {
11343 if (Op.getOpcode() != ISD::XOR)
11345 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11346 if (N1C && N1C->getAPIntValue() == 1) {
11347 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11348 Op.getOperand(0).hasOneUse();
11353 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11354 bool addTest = true;
11355 SDValue Chain = Op.getOperand(0);
11356 SDValue Cond = Op.getOperand(1);
11357 SDValue Dest = Op.getOperand(2);
11360 bool Inverted = false;
11362 if (Cond.getOpcode() == ISD::SETCC) {
11363 // Check for setcc([su]{add,sub,mul}o == 0).
11364 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11365 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11366 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11367 Cond.getOperand(0).getResNo() == 1 &&
11368 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11369 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11370 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11371 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11372 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11373 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11375 Cond = Cond.getOperand(0);
11377 SDValue NewCond = LowerSETCC(Cond, DAG);
11378 if (NewCond.getNode())
11383 // FIXME: LowerXALUO doesn't handle these!!
11384 else if (Cond.getOpcode() == X86ISD::ADD ||
11385 Cond.getOpcode() == X86ISD::SUB ||
11386 Cond.getOpcode() == X86ISD::SMUL ||
11387 Cond.getOpcode() == X86ISD::UMUL)
11388 Cond = LowerXALUO(Cond, DAG);
11391 // Look pass (and (setcc_carry (cmp ...)), 1).
11392 if (Cond.getOpcode() == ISD::AND &&
11393 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11394 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11395 if (C && C->getAPIntValue() == 1)
11396 Cond = Cond.getOperand(0);
11399 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11400 // setting operand in place of the X86ISD::SETCC.
11401 unsigned CondOpcode = Cond.getOpcode();
11402 if (CondOpcode == X86ISD::SETCC ||
11403 CondOpcode == X86ISD::SETCC_CARRY) {
11404 CC = Cond.getOperand(0);
11406 SDValue Cmp = Cond.getOperand(1);
11407 unsigned Opc = Cmp.getOpcode();
11408 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11409 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11413 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11417 // These can only come from an arithmetic instruction with overflow,
11418 // e.g. SADDO, UADDO.
11419 Cond = Cond.getNode()->getOperand(1);
11425 CondOpcode = Cond.getOpcode();
11426 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11427 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11428 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11429 Cond.getOperand(0).getValueType() != MVT::i8)) {
11430 SDValue LHS = Cond.getOperand(0);
11431 SDValue RHS = Cond.getOperand(1);
11432 unsigned X86Opcode;
11435 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11436 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11438 switch (CondOpcode) {
11439 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11441 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11443 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11446 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11447 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11449 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11451 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11454 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11455 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11456 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11457 default: llvm_unreachable("unexpected overflowing operator");
11460 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11461 if (CondOpcode == ISD::UMULO)
11462 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11465 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11467 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11469 if (CondOpcode == ISD::UMULO)
11470 Cond = X86Op.getValue(2);
11472 Cond = X86Op.getValue(1);
11474 CC = DAG.getConstant(X86Cond, MVT::i8);
11478 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11479 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11480 if (CondOpc == ISD::OR) {
11481 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11482 // two branches instead of an explicit OR instruction with a
11484 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11485 isX86LogicalCmp(Cmp)) {
11486 CC = Cond.getOperand(0).getOperand(0);
11487 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11488 Chain, Dest, CC, Cmp);
11489 CC = Cond.getOperand(1).getOperand(0);
11493 } else { // ISD::AND
11494 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11495 // two branches instead of an explicit AND instruction with a
11496 // separate test. However, we only do this if this block doesn't
11497 // have a fall-through edge, because this requires an explicit
11498 // jmp when the condition is false.
11499 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11500 isX86LogicalCmp(Cmp) &&
11501 Op.getNode()->hasOneUse()) {
11502 X86::CondCode CCode =
11503 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11504 CCode = X86::GetOppositeBranchCondition(CCode);
11505 CC = DAG.getConstant(CCode, MVT::i8);
11506 SDNode *User = *Op.getNode()->use_begin();
11507 // Look for an unconditional branch following this conditional branch.
11508 // We need this because we need to reverse the successors in order
11509 // to implement FCMP_OEQ.
11510 if (User->getOpcode() == ISD::BR) {
11511 SDValue FalseBB = User->getOperand(1);
11513 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11514 assert(NewBR == User);
11518 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11519 Chain, Dest, CC, Cmp);
11520 X86::CondCode CCode =
11521 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11522 CCode = X86::GetOppositeBranchCondition(CCode);
11523 CC = DAG.getConstant(CCode, MVT::i8);
11529 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11530 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11531 // It should be transformed during dag combiner except when the condition
11532 // is set by a arithmetics with overflow node.
11533 X86::CondCode CCode =
11534 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11535 CCode = X86::GetOppositeBranchCondition(CCode);
11536 CC = DAG.getConstant(CCode, MVT::i8);
11537 Cond = Cond.getOperand(0).getOperand(1);
11539 } else if (Cond.getOpcode() == ISD::SETCC &&
11540 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11541 // For FCMP_OEQ, we can emit
11542 // two branches instead of an explicit AND instruction with a
11543 // separate test. However, we only do this if this block doesn't
11544 // have a fall-through edge, because this requires an explicit
11545 // jmp when the condition is false.
11546 if (Op.getNode()->hasOneUse()) {
11547 SDNode *User = *Op.getNode()->use_begin();
11548 // Look for an unconditional branch following this conditional branch.
11549 // We need this because we need to reverse the successors in order
11550 // to implement FCMP_OEQ.
11551 if (User->getOpcode() == ISD::BR) {
11552 SDValue FalseBB = User->getOperand(1);
11554 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11555 assert(NewBR == User);
11559 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11560 Cond.getOperand(0), Cond.getOperand(1));
11561 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11562 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11563 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11564 Chain, Dest, CC, Cmp);
11565 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11570 } else if (Cond.getOpcode() == ISD::SETCC &&
11571 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11572 // For FCMP_UNE, we can emit
11573 // two branches instead of an explicit AND instruction with a
11574 // separate test. However, we only do this if this block doesn't
11575 // have a fall-through edge, because this requires an explicit
11576 // jmp when the condition is false.
11577 if (Op.getNode()->hasOneUse()) {
11578 SDNode *User = *Op.getNode()->use_begin();
11579 // Look for an unconditional branch following this conditional branch.
11580 // We need this because we need to reverse the successors in order
11581 // to implement FCMP_UNE.
11582 if (User->getOpcode() == ISD::BR) {
11583 SDValue FalseBB = User->getOperand(1);
11585 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11586 assert(NewBR == User);
11589 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11590 Cond.getOperand(0), Cond.getOperand(1));
11591 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11592 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11593 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11594 Chain, Dest, CC, Cmp);
11595 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11605 // Look pass the truncate if the high bits are known zero.
11606 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11607 Cond = Cond.getOperand(0);
11609 // We know the result of AND is compared against zero. Try to match
11611 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11612 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11613 if (NewSetCC.getNode()) {
11614 CC = NewSetCC.getOperand(0);
11615 Cond = NewSetCC.getOperand(1);
11622 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11623 CC = DAG.getConstant(X86Cond, MVT::i8);
11624 Cond = EmitTest(Cond, X86Cond, dl, DAG);
11626 Cond = ConvertCmpIfNecessary(Cond, DAG);
11627 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11628 Chain, Dest, CC, Cond);
11631 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11632 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11633 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11634 // that the guard pages used by the OS virtual memory manager are allocated in
11635 // correct sequence.
11637 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11638 SelectionDAG &DAG) const {
11639 MachineFunction &MF = DAG.getMachineFunction();
11640 bool SplitStack = MF.shouldSplitStack();
11641 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11646 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11647 SDNode* Node = Op.getNode();
11649 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11650 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11651 " not tell us which reg is the stack pointer!");
11652 EVT VT = Node->getValueType(0);
11653 SDValue Tmp1 = SDValue(Node, 0);
11654 SDValue Tmp2 = SDValue(Node, 1);
11655 SDValue Tmp3 = Node->getOperand(2);
11656 SDValue Chain = Tmp1.getOperand(0);
11658 // Chain the dynamic stack allocation so that it doesn't modify the stack
11659 // pointer when other instructions are using the stack.
11660 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11663 SDValue Size = Tmp2.getOperand(1);
11664 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11665 Chain = SP.getValue(1);
11666 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11667 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11668 unsigned StackAlign = TFI.getStackAlignment();
11669 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11670 if (Align > StackAlign)
11671 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11672 DAG.getConstant(-(uint64_t)Align, VT));
11673 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11675 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11676 DAG.getIntPtrConstant(0, true), SDValue(),
11679 SDValue Ops[2] = { Tmp1, Tmp2 };
11680 return DAG.getMergeValues(Ops, dl);
11684 SDValue Chain = Op.getOperand(0);
11685 SDValue Size = Op.getOperand(1);
11686 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11687 EVT VT = Op.getNode()->getValueType(0);
11689 bool Is64Bit = Subtarget->is64Bit();
11690 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11693 MachineRegisterInfo &MRI = MF.getRegInfo();
11696 // The 64 bit implementation of segmented stacks needs to clobber both r10
11697 // r11. This makes it impossible to use it along with nested parameters.
11698 const Function *F = MF.getFunction();
11700 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11702 if (I->hasNestAttr())
11703 report_fatal_error("Cannot use segmented stacks with functions that "
11704 "have nested arguments.");
11707 const TargetRegisterClass *AddrRegClass =
11708 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11709 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11710 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11711 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11712 DAG.getRegister(Vreg, SPTy));
11713 SDValue Ops1[2] = { Value, Chain };
11714 return DAG.getMergeValues(Ops1, dl);
11717 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11719 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11720 Flag = Chain.getValue(1);
11721 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11723 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11725 const X86RegisterInfo *RegInfo =
11726 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11727 unsigned SPReg = RegInfo->getStackRegister();
11728 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11729 Chain = SP.getValue(1);
11732 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11733 DAG.getConstant(-(uint64_t)Align, VT));
11734 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11737 SDValue Ops1[2] = { SP, Chain };
11738 return DAG.getMergeValues(Ops1, dl);
11742 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11743 MachineFunction &MF = DAG.getMachineFunction();
11744 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11746 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11749 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11750 // vastart just stores the address of the VarArgsFrameIndex slot into the
11751 // memory location argument.
11752 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11754 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11755 MachinePointerInfo(SV), false, false, 0);
11759 // gp_offset (0 - 6 * 8)
11760 // fp_offset (48 - 48 + 8 * 16)
11761 // overflow_arg_area (point to parameters coming in memory).
11763 SmallVector<SDValue, 8> MemOps;
11764 SDValue FIN = Op.getOperand(1);
11766 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11767 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11769 FIN, MachinePointerInfo(SV), false, false, 0);
11770 MemOps.push_back(Store);
11773 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11774 FIN, DAG.getIntPtrConstant(4));
11775 Store = DAG.getStore(Op.getOperand(0), DL,
11776 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11778 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11779 MemOps.push_back(Store);
11781 // Store ptr to overflow_arg_area
11782 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11783 FIN, DAG.getIntPtrConstant(4));
11784 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11786 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11787 MachinePointerInfo(SV, 8),
11789 MemOps.push_back(Store);
11791 // Store ptr to reg_save_area.
11792 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11793 FIN, DAG.getIntPtrConstant(8));
11794 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11796 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11797 MachinePointerInfo(SV, 16), false, false, 0);
11798 MemOps.push_back(Store);
11799 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11802 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11803 assert(Subtarget->is64Bit() &&
11804 "LowerVAARG only handles 64-bit va_arg!");
11805 assert((Subtarget->isTargetLinux() ||
11806 Subtarget->isTargetDarwin()) &&
11807 "Unhandled target in LowerVAARG");
11808 assert(Op.getNode()->getNumOperands() == 4);
11809 SDValue Chain = Op.getOperand(0);
11810 SDValue SrcPtr = Op.getOperand(1);
11811 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11812 unsigned Align = Op.getConstantOperandVal(3);
11815 EVT ArgVT = Op.getNode()->getValueType(0);
11816 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11817 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11820 // Decide which area this value should be read from.
11821 // TODO: Implement the AMD64 ABI in its entirety. This simple
11822 // selection mechanism works only for the basic types.
11823 if (ArgVT == MVT::f80) {
11824 llvm_unreachable("va_arg for f80 not yet implemented");
11825 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11826 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11827 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11828 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11830 llvm_unreachable("Unhandled argument type in LowerVAARG");
11833 if (ArgMode == 2) {
11834 // Sanity Check: Make sure using fp_offset makes sense.
11835 assert(!getTargetMachine().Options.UseSoftFloat &&
11836 !(DAG.getMachineFunction()
11837 .getFunction()->getAttributes()
11838 .hasAttribute(AttributeSet::FunctionIndex,
11839 Attribute::NoImplicitFloat)) &&
11840 Subtarget->hasSSE1());
11843 // Insert VAARG_64 node into the DAG
11844 // VAARG_64 returns two values: Variable Argument Address, Chain
11845 SmallVector<SDValue, 11> InstOps;
11846 InstOps.push_back(Chain);
11847 InstOps.push_back(SrcPtr);
11848 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11849 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11850 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11851 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11852 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11853 VTs, InstOps, MVT::i64,
11854 MachinePointerInfo(SV),
11856 /*Volatile=*/false,
11858 /*WriteMem=*/true);
11859 Chain = VAARG.getValue(1);
11861 // Load the next argument and return it
11862 return DAG.getLoad(ArgVT, dl,
11865 MachinePointerInfo(),
11866 false, false, false, 0);
11869 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11870 SelectionDAG &DAG) {
11871 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11872 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11873 SDValue Chain = Op.getOperand(0);
11874 SDValue DstPtr = Op.getOperand(1);
11875 SDValue SrcPtr = Op.getOperand(2);
11876 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11877 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11880 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11881 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11883 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11886 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11887 // amount is a constant. Takes immediate version of shift as input.
11888 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11889 SDValue SrcOp, uint64_t ShiftAmt,
11890 SelectionDAG &DAG) {
11891 MVT ElementType = VT.getVectorElementType();
11893 // Fold this packed shift into its first operand if ShiftAmt is 0.
11897 // Check for ShiftAmt >= element width
11898 if (ShiftAmt >= ElementType.getSizeInBits()) {
11899 if (Opc == X86ISD::VSRAI)
11900 ShiftAmt = ElementType.getSizeInBits() - 1;
11902 return DAG.getConstant(0, VT);
11905 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11906 && "Unknown target vector shift-by-constant node");
11908 // Fold this packed vector shift into a build vector if SrcOp is a
11909 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11910 if (VT == SrcOp.getSimpleValueType() &&
11911 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11912 SmallVector<SDValue, 8> Elts;
11913 unsigned NumElts = SrcOp->getNumOperands();
11914 ConstantSDNode *ND;
11917 default: llvm_unreachable(nullptr);
11918 case X86ISD::VSHLI:
11919 for (unsigned i=0; i!=NumElts; ++i) {
11920 SDValue CurrentOp = SrcOp->getOperand(i);
11921 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11922 Elts.push_back(CurrentOp);
11925 ND = cast<ConstantSDNode>(CurrentOp);
11926 const APInt &C = ND->getAPIntValue();
11927 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11930 case X86ISD::VSRLI:
11931 for (unsigned i=0; i!=NumElts; ++i) {
11932 SDValue CurrentOp = SrcOp->getOperand(i);
11933 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11934 Elts.push_back(CurrentOp);
11937 ND = cast<ConstantSDNode>(CurrentOp);
11938 const APInt &C = ND->getAPIntValue();
11939 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11942 case X86ISD::VSRAI:
11943 for (unsigned i=0; i!=NumElts; ++i) {
11944 SDValue CurrentOp = SrcOp->getOperand(i);
11945 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11946 Elts.push_back(CurrentOp);
11949 ND = cast<ConstantSDNode>(CurrentOp);
11950 const APInt &C = ND->getAPIntValue();
11951 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11956 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11959 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11962 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11963 // may or may not be a constant. Takes immediate version of shift as input.
11964 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11965 SDValue SrcOp, SDValue ShAmt,
11966 SelectionDAG &DAG) {
11967 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11969 // Catch shift-by-constant.
11970 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11971 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11972 CShAmt->getZExtValue(), DAG);
11974 // Change opcode to non-immediate version
11976 default: llvm_unreachable("Unknown target vector shift node");
11977 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11978 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11979 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11982 // Need to build a vector containing shift amount
11983 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11986 ShOps[1] = DAG.getConstant(0, MVT::i32);
11987 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11988 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11990 // The return type has to be a 128-bit type with the same element
11991 // type as the input type.
11992 MVT EltVT = VT.getVectorElementType();
11993 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11995 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11996 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11999 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
12001 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12003 default: return SDValue(); // Don't custom lower most intrinsics.
12004 // Comparison intrinsics.
12005 case Intrinsic::x86_sse_comieq_ss:
12006 case Intrinsic::x86_sse_comilt_ss:
12007 case Intrinsic::x86_sse_comile_ss:
12008 case Intrinsic::x86_sse_comigt_ss:
12009 case Intrinsic::x86_sse_comige_ss:
12010 case Intrinsic::x86_sse_comineq_ss:
12011 case Intrinsic::x86_sse_ucomieq_ss:
12012 case Intrinsic::x86_sse_ucomilt_ss:
12013 case Intrinsic::x86_sse_ucomile_ss:
12014 case Intrinsic::x86_sse_ucomigt_ss:
12015 case Intrinsic::x86_sse_ucomige_ss:
12016 case Intrinsic::x86_sse_ucomineq_ss:
12017 case Intrinsic::x86_sse2_comieq_sd:
12018 case Intrinsic::x86_sse2_comilt_sd:
12019 case Intrinsic::x86_sse2_comile_sd:
12020 case Intrinsic::x86_sse2_comigt_sd:
12021 case Intrinsic::x86_sse2_comige_sd:
12022 case Intrinsic::x86_sse2_comineq_sd:
12023 case Intrinsic::x86_sse2_ucomieq_sd:
12024 case Intrinsic::x86_sse2_ucomilt_sd:
12025 case Intrinsic::x86_sse2_ucomile_sd:
12026 case Intrinsic::x86_sse2_ucomigt_sd:
12027 case Intrinsic::x86_sse2_ucomige_sd:
12028 case Intrinsic::x86_sse2_ucomineq_sd: {
12032 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12033 case Intrinsic::x86_sse_comieq_ss:
12034 case Intrinsic::x86_sse2_comieq_sd:
12035 Opc = X86ISD::COMI;
12038 case Intrinsic::x86_sse_comilt_ss:
12039 case Intrinsic::x86_sse2_comilt_sd:
12040 Opc = X86ISD::COMI;
12043 case Intrinsic::x86_sse_comile_ss:
12044 case Intrinsic::x86_sse2_comile_sd:
12045 Opc = X86ISD::COMI;
12048 case Intrinsic::x86_sse_comigt_ss:
12049 case Intrinsic::x86_sse2_comigt_sd:
12050 Opc = X86ISD::COMI;
12053 case Intrinsic::x86_sse_comige_ss:
12054 case Intrinsic::x86_sse2_comige_sd:
12055 Opc = X86ISD::COMI;
12058 case Intrinsic::x86_sse_comineq_ss:
12059 case Intrinsic::x86_sse2_comineq_sd:
12060 Opc = X86ISD::COMI;
12063 case Intrinsic::x86_sse_ucomieq_ss:
12064 case Intrinsic::x86_sse2_ucomieq_sd:
12065 Opc = X86ISD::UCOMI;
12068 case Intrinsic::x86_sse_ucomilt_ss:
12069 case Intrinsic::x86_sse2_ucomilt_sd:
12070 Opc = X86ISD::UCOMI;
12073 case Intrinsic::x86_sse_ucomile_ss:
12074 case Intrinsic::x86_sse2_ucomile_sd:
12075 Opc = X86ISD::UCOMI;
12078 case Intrinsic::x86_sse_ucomigt_ss:
12079 case Intrinsic::x86_sse2_ucomigt_sd:
12080 Opc = X86ISD::UCOMI;
12083 case Intrinsic::x86_sse_ucomige_ss:
12084 case Intrinsic::x86_sse2_ucomige_sd:
12085 Opc = X86ISD::UCOMI;
12088 case Intrinsic::x86_sse_ucomineq_ss:
12089 case Intrinsic::x86_sse2_ucomineq_sd:
12090 Opc = X86ISD::UCOMI;
12095 SDValue LHS = Op.getOperand(1);
12096 SDValue RHS = Op.getOperand(2);
12097 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12098 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12099 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12100 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12101 DAG.getConstant(X86CC, MVT::i8), Cond);
12102 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12105 // Arithmetic intrinsics.
12106 case Intrinsic::x86_sse2_pmulu_dq:
12107 case Intrinsic::x86_avx2_pmulu_dq:
12108 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12109 Op.getOperand(1), Op.getOperand(2));
12111 case Intrinsic::x86_sse41_pmuldq:
12112 case Intrinsic::x86_avx2_pmul_dq:
12113 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12114 Op.getOperand(1), Op.getOperand(2));
12116 case Intrinsic::x86_sse2_pmulhu_w:
12117 case Intrinsic::x86_avx2_pmulhu_w:
12118 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12119 Op.getOperand(1), Op.getOperand(2));
12121 case Intrinsic::x86_sse2_pmulh_w:
12122 case Intrinsic::x86_avx2_pmulh_w:
12123 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12124 Op.getOperand(1), Op.getOperand(2));
12126 // SSE2/AVX2 sub with unsigned saturation intrinsics
12127 case Intrinsic::x86_sse2_psubus_b:
12128 case Intrinsic::x86_sse2_psubus_w:
12129 case Intrinsic::x86_avx2_psubus_b:
12130 case Intrinsic::x86_avx2_psubus_w:
12131 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12132 Op.getOperand(1), Op.getOperand(2));
12134 // SSE3/AVX horizontal add/sub intrinsics
12135 case Intrinsic::x86_sse3_hadd_ps:
12136 case Intrinsic::x86_sse3_hadd_pd:
12137 case Intrinsic::x86_avx_hadd_ps_256:
12138 case Intrinsic::x86_avx_hadd_pd_256:
12139 case Intrinsic::x86_sse3_hsub_ps:
12140 case Intrinsic::x86_sse3_hsub_pd:
12141 case Intrinsic::x86_avx_hsub_ps_256:
12142 case Intrinsic::x86_avx_hsub_pd_256:
12143 case Intrinsic::x86_ssse3_phadd_w_128:
12144 case Intrinsic::x86_ssse3_phadd_d_128:
12145 case Intrinsic::x86_avx2_phadd_w:
12146 case Intrinsic::x86_avx2_phadd_d:
12147 case Intrinsic::x86_ssse3_phsub_w_128:
12148 case Intrinsic::x86_ssse3_phsub_d_128:
12149 case Intrinsic::x86_avx2_phsub_w:
12150 case Intrinsic::x86_avx2_phsub_d: {
12153 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12154 case Intrinsic::x86_sse3_hadd_ps:
12155 case Intrinsic::x86_sse3_hadd_pd:
12156 case Intrinsic::x86_avx_hadd_ps_256:
12157 case Intrinsic::x86_avx_hadd_pd_256:
12158 Opcode = X86ISD::FHADD;
12160 case Intrinsic::x86_sse3_hsub_ps:
12161 case Intrinsic::x86_sse3_hsub_pd:
12162 case Intrinsic::x86_avx_hsub_ps_256:
12163 case Intrinsic::x86_avx_hsub_pd_256:
12164 Opcode = X86ISD::FHSUB;
12166 case Intrinsic::x86_ssse3_phadd_w_128:
12167 case Intrinsic::x86_ssse3_phadd_d_128:
12168 case Intrinsic::x86_avx2_phadd_w:
12169 case Intrinsic::x86_avx2_phadd_d:
12170 Opcode = X86ISD::HADD;
12172 case Intrinsic::x86_ssse3_phsub_w_128:
12173 case Intrinsic::x86_ssse3_phsub_d_128:
12174 case Intrinsic::x86_avx2_phsub_w:
12175 case Intrinsic::x86_avx2_phsub_d:
12176 Opcode = X86ISD::HSUB;
12179 return DAG.getNode(Opcode, dl, Op.getValueType(),
12180 Op.getOperand(1), Op.getOperand(2));
12183 // SSE2/SSE41/AVX2 integer max/min intrinsics.
12184 case Intrinsic::x86_sse2_pmaxu_b:
12185 case Intrinsic::x86_sse41_pmaxuw:
12186 case Intrinsic::x86_sse41_pmaxud:
12187 case Intrinsic::x86_avx2_pmaxu_b:
12188 case Intrinsic::x86_avx2_pmaxu_w:
12189 case Intrinsic::x86_avx2_pmaxu_d:
12190 case Intrinsic::x86_sse2_pminu_b:
12191 case Intrinsic::x86_sse41_pminuw:
12192 case Intrinsic::x86_sse41_pminud:
12193 case Intrinsic::x86_avx2_pminu_b:
12194 case Intrinsic::x86_avx2_pminu_w:
12195 case Intrinsic::x86_avx2_pminu_d:
12196 case Intrinsic::x86_sse41_pmaxsb:
12197 case Intrinsic::x86_sse2_pmaxs_w:
12198 case Intrinsic::x86_sse41_pmaxsd:
12199 case Intrinsic::x86_avx2_pmaxs_b:
12200 case Intrinsic::x86_avx2_pmaxs_w:
12201 case Intrinsic::x86_avx2_pmaxs_d:
12202 case Intrinsic::x86_sse41_pminsb:
12203 case Intrinsic::x86_sse2_pmins_w:
12204 case Intrinsic::x86_sse41_pminsd:
12205 case Intrinsic::x86_avx2_pmins_b:
12206 case Intrinsic::x86_avx2_pmins_w:
12207 case Intrinsic::x86_avx2_pmins_d: {
12210 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12211 case Intrinsic::x86_sse2_pmaxu_b:
12212 case Intrinsic::x86_sse41_pmaxuw:
12213 case Intrinsic::x86_sse41_pmaxud:
12214 case Intrinsic::x86_avx2_pmaxu_b:
12215 case Intrinsic::x86_avx2_pmaxu_w:
12216 case Intrinsic::x86_avx2_pmaxu_d:
12217 Opcode = X86ISD::UMAX;
12219 case Intrinsic::x86_sse2_pminu_b:
12220 case Intrinsic::x86_sse41_pminuw:
12221 case Intrinsic::x86_sse41_pminud:
12222 case Intrinsic::x86_avx2_pminu_b:
12223 case Intrinsic::x86_avx2_pminu_w:
12224 case Intrinsic::x86_avx2_pminu_d:
12225 Opcode = X86ISD::UMIN;
12227 case Intrinsic::x86_sse41_pmaxsb:
12228 case Intrinsic::x86_sse2_pmaxs_w:
12229 case Intrinsic::x86_sse41_pmaxsd:
12230 case Intrinsic::x86_avx2_pmaxs_b:
12231 case Intrinsic::x86_avx2_pmaxs_w:
12232 case Intrinsic::x86_avx2_pmaxs_d:
12233 Opcode = X86ISD::SMAX;
12235 case Intrinsic::x86_sse41_pminsb:
12236 case Intrinsic::x86_sse2_pmins_w:
12237 case Intrinsic::x86_sse41_pminsd:
12238 case Intrinsic::x86_avx2_pmins_b:
12239 case Intrinsic::x86_avx2_pmins_w:
12240 case Intrinsic::x86_avx2_pmins_d:
12241 Opcode = X86ISD::SMIN;
12244 return DAG.getNode(Opcode, dl, Op.getValueType(),
12245 Op.getOperand(1), Op.getOperand(2));
12248 // SSE/SSE2/AVX floating point max/min intrinsics.
12249 case Intrinsic::x86_sse_max_ps:
12250 case Intrinsic::x86_sse2_max_pd:
12251 case Intrinsic::x86_avx_max_ps_256:
12252 case Intrinsic::x86_avx_max_pd_256:
12253 case Intrinsic::x86_sse_min_ps:
12254 case Intrinsic::x86_sse2_min_pd:
12255 case Intrinsic::x86_avx_min_ps_256:
12256 case Intrinsic::x86_avx_min_pd_256: {
12259 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12260 case Intrinsic::x86_sse_max_ps:
12261 case Intrinsic::x86_sse2_max_pd:
12262 case Intrinsic::x86_avx_max_ps_256:
12263 case Intrinsic::x86_avx_max_pd_256:
12264 Opcode = X86ISD::FMAX;
12266 case Intrinsic::x86_sse_min_ps:
12267 case Intrinsic::x86_sse2_min_pd:
12268 case Intrinsic::x86_avx_min_ps_256:
12269 case Intrinsic::x86_avx_min_pd_256:
12270 Opcode = X86ISD::FMIN;
12273 return DAG.getNode(Opcode, dl, Op.getValueType(),
12274 Op.getOperand(1), Op.getOperand(2));
12277 // AVX2 variable shift intrinsics
12278 case Intrinsic::x86_avx2_psllv_d:
12279 case Intrinsic::x86_avx2_psllv_q:
12280 case Intrinsic::x86_avx2_psllv_d_256:
12281 case Intrinsic::x86_avx2_psllv_q_256:
12282 case Intrinsic::x86_avx2_psrlv_d:
12283 case Intrinsic::x86_avx2_psrlv_q:
12284 case Intrinsic::x86_avx2_psrlv_d_256:
12285 case Intrinsic::x86_avx2_psrlv_q_256:
12286 case Intrinsic::x86_avx2_psrav_d:
12287 case Intrinsic::x86_avx2_psrav_d_256: {
12290 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12291 case Intrinsic::x86_avx2_psllv_d:
12292 case Intrinsic::x86_avx2_psllv_q:
12293 case Intrinsic::x86_avx2_psllv_d_256:
12294 case Intrinsic::x86_avx2_psllv_q_256:
12297 case Intrinsic::x86_avx2_psrlv_d:
12298 case Intrinsic::x86_avx2_psrlv_q:
12299 case Intrinsic::x86_avx2_psrlv_d_256:
12300 case Intrinsic::x86_avx2_psrlv_q_256:
12303 case Intrinsic::x86_avx2_psrav_d:
12304 case Intrinsic::x86_avx2_psrav_d_256:
12308 return DAG.getNode(Opcode, dl, Op.getValueType(),
12309 Op.getOperand(1), Op.getOperand(2));
12312 case Intrinsic::x86_ssse3_pshuf_b_128:
12313 case Intrinsic::x86_avx2_pshuf_b:
12314 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12315 Op.getOperand(1), Op.getOperand(2));
12317 case Intrinsic::x86_ssse3_psign_b_128:
12318 case Intrinsic::x86_ssse3_psign_w_128:
12319 case Intrinsic::x86_ssse3_psign_d_128:
12320 case Intrinsic::x86_avx2_psign_b:
12321 case Intrinsic::x86_avx2_psign_w:
12322 case Intrinsic::x86_avx2_psign_d:
12323 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12324 Op.getOperand(1), Op.getOperand(2));
12326 case Intrinsic::x86_sse41_insertps:
12327 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12328 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12330 case Intrinsic::x86_avx_vperm2f128_ps_256:
12331 case Intrinsic::x86_avx_vperm2f128_pd_256:
12332 case Intrinsic::x86_avx_vperm2f128_si_256:
12333 case Intrinsic::x86_avx2_vperm2i128:
12334 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12335 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12337 case Intrinsic::x86_avx2_permd:
12338 case Intrinsic::x86_avx2_permps:
12339 // Operands intentionally swapped. Mask is last operand to intrinsic,
12340 // but second operand for node/instruction.
12341 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12342 Op.getOperand(2), Op.getOperand(1));
12344 case Intrinsic::x86_sse_sqrt_ps:
12345 case Intrinsic::x86_sse2_sqrt_pd:
12346 case Intrinsic::x86_avx_sqrt_ps_256:
12347 case Intrinsic::x86_avx_sqrt_pd_256:
12348 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12350 // ptest and testp intrinsics. The intrinsic these come from are designed to
12351 // return an integer value, not just an instruction so lower it to the ptest
12352 // or testp pattern and a setcc for the result.
12353 case Intrinsic::x86_sse41_ptestz:
12354 case Intrinsic::x86_sse41_ptestc:
12355 case Intrinsic::x86_sse41_ptestnzc:
12356 case Intrinsic::x86_avx_ptestz_256:
12357 case Intrinsic::x86_avx_ptestc_256:
12358 case Intrinsic::x86_avx_ptestnzc_256:
12359 case Intrinsic::x86_avx_vtestz_ps:
12360 case Intrinsic::x86_avx_vtestc_ps:
12361 case Intrinsic::x86_avx_vtestnzc_ps:
12362 case Intrinsic::x86_avx_vtestz_pd:
12363 case Intrinsic::x86_avx_vtestc_pd:
12364 case Intrinsic::x86_avx_vtestnzc_pd:
12365 case Intrinsic::x86_avx_vtestz_ps_256:
12366 case Intrinsic::x86_avx_vtestc_ps_256:
12367 case Intrinsic::x86_avx_vtestnzc_ps_256:
12368 case Intrinsic::x86_avx_vtestz_pd_256:
12369 case Intrinsic::x86_avx_vtestc_pd_256:
12370 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12371 bool IsTestPacked = false;
12374 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12375 case Intrinsic::x86_avx_vtestz_ps:
12376 case Intrinsic::x86_avx_vtestz_pd:
12377 case Intrinsic::x86_avx_vtestz_ps_256:
12378 case Intrinsic::x86_avx_vtestz_pd_256:
12379 IsTestPacked = true; // Fallthrough
12380 case Intrinsic::x86_sse41_ptestz:
12381 case Intrinsic::x86_avx_ptestz_256:
12383 X86CC = X86::COND_E;
12385 case Intrinsic::x86_avx_vtestc_ps:
12386 case Intrinsic::x86_avx_vtestc_pd:
12387 case Intrinsic::x86_avx_vtestc_ps_256:
12388 case Intrinsic::x86_avx_vtestc_pd_256:
12389 IsTestPacked = true; // Fallthrough
12390 case Intrinsic::x86_sse41_ptestc:
12391 case Intrinsic::x86_avx_ptestc_256:
12393 X86CC = X86::COND_B;
12395 case Intrinsic::x86_avx_vtestnzc_ps:
12396 case Intrinsic::x86_avx_vtestnzc_pd:
12397 case Intrinsic::x86_avx_vtestnzc_ps_256:
12398 case Intrinsic::x86_avx_vtestnzc_pd_256:
12399 IsTestPacked = true; // Fallthrough
12400 case Intrinsic::x86_sse41_ptestnzc:
12401 case Intrinsic::x86_avx_ptestnzc_256:
12403 X86CC = X86::COND_A;
12407 SDValue LHS = Op.getOperand(1);
12408 SDValue RHS = Op.getOperand(2);
12409 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12410 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12411 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12412 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12413 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12415 case Intrinsic::x86_avx512_kortestz_w:
12416 case Intrinsic::x86_avx512_kortestc_w: {
12417 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12418 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12419 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12420 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12421 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12422 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12423 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12426 // SSE/AVX shift intrinsics
12427 case Intrinsic::x86_sse2_psll_w:
12428 case Intrinsic::x86_sse2_psll_d:
12429 case Intrinsic::x86_sse2_psll_q:
12430 case Intrinsic::x86_avx2_psll_w:
12431 case Intrinsic::x86_avx2_psll_d:
12432 case Intrinsic::x86_avx2_psll_q:
12433 case Intrinsic::x86_sse2_psrl_w:
12434 case Intrinsic::x86_sse2_psrl_d:
12435 case Intrinsic::x86_sse2_psrl_q:
12436 case Intrinsic::x86_avx2_psrl_w:
12437 case Intrinsic::x86_avx2_psrl_d:
12438 case Intrinsic::x86_avx2_psrl_q:
12439 case Intrinsic::x86_sse2_psra_w:
12440 case Intrinsic::x86_sse2_psra_d:
12441 case Intrinsic::x86_avx2_psra_w:
12442 case Intrinsic::x86_avx2_psra_d: {
12445 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12446 case Intrinsic::x86_sse2_psll_w:
12447 case Intrinsic::x86_sse2_psll_d:
12448 case Intrinsic::x86_sse2_psll_q:
12449 case Intrinsic::x86_avx2_psll_w:
12450 case Intrinsic::x86_avx2_psll_d:
12451 case Intrinsic::x86_avx2_psll_q:
12452 Opcode = X86ISD::VSHL;
12454 case Intrinsic::x86_sse2_psrl_w:
12455 case Intrinsic::x86_sse2_psrl_d:
12456 case Intrinsic::x86_sse2_psrl_q:
12457 case Intrinsic::x86_avx2_psrl_w:
12458 case Intrinsic::x86_avx2_psrl_d:
12459 case Intrinsic::x86_avx2_psrl_q:
12460 Opcode = X86ISD::VSRL;
12462 case Intrinsic::x86_sse2_psra_w:
12463 case Intrinsic::x86_sse2_psra_d:
12464 case Intrinsic::x86_avx2_psra_w:
12465 case Intrinsic::x86_avx2_psra_d:
12466 Opcode = X86ISD::VSRA;
12469 return DAG.getNode(Opcode, dl, Op.getValueType(),
12470 Op.getOperand(1), Op.getOperand(2));
12473 // SSE/AVX immediate shift intrinsics
12474 case Intrinsic::x86_sse2_pslli_w:
12475 case Intrinsic::x86_sse2_pslli_d:
12476 case Intrinsic::x86_sse2_pslli_q:
12477 case Intrinsic::x86_avx2_pslli_w:
12478 case Intrinsic::x86_avx2_pslli_d:
12479 case Intrinsic::x86_avx2_pslli_q:
12480 case Intrinsic::x86_sse2_psrli_w:
12481 case Intrinsic::x86_sse2_psrli_d:
12482 case Intrinsic::x86_sse2_psrli_q:
12483 case Intrinsic::x86_avx2_psrli_w:
12484 case Intrinsic::x86_avx2_psrli_d:
12485 case Intrinsic::x86_avx2_psrli_q:
12486 case Intrinsic::x86_sse2_psrai_w:
12487 case Intrinsic::x86_sse2_psrai_d:
12488 case Intrinsic::x86_avx2_psrai_w:
12489 case Intrinsic::x86_avx2_psrai_d: {
12492 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12493 case Intrinsic::x86_sse2_pslli_w:
12494 case Intrinsic::x86_sse2_pslli_d:
12495 case Intrinsic::x86_sse2_pslli_q:
12496 case Intrinsic::x86_avx2_pslli_w:
12497 case Intrinsic::x86_avx2_pslli_d:
12498 case Intrinsic::x86_avx2_pslli_q:
12499 Opcode = X86ISD::VSHLI;
12501 case Intrinsic::x86_sse2_psrli_w:
12502 case Intrinsic::x86_sse2_psrli_d:
12503 case Intrinsic::x86_sse2_psrli_q:
12504 case Intrinsic::x86_avx2_psrli_w:
12505 case Intrinsic::x86_avx2_psrli_d:
12506 case Intrinsic::x86_avx2_psrli_q:
12507 Opcode = X86ISD::VSRLI;
12509 case Intrinsic::x86_sse2_psrai_w:
12510 case Intrinsic::x86_sse2_psrai_d:
12511 case Intrinsic::x86_avx2_psrai_w:
12512 case Intrinsic::x86_avx2_psrai_d:
12513 Opcode = X86ISD::VSRAI;
12516 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12517 Op.getOperand(1), Op.getOperand(2), DAG);
12520 case Intrinsic::x86_sse42_pcmpistria128:
12521 case Intrinsic::x86_sse42_pcmpestria128:
12522 case Intrinsic::x86_sse42_pcmpistric128:
12523 case Intrinsic::x86_sse42_pcmpestric128:
12524 case Intrinsic::x86_sse42_pcmpistrio128:
12525 case Intrinsic::x86_sse42_pcmpestrio128:
12526 case Intrinsic::x86_sse42_pcmpistris128:
12527 case Intrinsic::x86_sse42_pcmpestris128:
12528 case Intrinsic::x86_sse42_pcmpistriz128:
12529 case Intrinsic::x86_sse42_pcmpestriz128: {
12533 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12534 case Intrinsic::x86_sse42_pcmpistria128:
12535 Opcode = X86ISD::PCMPISTRI;
12536 X86CC = X86::COND_A;
12538 case Intrinsic::x86_sse42_pcmpestria128:
12539 Opcode = X86ISD::PCMPESTRI;
12540 X86CC = X86::COND_A;
12542 case Intrinsic::x86_sse42_pcmpistric128:
12543 Opcode = X86ISD::PCMPISTRI;
12544 X86CC = X86::COND_B;
12546 case Intrinsic::x86_sse42_pcmpestric128:
12547 Opcode = X86ISD::PCMPESTRI;
12548 X86CC = X86::COND_B;
12550 case Intrinsic::x86_sse42_pcmpistrio128:
12551 Opcode = X86ISD::PCMPISTRI;
12552 X86CC = X86::COND_O;
12554 case Intrinsic::x86_sse42_pcmpestrio128:
12555 Opcode = X86ISD::PCMPESTRI;
12556 X86CC = X86::COND_O;
12558 case Intrinsic::x86_sse42_pcmpistris128:
12559 Opcode = X86ISD::PCMPISTRI;
12560 X86CC = X86::COND_S;
12562 case Intrinsic::x86_sse42_pcmpestris128:
12563 Opcode = X86ISD::PCMPESTRI;
12564 X86CC = X86::COND_S;
12566 case Intrinsic::x86_sse42_pcmpistriz128:
12567 Opcode = X86ISD::PCMPISTRI;
12568 X86CC = X86::COND_E;
12570 case Intrinsic::x86_sse42_pcmpestriz128:
12571 Opcode = X86ISD::PCMPESTRI;
12572 X86CC = X86::COND_E;
12575 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12576 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12577 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12578 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12579 DAG.getConstant(X86CC, MVT::i8),
12580 SDValue(PCMP.getNode(), 1));
12581 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12584 case Intrinsic::x86_sse42_pcmpistri128:
12585 case Intrinsic::x86_sse42_pcmpestri128: {
12587 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12588 Opcode = X86ISD::PCMPISTRI;
12590 Opcode = X86ISD::PCMPESTRI;
12592 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12593 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12594 return DAG.getNode(Opcode, dl, VTs, NewOps);
12596 case Intrinsic::x86_fma_vfmadd_ps:
12597 case Intrinsic::x86_fma_vfmadd_pd:
12598 case Intrinsic::x86_fma_vfmsub_ps:
12599 case Intrinsic::x86_fma_vfmsub_pd:
12600 case Intrinsic::x86_fma_vfnmadd_ps:
12601 case Intrinsic::x86_fma_vfnmadd_pd:
12602 case Intrinsic::x86_fma_vfnmsub_ps:
12603 case Intrinsic::x86_fma_vfnmsub_pd:
12604 case Intrinsic::x86_fma_vfmaddsub_ps:
12605 case Intrinsic::x86_fma_vfmaddsub_pd:
12606 case Intrinsic::x86_fma_vfmsubadd_ps:
12607 case Intrinsic::x86_fma_vfmsubadd_pd:
12608 case Intrinsic::x86_fma_vfmadd_ps_256:
12609 case Intrinsic::x86_fma_vfmadd_pd_256:
12610 case Intrinsic::x86_fma_vfmsub_ps_256:
12611 case Intrinsic::x86_fma_vfmsub_pd_256:
12612 case Intrinsic::x86_fma_vfnmadd_ps_256:
12613 case Intrinsic::x86_fma_vfnmadd_pd_256:
12614 case Intrinsic::x86_fma_vfnmsub_ps_256:
12615 case Intrinsic::x86_fma_vfnmsub_pd_256:
12616 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12617 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12618 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12619 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12620 case Intrinsic::x86_fma_vfmadd_ps_512:
12621 case Intrinsic::x86_fma_vfmadd_pd_512:
12622 case Intrinsic::x86_fma_vfmsub_ps_512:
12623 case Intrinsic::x86_fma_vfmsub_pd_512:
12624 case Intrinsic::x86_fma_vfnmadd_ps_512:
12625 case Intrinsic::x86_fma_vfnmadd_pd_512:
12626 case Intrinsic::x86_fma_vfnmsub_ps_512:
12627 case Intrinsic::x86_fma_vfnmsub_pd_512:
12628 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12629 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12630 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12631 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12634 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12635 case Intrinsic::x86_fma_vfmadd_ps:
12636 case Intrinsic::x86_fma_vfmadd_pd:
12637 case Intrinsic::x86_fma_vfmadd_ps_256:
12638 case Intrinsic::x86_fma_vfmadd_pd_256:
12639 case Intrinsic::x86_fma_vfmadd_ps_512:
12640 case Intrinsic::x86_fma_vfmadd_pd_512:
12641 Opc = X86ISD::FMADD;
12643 case Intrinsic::x86_fma_vfmsub_ps:
12644 case Intrinsic::x86_fma_vfmsub_pd:
12645 case Intrinsic::x86_fma_vfmsub_ps_256:
12646 case Intrinsic::x86_fma_vfmsub_pd_256:
12647 case Intrinsic::x86_fma_vfmsub_ps_512:
12648 case Intrinsic::x86_fma_vfmsub_pd_512:
12649 Opc = X86ISD::FMSUB;
12651 case Intrinsic::x86_fma_vfnmadd_ps:
12652 case Intrinsic::x86_fma_vfnmadd_pd:
12653 case Intrinsic::x86_fma_vfnmadd_ps_256:
12654 case Intrinsic::x86_fma_vfnmadd_pd_256:
12655 case Intrinsic::x86_fma_vfnmadd_ps_512:
12656 case Intrinsic::x86_fma_vfnmadd_pd_512:
12657 Opc = X86ISD::FNMADD;
12659 case Intrinsic::x86_fma_vfnmsub_ps:
12660 case Intrinsic::x86_fma_vfnmsub_pd:
12661 case Intrinsic::x86_fma_vfnmsub_ps_256:
12662 case Intrinsic::x86_fma_vfnmsub_pd_256:
12663 case Intrinsic::x86_fma_vfnmsub_ps_512:
12664 case Intrinsic::x86_fma_vfnmsub_pd_512:
12665 Opc = X86ISD::FNMSUB;
12667 case Intrinsic::x86_fma_vfmaddsub_ps:
12668 case Intrinsic::x86_fma_vfmaddsub_pd:
12669 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12670 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12671 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12672 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12673 Opc = X86ISD::FMADDSUB;
12675 case Intrinsic::x86_fma_vfmsubadd_ps:
12676 case Intrinsic::x86_fma_vfmsubadd_pd:
12677 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12678 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12679 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12680 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12681 Opc = X86ISD::FMSUBADD;
12685 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12686 Op.getOperand(2), Op.getOperand(3));
12691 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12692 SDValue Src, SDValue Mask, SDValue Base,
12693 SDValue Index, SDValue ScaleOp, SDValue Chain,
12694 const X86Subtarget * Subtarget) {
12696 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12697 assert(C && "Invalid scale type");
12698 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12699 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12700 Index.getSimpleValueType().getVectorNumElements());
12702 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12704 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12706 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12707 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12708 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12709 SDValue Segment = DAG.getRegister(0, MVT::i32);
12710 if (Src.getOpcode() == ISD::UNDEF)
12711 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12712 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12713 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12714 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12715 return DAG.getMergeValues(RetOps, dl);
12718 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12719 SDValue Src, SDValue Mask, SDValue Base,
12720 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12722 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12723 assert(C && "Invalid scale type");
12724 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12725 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12726 SDValue Segment = DAG.getRegister(0, MVT::i32);
12727 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12728 Index.getSimpleValueType().getVectorNumElements());
12730 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12732 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12734 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12735 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12736 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12737 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12738 return SDValue(Res, 1);
12741 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12742 SDValue Mask, SDValue Base, SDValue Index,
12743 SDValue ScaleOp, SDValue Chain) {
12745 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12746 assert(C && "Invalid scale type");
12747 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12748 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12749 SDValue Segment = DAG.getRegister(0, MVT::i32);
12751 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12753 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12755 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12757 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12758 //SDVTList VTs = DAG.getVTList(MVT::Other);
12759 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12760 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12761 return SDValue(Res, 0);
12764 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12765 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12766 // also used to custom lower READCYCLECOUNTER nodes.
12767 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12768 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12769 SmallVectorImpl<SDValue> &Results) {
12770 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12771 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12774 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12775 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12776 // and the EAX register is loaded with the low-order 32 bits.
12777 if (Subtarget->is64Bit()) {
12778 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12779 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12782 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12783 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12786 SDValue Chain = HI.getValue(1);
12788 if (Opcode == X86ISD::RDTSCP_DAG) {
12789 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12791 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12792 // the ECX register. Add 'ecx' explicitly to the chain.
12793 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12795 // Explicitly store the content of ECX at the location passed in input
12796 // to the 'rdtscp' intrinsic.
12797 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12798 MachinePointerInfo(), false, false, 0);
12801 if (Subtarget->is64Bit()) {
12802 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12803 // the EAX register is loaded with the low-order 32 bits.
12804 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12805 DAG.getConstant(32, MVT::i8));
12806 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12807 Results.push_back(Chain);
12811 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12812 SDValue Ops[] = { LO, HI };
12813 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12814 Results.push_back(Pair);
12815 Results.push_back(Chain);
12818 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12819 SelectionDAG &DAG) {
12820 SmallVector<SDValue, 2> Results;
12822 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12824 return DAG.getMergeValues(Results, DL);
12827 enum IntrinsicType {
12828 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12831 struct IntrinsicData {
12832 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12833 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12834 IntrinsicType Type;
12839 std::map < unsigned, IntrinsicData> IntrMap;
12840 static void InitIntinsicsMap() {
12841 static bool Initialized = false;
12844 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12845 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12846 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12847 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12848 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12849 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12850 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12851 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12852 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12853 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12854 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
12855 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12856 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
12857 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12858 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
12859 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12860 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
12861 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12863 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12864 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12865 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
12866 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12867 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
12868 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12869 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
12870 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12871 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
12872 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12873 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
12874 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12875 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
12876 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12877 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
12878 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12880 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
12881 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12882 X86::VGATHERPF1QPSm)));
12883 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
12884 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12885 X86::VGATHERPF1QPDm)));
12886 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
12887 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12888 X86::VGATHERPF1DPDm)));
12889 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
12890 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12891 X86::VGATHERPF1DPSm)));
12892 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
12893 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12894 X86::VSCATTERPF1QPSm)));
12895 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
12896 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12897 X86::VSCATTERPF1QPDm)));
12898 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
12899 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12900 X86::VSCATTERPF1DPDm)));
12901 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
12902 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12903 X86::VSCATTERPF1DPSm)));
12904 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12905 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12906 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12907 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12908 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12909 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12910 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12911 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12912 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12913 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12914 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12915 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12916 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12917 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
12918 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12919 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
12920 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12921 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
12922 Initialized = true;
12925 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12926 SelectionDAG &DAG) {
12927 InitIntinsicsMap();
12928 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12929 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12930 if (itr == IntrMap.end())
12934 IntrinsicData Intr = itr->second;
12935 switch(Intr.Type) {
12938 // Emit the node with the right value type.
12939 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12940 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12942 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12943 // Otherwise return the value from Rand, which is always 0, casted to i32.
12944 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12945 DAG.getConstant(1, Op->getValueType(1)),
12946 DAG.getConstant(X86::COND_B, MVT::i32),
12947 SDValue(Result.getNode(), 1) };
12948 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12949 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12952 // Return { result, isValid, chain }.
12953 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12954 SDValue(Result.getNode(), 2));
12957 //gather(v1, mask, index, base, scale);
12958 SDValue Chain = Op.getOperand(0);
12959 SDValue Src = Op.getOperand(2);
12960 SDValue Base = Op.getOperand(3);
12961 SDValue Index = Op.getOperand(4);
12962 SDValue Mask = Op.getOperand(5);
12963 SDValue Scale = Op.getOperand(6);
12964 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12968 //scatter(base, mask, index, v1, scale);
12969 SDValue Chain = Op.getOperand(0);
12970 SDValue Base = Op.getOperand(2);
12971 SDValue Mask = Op.getOperand(3);
12972 SDValue Index = Op.getOperand(4);
12973 SDValue Src = Op.getOperand(5);
12974 SDValue Scale = Op.getOperand(6);
12975 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12978 SDValue Hint = Op.getOperand(6);
12980 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
12981 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12982 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12983 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12984 SDValue Chain = Op.getOperand(0);
12985 SDValue Mask = Op.getOperand(2);
12986 SDValue Index = Op.getOperand(3);
12987 SDValue Base = Op.getOperand(4);
12988 SDValue Scale = Op.getOperand(5);
12989 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12991 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12993 SmallVector<SDValue, 2> Results;
12994 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12995 return DAG.getMergeValues(Results, dl);
12997 // XTEST intrinsics.
12999 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
13000 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
13001 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13002 DAG.getConstant(X86::COND_NE, MVT::i8),
13004 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
13005 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
13006 Ret, SDValue(InTrans.getNode(), 1));
13009 llvm_unreachable("Unknown Intrinsic Type");
13012 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
13013 SelectionDAG &DAG) const {
13014 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13015 MFI->setReturnAddressIsTaken(true);
13017 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13020 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13022 EVT PtrVT = getPointerTy();
13025 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13026 const X86RegisterInfo *RegInfo =
13027 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13028 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13029 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13030 DAG.getNode(ISD::ADD, dl, PtrVT,
13031 FrameAddr, Offset),
13032 MachinePointerInfo(), false, false, false, 0);
13035 // Just load the return address.
13036 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13037 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13038 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13041 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13042 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13043 MFI->setFrameAddressIsTaken(true);
13045 EVT VT = Op.getValueType();
13046 SDLoc dl(Op); // FIXME probably not meaningful
13047 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13048 const X86RegisterInfo *RegInfo =
13049 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13050 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13051 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13052 (FrameReg == X86::EBP && VT == MVT::i32)) &&
13053 "Invalid Frame Register!");
13054 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13056 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13057 MachinePointerInfo(),
13058 false, false, false, 0);
13062 // FIXME? Maybe this could be a TableGen attribute on some registers and
13063 // this table could be generated automatically from RegInfo.
13064 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13066 unsigned Reg = StringSwitch<unsigned>(RegName)
13067 .Case("esp", X86::ESP)
13068 .Case("rsp", X86::RSP)
13072 report_fatal_error("Invalid register name global variable");
13075 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13076 SelectionDAG &DAG) const {
13077 const X86RegisterInfo *RegInfo =
13078 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13079 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13082 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13083 SDValue Chain = Op.getOperand(0);
13084 SDValue Offset = Op.getOperand(1);
13085 SDValue Handler = Op.getOperand(2);
13088 EVT PtrVT = getPointerTy();
13089 const X86RegisterInfo *RegInfo =
13090 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13091 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13092 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13093 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13094 "Invalid Frame Register!");
13095 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13096 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13098 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13099 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13100 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13101 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13103 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13105 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13106 DAG.getRegister(StoreAddrReg, PtrVT));
13109 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13110 SelectionDAG &DAG) const {
13112 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13113 DAG.getVTList(MVT::i32, MVT::Other),
13114 Op.getOperand(0), Op.getOperand(1));
13117 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13118 SelectionDAG &DAG) const {
13120 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13121 Op.getOperand(0), Op.getOperand(1));
13124 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13125 return Op.getOperand(0);
13128 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13129 SelectionDAG &DAG) const {
13130 SDValue Root = Op.getOperand(0);
13131 SDValue Trmp = Op.getOperand(1); // trampoline
13132 SDValue FPtr = Op.getOperand(2); // nested function
13133 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13136 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13137 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13139 if (Subtarget->is64Bit()) {
13140 SDValue OutChains[6];
13142 // Large code-model.
13143 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
13144 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13146 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13147 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13149 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13151 // Load the pointer to the nested function into R11.
13152 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13153 SDValue Addr = Trmp;
13154 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13155 Addr, MachinePointerInfo(TrmpAddr),
13158 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13159 DAG.getConstant(2, MVT::i64));
13160 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13161 MachinePointerInfo(TrmpAddr, 2),
13164 // Load the 'nest' parameter value into R10.
13165 // R10 is specified in X86CallingConv.td
13166 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13167 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13168 DAG.getConstant(10, MVT::i64));
13169 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13170 Addr, MachinePointerInfo(TrmpAddr, 10),
13173 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13174 DAG.getConstant(12, MVT::i64));
13175 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13176 MachinePointerInfo(TrmpAddr, 12),
13179 // Jump to the nested function.
13180 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13181 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13182 DAG.getConstant(20, MVT::i64));
13183 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13184 Addr, MachinePointerInfo(TrmpAddr, 20),
13187 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13188 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13189 DAG.getConstant(22, MVT::i64));
13190 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13191 MachinePointerInfo(TrmpAddr, 22),
13194 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13196 const Function *Func =
13197 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13198 CallingConv::ID CC = Func->getCallingConv();
13203 llvm_unreachable("Unsupported calling convention");
13204 case CallingConv::C:
13205 case CallingConv::X86_StdCall: {
13206 // Pass 'nest' parameter in ECX.
13207 // Must be kept in sync with X86CallingConv.td
13208 NestReg = X86::ECX;
13210 // Check that ECX wasn't needed by an 'inreg' parameter.
13211 FunctionType *FTy = Func->getFunctionType();
13212 const AttributeSet &Attrs = Func->getAttributes();
13214 if (!Attrs.isEmpty() && !Func->isVarArg()) {
13215 unsigned InRegCount = 0;
13218 for (FunctionType::param_iterator I = FTy->param_begin(),
13219 E = FTy->param_end(); I != E; ++I, ++Idx)
13220 if (Attrs.hasAttribute(Idx, Attribute::InReg))
13221 // FIXME: should only count parameters that are lowered to integers.
13222 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13224 if (InRegCount > 2) {
13225 report_fatal_error("Nest register in use - reduce number of inreg"
13231 case CallingConv::X86_FastCall:
13232 case CallingConv::X86_ThisCall:
13233 case CallingConv::Fast:
13234 // Pass 'nest' parameter in EAX.
13235 // Must be kept in sync with X86CallingConv.td
13236 NestReg = X86::EAX;
13240 SDValue OutChains[4];
13241 SDValue Addr, Disp;
13243 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13244 DAG.getConstant(10, MVT::i32));
13245 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13247 // This is storing the opcode for MOV32ri.
13248 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13249 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13250 OutChains[0] = DAG.getStore(Root, dl,
13251 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13252 Trmp, MachinePointerInfo(TrmpAddr),
13255 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13256 DAG.getConstant(1, MVT::i32));
13257 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13258 MachinePointerInfo(TrmpAddr, 1),
13261 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13262 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13263 DAG.getConstant(5, MVT::i32));
13264 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13265 MachinePointerInfo(TrmpAddr, 5),
13268 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13269 DAG.getConstant(6, MVT::i32));
13270 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13271 MachinePointerInfo(TrmpAddr, 6),
13274 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13278 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13279 SelectionDAG &DAG) const {
13281 The rounding mode is in bits 11:10 of FPSR, and has the following
13283 00 Round to nearest
13288 FLT_ROUNDS, on the other hand, expects the following:
13295 To perform the conversion, we do:
13296 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13299 MachineFunction &MF = DAG.getMachineFunction();
13300 const TargetMachine &TM = MF.getTarget();
13301 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13302 unsigned StackAlignment = TFI.getStackAlignment();
13303 MVT VT = Op.getSimpleValueType();
13306 // Save FP Control Word to stack slot
13307 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13308 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13310 MachineMemOperand *MMO =
13311 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13312 MachineMemOperand::MOStore, 2, 2);
13314 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13315 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13316 DAG.getVTList(MVT::Other),
13317 Ops, MVT::i16, MMO);
13319 // Load FP Control Word from stack slot
13320 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13321 MachinePointerInfo(), false, false, false, 0);
13323 // Transform as necessary
13325 DAG.getNode(ISD::SRL, DL, MVT::i16,
13326 DAG.getNode(ISD::AND, DL, MVT::i16,
13327 CWD, DAG.getConstant(0x800, MVT::i16)),
13328 DAG.getConstant(11, MVT::i8));
13330 DAG.getNode(ISD::SRL, DL, MVT::i16,
13331 DAG.getNode(ISD::AND, DL, MVT::i16,
13332 CWD, DAG.getConstant(0x400, MVT::i16)),
13333 DAG.getConstant(9, MVT::i8));
13336 DAG.getNode(ISD::AND, DL, MVT::i16,
13337 DAG.getNode(ISD::ADD, DL, MVT::i16,
13338 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13339 DAG.getConstant(1, MVT::i16)),
13340 DAG.getConstant(3, MVT::i16));
13342 return DAG.getNode((VT.getSizeInBits() < 16 ?
13343 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13346 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13347 MVT VT = Op.getSimpleValueType();
13349 unsigned NumBits = VT.getSizeInBits();
13352 Op = Op.getOperand(0);
13353 if (VT == MVT::i8) {
13354 // Zero extend to i32 since there is not an i8 bsr.
13356 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13359 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13360 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13361 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13363 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13366 DAG.getConstant(NumBits+NumBits-1, OpVT),
13367 DAG.getConstant(X86::COND_E, MVT::i8),
13370 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13372 // Finally xor with NumBits-1.
13373 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13376 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13380 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13381 MVT VT = Op.getSimpleValueType();
13383 unsigned NumBits = VT.getSizeInBits();
13386 Op = Op.getOperand(0);
13387 if (VT == MVT::i8) {
13388 // Zero extend to i32 since there is not an i8 bsr.
13390 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13393 // Issue a bsr (scan bits in reverse).
13394 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13395 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13397 // And xor with NumBits-1.
13398 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13401 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13405 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13406 MVT VT = Op.getSimpleValueType();
13407 unsigned NumBits = VT.getSizeInBits();
13409 Op = Op.getOperand(0);
13411 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13412 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13413 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13415 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13418 DAG.getConstant(NumBits, VT),
13419 DAG.getConstant(X86::COND_E, MVT::i8),
13422 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13425 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13426 // ones, and then concatenate the result back.
13427 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13428 MVT VT = Op.getSimpleValueType();
13430 assert(VT.is256BitVector() && VT.isInteger() &&
13431 "Unsupported value type for operation");
13433 unsigned NumElems = VT.getVectorNumElements();
13436 // Extract the LHS vectors
13437 SDValue LHS = Op.getOperand(0);
13438 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13439 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13441 // Extract the RHS vectors
13442 SDValue RHS = Op.getOperand(1);
13443 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13444 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13446 MVT EltVT = VT.getVectorElementType();
13447 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13449 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13450 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13451 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13454 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13455 assert(Op.getSimpleValueType().is256BitVector() &&
13456 Op.getSimpleValueType().isInteger() &&
13457 "Only handle AVX 256-bit vector integer operation");
13458 return Lower256IntArith(Op, DAG);
13461 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13462 assert(Op.getSimpleValueType().is256BitVector() &&
13463 Op.getSimpleValueType().isInteger() &&
13464 "Only handle AVX 256-bit vector integer operation");
13465 return Lower256IntArith(Op, DAG);
13468 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13469 SelectionDAG &DAG) {
13471 MVT VT = Op.getSimpleValueType();
13473 // Decompose 256-bit ops into smaller 128-bit ops.
13474 if (VT.is256BitVector() && !Subtarget->hasInt256())
13475 return Lower256IntArith(Op, DAG);
13477 SDValue A = Op.getOperand(0);
13478 SDValue B = Op.getOperand(1);
13480 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13481 if (VT == MVT::v4i32) {
13482 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13483 "Should not custom lower when pmuldq is available!");
13485 // Extract the odd parts.
13486 static const int UnpackMask[] = { 1, -1, 3, -1 };
13487 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13488 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13490 // Multiply the even parts.
13491 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13492 // Now multiply odd parts.
13493 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13495 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13496 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13498 // Merge the two vectors back together with a shuffle. This expands into 2
13500 static const int ShufMask[] = { 0, 4, 2, 6 };
13501 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13504 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13505 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13507 // Ahi = psrlqi(a, 32);
13508 // Bhi = psrlqi(b, 32);
13510 // AloBlo = pmuludq(a, b);
13511 // AloBhi = pmuludq(a, Bhi);
13512 // AhiBlo = pmuludq(Ahi, b);
13514 // AloBhi = psllqi(AloBhi, 32);
13515 // AhiBlo = psllqi(AhiBlo, 32);
13516 // return AloBlo + AloBhi + AhiBlo;
13518 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13519 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13521 // Bit cast to 32-bit vectors for MULUDQ
13522 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13523 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13524 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13525 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13526 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13527 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13529 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13530 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13531 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13533 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13534 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13536 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13537 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13540 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13541 assert(Subtarget->isTargetWin64() && "Unexpected target");
13542 EVT VT = Op.getValueType();
13543 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13544 "Unexpected return type for lowering");
13548 switch (Op->getOpcode()) {
13549 default: llvm_unreachable("Unexpected request for libcall!");
13550 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13551 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13552 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13553 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13554 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13555 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13559 SDValue InChain = DAG.getEntryNode();
13561 TargetLowering::ArgListTy Args;
13562 TargetLowering::ArgListEntry Entry;
13563 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13564 EVT ArgVT = Op->getOperand(i).getValueType();
13565 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13566 "Unexpected argument type for lowering");
13567 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13568 Entry.Node = StackPtr;
13569 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13571 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13572 Entry.Ty = PointerType::get(ArgTy,0);
13573 Entry.isSExt = false;
13574 Entry.isZExt = false;
13575 Args.push_back(Entry);
13578 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13581 TargetLowering::CallLoweringInfo CLI(DAG);
13582 CLI.setDebugLoc(dl).setChain(InChain)
13583 .setCallee(getLibcallCallingConv(LC),
13584 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13586 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13588 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13589 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13592 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13593 SelectionDAG &DAG) {
13594 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13595 EVT VT = Op0.getValueType();
13598 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13599 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13601 // Get the high parts.
13602 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13603 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13604 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13606 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13608 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13609 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13611 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13612 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13613 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13614 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13615 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13617 // Shuffle it back into the right order.
13618 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13619 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13620 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13621 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13623 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13624 // unsigned multiply.
13625 if (IsSigned && !Subtarget->hasSSE41()) {
13627 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13628 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13629 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13630 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13631 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13633 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13634 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13637 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13640 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13641 const X86Subtarget *Subtarget) {
13642 MVT VT = Op.getSimpleValueType();
13644 SDValue R = Op.getOperand(0);
13645 SDValue Amt = Op.getOperand(1);
13647 // Optimize shl/srl/sra with constant shift amount.
13648 if (isSplatVector(Amt.getNode())) {
13649 SDValue SclrAmt = Amt->getOperand(0);
13650 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13651 uint64_t ShiftAmt = C->getZExtValue();
13653 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13654 (Subtarget->hasInt256() &&
13655 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13656 (Subtarget->hasAVX512() &&
13657 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13658 if (Op.getOpcode() == ISD::SHL)
13659 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13661 if (Op.getOpcode() == ISD::SRL)
13662 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13664 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13665 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13669 if (VT == MVT::v16i8) {
13670 if (Op.getOpcode() == ISD::SHL) {
13671 // Make a large shift.
13672 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13673 MVT::v8i16, R, ShiftAmt,
13675 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13676 // Zero out the rightmost bits.
13677 SmallVector<SDValue, 16> V(16,
13678 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13680 return DAG.getNode(ISD::AND, dl, VT, SHL,
13681 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13683 if (Op.getOpcode() == ISD::SRL) {
13684 // Make a large shift.
13685 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13686 MVT::v8i16, R, ShiftAmt,
13688 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13689 // Zero out the leftmost bits.
13690 SmallVector<SDValue, 16> V(16,
13691 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13693 return DAG.getNode(ISD::AND, dl, VT, SRL,
13694 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13696 if (Op.getOpcode() == ISD::SRA) {
13697 if (ShiftAmt == 7) {
13698 // R s>> 7 === R s< 0
13699 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13700 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13703 // R s>> a === ((R u>> a) ^ m) - m
13704 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13705 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13707 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13708 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13709 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13712 llvm_unreachable("Unknown shift opcode.");
13715 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13716 if (Op.getOpcode() == ISD::SHL) {
13717 // Make a large shift.
13718 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13719 MVT::v16i16, R, ShiftAmt,
13721 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13722 // Zero out the rightmost bits.
13723 SmallVector<SDValue, 32> V(32,
13724 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13726 return DAG.getNode(ISD::AND, dl, VT, SHL,
13727 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13729 if (Op.getOpcode() == ISD::SRL) {
13730 // Make a large shift.
13731 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13732 MVT::v16i16, R, ShiftAmt,
13734 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13735 // Zero out the leftmost bits.
13736 SmallVector<SDValue, 32> V(32,
13737 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13739 return DAG.getNode(ISD::AND, dl, VT, SRL,
13740 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13742 if (Op.getOpcode() == ISD::SRA) {
13743 if (ShiftAmt == 7) {
13744 // R s>> 7 === R s< 0
13745 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13746 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13749 // R s>> a === ((R u>> a) ^ m) - m
13750 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13751 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13753 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13754 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13755 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13758 llvm_unreachable("Unknown shift opcode.");
13763 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13764 if (!Subtarget->is64Bit() &&
13765 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13766 Amt.getOpcode() == ISD::BITCAST &&
13767 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13768 Amt = Amt.getOperand(0);
13769 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13770 VT.getVectorNumElements();
13771 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13772 uint64_t ShiftAmt = 0;
13773 for (unsigned i = 0; i != Ratio; ++i) {
13774 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13778 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13780 // Check remaining shift amounts.
13781 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13782 uint64_t ShAmt = 0;
13783 for (unsigned j = 0; j != Ratio; ++j) {
13784 ConstantSDNode *C =
13785 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13789 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13791 if (ShAmt != ShiftAmt)
13794 switch (Op.getOpcode()) {
13796 llvm_unreachable("Unknown shift opcode!");
13798 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13801 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13804 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13812 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13813 const X86Subtarget* Subtarget) {
13814 MVT VT = Op.getSimpleValueType();
13816 SDValue R = Op.getOperand(0);
13817 SDValue Amt = Op.getOperand(1);
13819 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13820 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13821 (Subtarget->hasInt256() &&
13822 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13823 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13824 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13826 EVT EltVT = VT.getVectorElementType();
13828 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13829 unsigned NumElts = VT.getVectorNumElements();
13831 for (i = 0; i != NumElts; ++i) {
13832 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13836 for (j = i; j != NumElts; ++j) {
13837 SDValue Arg = Amt.getOperand(j);
13838 if (Arg.getOpcode() == ISD::UNDEF) continue;
13839 if (Arg != Amt.getOperand(i))
13842 if (i != NumElts && j == NumElts)
13843 BaseShAmt = Amt.getOperand(i);
13845 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13846 Amt = Amt.getOperand(0);
13847 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13848 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13849 SDValue InVec = Amt.getOperand(0);
13850 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13851 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13853 for (; i != NumElts; ++i) {
13854 SDValue Arg = InVec.getOperand(i);
13855 if (Arg.getOpcode() == ISD::UNDEF) continue;
13859 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13860 if (ConstantSDNode *C =
13861 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13862 unsigned SplatIdx =
13863 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13864 if (C->getZExtValue() == SplatIdx)
13865 BaseShAmt = InVec.getOperand(1);
13868 if (!BaseShAmt.getNode())
13869 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13870 DAG.getIntPtrConstant(0));
13874 if (BaseShAmt.getNode()) {
13875 if (EltVT.bitsGT(MVT::i32))
13876 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13877 else if (EltVT.bitsLT(MVT::i32))
13878 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13880 switch (Op.getOpcode()) {
13882 llvm_unreachable("Unknown shift opcode!");
13884 switch (VT.SimpleTy) {
13885 default: return SDValue();
13894 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13897 switch (VT.SimpleTy) {
13898 default: return SDValue();
13905 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13908 switch (VT.SimpleTy) {
13909 default: return SDValue();
13918 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13924 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13925 if (!Subtarget->is64Bit() &&
13926 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13927 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13928 Amt.getOpcode() == ISD::BITCAST &&
13929 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13930 Amt = Amt.getOperand(0);
13931 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13932 VT.getVectorNumElements();
13933 std::vector<SDValue> Vals(Ratio);
13934 for (unsigned i = 0; i != Ratio; ++i)
13935 Vals[i] = Amt.getOperand(i);
13936 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13937 for (unsigned j = 0; j != Ratio; ++j)
13938 if (Vals[j] != Amt.getOperand(i + j))
13941 switch (Op.getOpcode()) {
13943 llvm_unreachable("Unknown shift opcode!");
13945 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13947 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13949 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13956 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13957 SelectionDAG &DAG) {
13959 MVT VT = Op.getSimpleValueType();
13961 SDValue R = Op.getOperand(0);
13962 SDValue Amt = Op.getOperand(1);
13965 if (!Subtarget->hasSSE2())
13968 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13972 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13976 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13978 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13979 if (Subtarget->hasInt256()) {
13980 if (Op.getOpcode() == ISD::SRL &&
13981 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13982 VT == MVT::v4i64 || VT == MVT::v8i32))
13984 if (Op.getOpcode() == ISD::SHL &&
13985 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13986 VT == MVT::v4i64 || VT == MVT::v8i32))
13988 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13992 // If possible, lower this packed shift into a vector multiply instead of
13993 // expanding it into a sequence of scalar shifts.
13994 // Do this only if the vector shift count is a constant build_vector.
13995 if (Op.getOpcode() == ISD::SHL &&
13996 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13997 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13998 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13999 SmallVector<SDValue, 8> Elts;
14000 EVT SVT = VT.getScalarType();
14001 unsigned SVTBits = SVT.getSizeInBits();
14002 const APInt &One = APInt(SVTBits, 1);
14003 unsigned NumElems = VT.getVectorNumElements();
14005 for (unsigned i=0; i !=NumElems; ++i) {
14006 SDValue Op = Amt->getOperand(i);
14007 if (Op->getOpcode() == ISD::UNDEF) {
14008 Elts.push_back(Op);
14012 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
14013 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
14014 uint64_t ShAmt = C.getZExtValue();
14015 if (ShAmt >= SVTBits) {
14016 Elts.push_back(DAG.getUNDEF(SVT));
14019 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14021 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14022 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14025 // Lower SHL with variable shift amount.
14026 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14027 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14029 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14030 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14031 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14032 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14035 // If possible, lower this shift as a sequence of two shifts by
14036 // constant plus a MOVSS/MOVSD instead of scalarizing it.
14038 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14040 // Could be rewritten as:
14041 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14043 // The advantage is that the two shifts from the example would be
14044 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14045 // the vector shift into four scalar shifts plus four pairs of vector
14047 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14048 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14049 unsigned TargetOpcode = X86ISD::MOVSS;
14050 bool CanBeSimplified;
14051 // The splat value for the first packed shift (the 'X' from the example).
14052 SDValue Amt1 = Amt->getOperand(0);
14053 // The splat value for the second packed shift (the 'Y' from the example).
14054 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14055 Amt->getOperand(2);
14057 // See if it is possible to replace this node with a sequence of
14058 // two shifts followed by a MOVSS/MOVSD
14059 if (VT == MVT::v4i32) {
14060 // Check if it is legal to use a MOVSS.
14061 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14062 Amt2 == Amt->getOperand(3);
14063 if (!CanBeSimplified) {
14064 // Otherwise, check if we can still simplify this node using a MOVSD.
14065 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14066 Amt->getOperand(2) == Amt->getOperand(3);
14067 TargetOpcode = X86ISD::MOVSD;
14068 Amt2 = Amt->getOperand(2);
14071 // Do similar checks for the case where the machine value type
14073 CanBeSimplified = Amt1 == Amt->getOperand(1);
14074 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14075 CanBeSimplified = Amt2 == Amt->getOperand(i);
14077 if (!CanBeSimplified) {
14078 TargetOpcode = X86ISD::MOVSD;
14079 CanBeSimplified = true;
14080 Amt2 = Amt->getOperand(4);
14081 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14082 CanBeSimplified = Amt1 == Amt->getOperand(i);
14083 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14084 CanBeSimplified = Amt2 == Amt->getOperand(j);
14088 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14089 isa<ConstantSDNode>(Amt2)) {
14090 // Replace this node with two shifts followed by a MOVSS/MOVSD.
14091 EVT CastVT = MVT::v4i32;
14093 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14094 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14096 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14097 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14098 if (TargetOpcode == X86ISD::MOVSD)
14099 CastVT = MVT::v2i64;
14100 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14101 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14102 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14104 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14108 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14109 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14112 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14113 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14115 // Turn 'a' into a mask suitable for VSELECT
14116 SDValue VSelM = DAG.getConstant(0x80, VT);
14117 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14118 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14120 SDValue CM1 = DAG.getConstant(0x0f, VT);
14121 SDValue CM2 = DAG.getConstant(0x3f, VT);
14123 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14124 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14125 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14126 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14127 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14130 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14131 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14132 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14134 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14135 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14136 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14137 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14138 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14141 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14142 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14143 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14145 // return VSELECT(r, r+r, a);
14146 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14147 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14151 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14152 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14153 // solution better.
14154 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14155 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14157 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14158 R = DAG.getNode(ExtOpc, dl, NewVT, R);
14159 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14160 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14161 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14164 // Decompose 256-bit shifts into smaller 128-bit shifts.
14165 if (VT.is256BitVector()) {
14166 unsigned NumElems = VT.getVectorNumElements();
14167 MVT EltVT = VT.getVectorElementType();
14168 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14170 // Extract the two vectors
14171 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14172 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14174 // Recreate the shift amount vectors
14175 SDValue Amt1, Amt2;
14176 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14177 // Constant shift amount
14178 SmallVector<SDValue, 4> Amt1Csts;
14179 SmallVector<SDValue, 4> Amt2Csts;
14180 for (unsigned i = 0; i != NumElems/2; ++i)
14181 Amt1Csts.push_back(Amt->getOperand(i));
14182 for (unsigned i = NumElems/2; i != NumElems; ++i)
14183 Amt2Csts.push_back(Amt->getOperand(i));
14185 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14186 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14188 // Variable shift amount
14189 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14190 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14193 // Issue new vector shifts for the smaller types
14194 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14195 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14197 // Concatenate the result back
14198 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14204 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14205 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14206 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14207 // looks for this combo and may remove the "setcc" instruction if the "setcc"
14208 // has only one use.
14209 SDNode *N = Op.getNode();
14210 SDValue LHS = N->getOperand(0);
14211 SDValue RHS = N->getOperand(1);
14212 unsigned BaseOp = 0;
14215 switch (Op.getOpcode()) {
14216 default: llvm_unreachable("Unknown ovf instruction!");
14218 // A subtract of one will be selected as a INC. Note that INC doesn't
14219 // set CF, so we can't do this for UADDO.
14220 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14222 BaseOp = X86ISD::INC;
14223 Cond = X86::COND_O;
14226 BaseOp = X86ISD::ADD;
14227 Cond = X86::COND_O;
14230 BaseOp = X86ISD::ADD;
14231 Cond = X86::COND_B;
14234 // A subtract of one will be selected as a DEC. Note that DEC doesn't
14235 // set CF, so we can't do this for USUBO.
14236 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14238 BaseOp = X86ISD::DEC;
14239 Cond = X86::COND_O;
14242 BaseOp = X86ISD::SUB;
14243 Cond = X86::COND_O;
14246 BaseOp = X86ISD::SUB;
14247 Cond = X86::COND_B;
14250 BaseOp = X86ISD::SMUL;
14251 Cond = X86::COND_O;
14253 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14254 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14256 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14259 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14260 DAG.getConstant(X86::COND_O, MVT::i32),
14261 SDValue(Sum.getNode(), 2));
14263 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14267 // Also sets EFLAGS.
14268 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14269 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14272 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14273 DAG.getConstant(Cond, MVT::i32),
14274 SDValue(Sum.getNode(), 1));
14276 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14279 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14280 SelectionDAG &DAG) const {
14282 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14283 MVT VT = Op.getSimpleValueType();
14285 if (!Subtarget->hasSSE2() || !VT.isVector())
14288 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14289 ExtraVT.getScalarType().getSizeInBits();
14291 switch (VT.SimpleTy) {
14292 default: return SDValue();
14295 if (!Subtarget->hasFp256())
14297 if (!Subtarget->hasInt256()) {
14298 // needs to be split
14299 unsigned NumElems = VT.getVectorNumElements();
14301 // Extract the LHS vectors
14302 SDValue LHS = Op.getOperand(0);
14303 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14304 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14306 MVT EltVT = VT.getVectorElementType();
14307 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14309 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14310 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14311 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14313 SDValue Extra = DAG.getValueType(ExtraVT);
14315 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14316 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14318 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14323 SDValue Op0 = Op.getOperand(0);
14324 SDValue Op00 = Op0.getOperand(0);
14326 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14327 if (Op0.getOpcode() == ISD::BITCAST &&
14328 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14329 // (sext (vzext x)) -> (vsext x)
14330 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14331 if (Tmp1.getNode()) {
14332 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14333 // This folding is only valid when the in-reg type is a vector of i8,
14335 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14336 ExtraEltVT == MVT::i32) {
14337 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14338 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14339 "This optimization is invalid without a VZEXT.");
14340 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14346 // If the above didn't work, then just use Shift-Left + Shift-Right.
14347 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14349 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14355 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14356 SelectionDAG &DAG) {
14358 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14359 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14360 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14361 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14363 // The only fence that needs an instruction is a sequentially-consistent
14364 // cross-thread fence.
14365 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14366 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14367 // no-sse2). There isn't any reason to disable it if the target processor
14369 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14370 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14372 SDValue Chain = Op.getOperand(0);
14373 SDValue Zero = DAG.getConstant(0, MVT::i32);
14375 DAG.getRegister(X86::ESP, MVT::i32), // Base
14376 DAG.getTargetConstant(1, MVT::i8), // Scale
14377 DAG.getRegister(0, MVT::i32), // Index
14378 DAG.getTargetConstant(0, MVT::i32), // Disp
14379 DAG.getRegister(0, MVT::i32), // Segment.
14383 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14384 return SDValue(Res, 0);
14387 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14388 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14391 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14392 SelectionDAG &DAG) {
14393 MVT T = Op.getSimpleValueType();
14397 switch(T.SimpleTy) {
14398 default: llvm_unreachable("Invalid value type!");
14399 case MVT::i8: Reg = X86::AL; size = 1; break;
14400 case MVT::i16: Reg = X86::AX; size = 2; break;
14401 case MVT::i32: Reg = X86::EAX; size = 4; break;
14403 assert(Subtarget->is64Bit() && "Node not type legal!");
14404 Reg = X86::RAX; size = 8;
14407 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14408 Op.getOperand(2), SDValue());
14409 SDValue Ops[] = { cpIn.getValue(0),
14412 DAG.getTargetConstant(size, MVT::i8),
14413 cpIn.getValue(1) };
14414 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14415 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14416 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14419 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14423 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14424 SelectionDAG &DAG) {
14425 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14426 MVT DstVT = Op.getSimpleValueType();
14428 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14429 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14430 if (DstVT != MVT::f64)
14431 // This conversion needs to be expanded.
14434 SDValue InVec = Op->getOperand(0);
14436 unsigned NumElts = SrcVT.getVectorNumElements();
14437 EVT SVT = SrcVT.getVectorElementType();
14439 // Widen the vector in input in the case of MVT::v2i32.
14440 // Example: from MVT::v2i32 to MVT::v4i32.
14441 SmallVector<SDValue, 16> Elts;
14442 for (unsigned i = 0, e = NumElts; i != e; ++i)
14443 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14444 DAG.getIntPtrConstant(i)));
14446 // Explicitly mark the extra elements as Undef.
14447 SDValue Undef = DAG.getUNDEF(SVT);
14448 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14449 Elts.push_back(Undef);
14451 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14452 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14453 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14454 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14455 DAG.getIntPtrConstant(0));
14458 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14459 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14460 assert((DstVT == MVT::i64 ||
14461 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14462 "Unexpected custom BITCAST");
14463 // i64 <=> MMX conversions are Legal.
14464 if (SrcVT==MVT::i64 && DstVT.isVector())
14466 if (DstVT==MVT::i64 && SrcVT.isVector())
14468 // MMX <=> MMX conversions are Legal.
14469 if (SrcVT.isVector() && DstVT.isVector())
14471 // All other conversions need to be expanded.
14475 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14476 SDNode *Node = Op.getNode();
14478 EVT T = Node->getValueType(0);
14479 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14480 DAG.getConstant(0, T), Node->getOperand(2));
14481 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14482 cast<AtomicSDNode>(Node)->getMemoryVT(),
14483 Node->getOperand(0),
14484 Node->getOperand(1), negOp,
14485 cast<AtomicSDNode>(Node)->getMemOperand(),
14486 cast<AtomicSDNode>(Node)->getOrdering(),
14487 cast<AtomicSDNode>(Node)->getSynchScope());
14490 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14491 SDNode *Node = Op.getNode();
14493 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14495 // Convert seq_cst store -> xchg
14496 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14497 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14498 // (The only way to get a 16-byte store is cmpxchg16b)
14499 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14500 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14501 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14502 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14503 cast<AtomicSDNode>(Node)->getMemoryVT(),
14504 Node->getOperand(0),
14505 Node->getOperand(1), Node->getOperand(2),
14506 cast<AtomicSDNode>(Node)->getMemOperand(),
14507 cast<AtomicSDNode>(Node)->getOrdering(),
14508 cast<AtomicSDNode>(Node)->getSynchScope());
14509 return Swap.getValue(1);
14511 // Other atomic stores have a simple pattern.
14515 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14516 EVT VT = Op.getNode()->getSimpleValueType(0);
14518 // Let legalize expand this if it isn't a legal type yet.
14519 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14522 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14525 bool ExtraOp = false;
14526 switch (Op.getOpcode()) {
14527 default: llvm_unreachable("Invalid code");
14528 case ISD::ADDC: Opc = X86ISD::ADD; break;
14529 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14530 case ISD::SUBC: Opc = X86ISD::SUB; break;
14531 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14535 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14537 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14538 Op.getOperand(1), Op.getOperand(2));
14541 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14542 SelectionDAG &DAG) {
14543 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14545 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14546 // which returns the values as { float, float } (in XMM0) or
14547 // { double, double } (which is returned in XMM0, XMM1).
14549 SDValue Arg = Op.getOperand(0);
14550 EVT ArgVT = Arg.getValueType();
14551 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14553 TargetLowering::ArgListTy Args;
14554 TargetLowering::ArgListEntry Entry;
14558 Entry.isSExt = false;
14559 Entry.isZExt = false;
14560 Args.push_back(Entry);
14562 bool isF64 = ArgVT == MVT::f64;
14563 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14564 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14565 // the results are returned via SRet in memory.
14566 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14567 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14568 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14570 Type *RetTy = isF64
14571 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14572 : (Type*)VectorType::get(ArgTy, 4);
14574 TargetLowering::CallLoweringInfo CLI(DAG);
14575 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14576 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14578 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14581 // Returned in xmm0 and xmm1.
14582 return CallResult.first;
14584 // Returned in bits 0:31 and 32:64 xmm0.
14585 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14586 CallResult.first, DAG.getIntPtrConstant(0));
14587 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14588 CallResult.first, DAG.getIntPtrConstant(1));
14589 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14590 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14593 /// LowerOperation - Provide custom lowering hooks for some operations.
14595 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14596 switch (Op.getOpcode()) {
14597 default: llvm_unreachable("Should not custom lower this!");
14598 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14599 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14600 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14601 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14602 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14603 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14604 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14605 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14606 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
14607 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14608 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14609 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14610 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14611 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14612 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14613 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14614 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14615 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14616 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14617 case ISD::SHL_PARTS:
14618 case ISD::SRA_PARTS:
14619 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14620 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14621 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14622 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14623 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14624 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14625 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14626 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14627 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14628 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14629 case ISD::FABS: return LowerFABS(Op, DAG);
14630 case ISD::FNEG: return LowerFNEG(Op, DAG);
14631 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14632 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14633 case ISD::SETCC: return LowerSETCC(Op, DAG);
14634 case ISD::SELECT: return LowerSELECT(Op, DAG);
14635 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14636 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14637 case ISD::VASTART: return LowerVASTART(Op, DAG);
14638 case ISD::VAARG: return LowerVAARG(Op, DAG);
14639 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14640 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14641 case ISD::INTRINSIC_VOID:
14642 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14643 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14644 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14645 case ISD::FRAME_TO_ARGS_OFFSET:
14646 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14647 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14648 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14649 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14650 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14651 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14652 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14653 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14654 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14655 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14656 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14657 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14658 case ISD::UMUL_LOHI:
14659 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14662 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14668 case ISD::UMULO: return LowerXALUO(Op, DAG);
14669 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14670 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14674 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14675 case ISD::ADD: return LowerADD(Op, DAG);
14676 case ISD::SUB: return LowerSUB(Op, DAG);
14677 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14681 static void ReplaceATOMIC_LOAD(SDNode *Node,
14682 SmallVectorImpl<SDValue> &Results,
14683 SelectionDAG &DAG) {
14685 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14687 // Convert wide load -> cmpxchg8b/cmpxchg16b
14688 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14689 // (The only way to get a 16-byte load is cmpxchg16b)
14690 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14691 SDValue Zero = DAG.getConstant(0, VT);
14692 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14693 Node->getOperand(0),
14694 Node->getOperand(1), Zero, Zero,
14695 cast<AtomicSDNode>(Node)->getMemOperand(),
14696 cast<AtomicSDNode>(Node)->getOrdering(),
14697 cast<AtomicSDNode>(Node)->getOrdering(),
14698 cast<AtomicSDNode>(Node)->getSynchScope());
14699 Results.push_back(Swap.getValue(0));
14700 Results.push_back(Swap.getValue(1));
14704 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14705 SelectionDAG &DAG, unsigned NewOp) {
14707 assert (Node->getValueType(0) == MVT::i64 &&
14708 "Only know how to expand i64 atomics");
14710 SDValue Chain = Node->getOperand(0);
14711 SDValue In1 = Node->getOperand(1);
14712 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14713 Node->getOperand(2), DAG.getIntPtrConstant(0));
14714 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14715 Node->getOperand(2), DAG.getIntPtrConstant(1));
14716 SDValue Ops[] = { Chain, In1, In2L, In2H };
14717 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14719 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14720 cast<MemSDNode>(Node)->getMemOperand());
14721 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14722 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14723 Results.push_back(Result.getValue(2));
14726 /// ReplaceNodeResults - Replace a node with an illegal result type
14727 /// with a new node built out of custom code.
14728 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14729 SmallVectorImpl<SDValue>&Results,
14730 SelectionDAG &DAG) const {
14732 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14733 switch (N->getOpcode()) {
14735 llvm_unreachable("Do not know how to custom type legalize this operation!");
14736 case ISD::SIGN_EXTEND_INREG:
14741 // We don't want to expand or promote these.
14748 case ISD::UDIVREM: {
14749 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14750 Results.push_back(V);
14753 case ISD::FP_TO_SINT:
14754 case ISD::FP_TO_UINT: {
14755 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14757 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14760 std::pair<SDValue,SDValue> Vals =
14761 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14762 SDValue FIST = Vals.first, StackSlot = Vals.second;
14763 if (FIST.getNode()) {
14764 EVT VT = N->getValueType(0);
14765 // Return a load from the stack slot.
14766 if (StackSlot.getNode())
14767 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14768 MachinePointerInfo(),
14769 false, false, false, 0));
14771 Results.push_back(FIST);
14775 case ISD::UINT_TO_FP: {
14776 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14777 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14778 N->getValueType(0) != MVT::v2f32)
14780 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14782 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14784 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14785 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14786 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14787 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14788 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14789 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14792 case ISD::FP_ROUND: {
14793 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14795 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14796 Results.push_back(V);
14799 case ISD::INTRINSIC_W_CHAIN: {
14800 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14802 default : llvm_unreachable("Do not know how to custom type "
14803 "legalize this intrinsic operation!");
14804 case Intrinsic::x86_rdtsc:
14805 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14807 case Intrinsic::x86_rdtscp:
14808 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14812 case ISD::READCYCLECOUNTER: {
14813 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14816 case ISD::ATOMIC_CMP_SWAP: {
14817 EVT T = N->getValueType(0);
14818 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14819 bool Regs64bit = T == MVT::i128;
14820 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14821 SDValue cpInL, cpInH;
14822 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14823 DAG.getConstant(0, HalfT));
14824 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14825 DAG.getConstant(1, HalfT));
14826 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14827 Regs64bit ? X86::RAX : X86::EAX,
14829 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14830 Regs64bit ? X86::RDX : X86::EDX,
14831 cpInH, cpInL.getValue(1));
14832 SDValue swapInL, swapInH;
14833 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14834 DAG.getConstant(0, HalfT));
14835 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14836 DAG.getConstant(1, HalfT));
14837 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14838 Regs64bit ? X86::RBX : X86::EBX,
14839 swapInL, cpInH.getValue(1));
14840 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14841 Regs64bit ? X86::RCX : X86::ECX,
14842 swapInH, swapInL.getValue(1));
14843 SDValue Ops[] = { swapInH.getValue(0),
14845 swapInH.getValue(1) };
14846 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14847 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14848 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14849 X86ISD::LCMPXCHG8_DAG;
14850 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14851 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14852 Regs64bit ? X86::RAX : X86::EAX,
14853 HalfT, Result.getValue(1));
14854 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14855 Regs64bit ? X86::RDX : X86::EDX,
14856 HalfT, cpOutL.getValue(2));
14857 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14858 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14859 Results.push_back(cpOutH.getValue(1));
14862 case ISD::ATOMIC_LOAD_ADD:
14863 case ISD::ATOMIC_LOAD_AND:
14864 case ISD::ATOMIC_LOAD_NAND:
14865 case ISD::ATOMIC_LOAD_OR:
14866 case ISD::ATOMIC_LOAD_SUB:
14867 case ISD::ATOMIC_LOAD_XOR:
14868 case ISD::ATOMIC_LOAD_MAX:
14869 case ISD::ATOMIC_LOAD_MIN:
14870 case ISD::ATOMIC_LOAD_UMAX:
14871 case ISD::ATOMIC_LOAD_UMIN:
14872 case ISD::ATOMIC_SWAP: {
14874 switch (N->getOpcode()) {
14875 default: llvm_unreachable("Unexpected opcode");
14876 case ISD::ATOMIC_LOAD_ADD:
14877 Opc = X86ISD::ATOMADD64_DAG;
14879 case ISD::ATOMIC_LOAD_AND:
14880 Opc = X86ISD::ATOMAND64_DAG;
14882 case ISD::ATOMIC_LOAD_NAND:
14883 Opc = X86ISD::ATOMNAND64_DAG;
14885 case ISD::ATOMIC_LOAD_OR:
14886 Opc = X86ISD::ATOMOR64_DAG;
14888 case ISD::ATOMIC_LOAD_SUB:
14889 Opc = X86ISD::ATOMSUB64_DAG;
14891 case ISD::ATOMIC_LOAD_XOR:
14892 Opc = X86ISD::ATOMXOR64_DAG;
14894 case ISD::ATOMIC_LOAD_MAX:
14895 Opc = X86ISD::ATOMMAX64_DAG;
14897 case ISD::ATOMIC_LOAD_MIN:
14898 Opc = X86ISD::ATOMMIN64_DAG;
14900 case ISD::ATOMIC_LOAD_UMAX:
14901 Opc = X86ISD::ATOMUMAX64_DAG;
14903 case ISD::ATOMIC_LOAD_UMIN:
14904 Opc = X86ISD::ATOMUMIN64_DAG;
14906 case ISD::ATOMIC_SWAP:
14907 Opc = X86ISD::ATOMSWAP64_DAG;
14910 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14913 case ISD::ATOMIC_LOAD: {
14914 ReplaceATOMIC_LOAD(N, Results, DAG);
14917 case ISD::BITCAST: {
14918 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14919 EVT DstVT = N->getValueType(0);
14920 EVT SrcVT = N->getOperand(0)->getValueType(0);
14922 if (SrcVT != MVT::f64 ||
14923 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
14926 unsigned NumElts = DstVT.getVectorNumElements();
14927 EVT SVT = DstVT.getVectorElementType();
14928 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14929 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14930 MVT::v2f64, N->getOperand(0));
14931 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
14933 SmallVector<SDValue, 8> Elts;
14934 for (unsigned i = 0, e = NumElts; i != e; ++i)
14935 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
14936 ToVecInt, DAG.getIntPtrConstant(i)));
14938 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
14943 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14945 default: return nullptr;
14946 case X86ISD::BSF: return "X86ISD::BSF";
14947 case X86ISD::BSR: return "X86ISD::BSR";
14948 case X86ISD::SHLD: return "X86ISD::SHLD";
14949 case X86ISD::SHRD: return "X86ISD::SHRD";
14950 case X86ISD::FAND: return "X86ISD::FAND";
14951 case X86ISD::FANDN: return "X86ISD::FANDN";
14952 case X86ISD::FOR: return "X86ISD::FOR";
14953 case X86ISD::FXOR: return "X86ISD::FXOR";
14954 case X86ISD::FSRL: return "X86ISD::FSRL";
14955 case X86ISD::FILD: return "X86ISD::FILD";
14956 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14957 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14958 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14959 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14960 case X86ISD::FLD: return "X86ISD::FLD";
14961 case X86ISD::FST: return "X86ISD::FST";
14962 case X86ISD::CALL: return "X86ISD::CALL";
14963 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14964 case X86ISD::BT: return "X86ISD::BT";
14965 case X86ISD::CMP: return "X86ISD::CMP";
14966 case X86ISD::COMI: return "X86ISD::COMI";
14967 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14968 case X86ISD::CMPM: return "X86ISD::CMPM";
14969 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14970 case X86ISD::SETCC: return "X86ISD::SETCC";
14971 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14972 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14973 case X86ISD::CMOV: return "X86ISD::CMOV";
14974 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14975 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14976 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14977 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14978 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14979 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14980 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14981 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14982 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14983 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14984 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14985 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14986 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14987 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14988 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14989 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14990 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14991 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14992 case X86ISD::HADD: return "X86ISD::HADD";
14993 case X86ISD::HSUB: return "X86ISD::HSUB";
14994 case X86ISD::FHADD: return "X86ISD::FHADD";
14995 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14996 case X86ISD::UMAX: return "X86ISD::UMAX";
14997 case X86ISD::UMIN: return "X86ISD::UMIN";
14998 case X86ISD::SMAX: return "X86ISD::SMAX";
14999 case X86ISD::SMIN: return "X86ISD::SMIN";
15000 case X86ISD::FMAX: return "X86ISD::FMAX";
15001 case X86ISD::FMIN: return "X86ISD::FMIN";
15002 case X86ISD::FMAXC: return "X86ISD::FMAXC";
15003 case X86ISD::FMINC: return "X86ISD::FMINC";
15004 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
15005 case X86ISD::FRCP: return "X86ISD::FRCP";
15006 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
15007 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
15008 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
15009 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
15010 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
15011 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
15012 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
15013 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
15014 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
15015 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
15016 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
15017 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
15018 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
15019 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
15020 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
15021 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
15022 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
15023 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
15024 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
15025 case X86ISD::VZEXT: return "X86ISD::VZEXT";
15026 case X86ISD::VSEXT: return "X86ISD::VSEXT";
15027 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
15028 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
15029 case X86ISD::VINSERT: return "X86ISD::VINSERT";
15030 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
15031 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
15032 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
15033 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
15034 case X86ISD::VSHL: return "X86ISD::VSHL";
15035 case X86ISD::VSRL: return "X86ISD::VSRL";
15036 case X86ISD::VSRA: return "X86ISD::VSRA";
15037 case X86ISD::VSHLI: return "X86ISD::VSHLI";
15038 case X86ISD::VSRLI: return "X86ISD::VSRLI";
15039 case X86ISD::VSRAI: return "X86ISD::VSRAI";
15040 case X86ISD::CMPP: return "X86ISD::CMPP";
15041 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
15042 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
15043 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
15044 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
15045 case X86ISD::ADD: return "X86ISD::ADD";
15046 case X86ISD::SUB: return "X86ISD::SUB";
15047 case X86ISD::ADC: return "X86ISD::ADC";
15048 case X86ISD::SBB: return "X86ISD::SBB";
15049 case X86ISD::SMUL: return "X86ISD::SMUL";
15050 case X86ISD::UMUL: return "X86ISD::UMUL";
15051 case X86ISD::INC: return "X86ISD::INC";
15052 case X86ISD::DEC: return "X86ISD::DEC";
15053 case X86ISD::OR: return "X86ISD::OR";
15054 case X86ISD::XOR: return "X86ISD::XOR";
15055 case X86ISD::AND: return "X86ISD::AND";
15056 case X86ISD::BEXTR: return "X86ISD::BEXTR";
15057 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
15058 case X86ISD::PTEST: return "X86ISD::PTEST";
15059 case X86ISD::TESTP: return "X86ISD::TESTP";
15060 case X86ISD::TESTM: return "X86ISD::TESTM";
15061 case X86ISD::TESTNM: return "X86ISD::TESTNM";
15062 case X86ISD::KORTEST: return "X86ISD::KORTEST";
15063 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
15064 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
15065 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
15066 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
15067 case X86ISD::SHUFP: return "X86ISD::SHUFP";
15068 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
15069 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
15070 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
15071 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
15072 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
15073 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
15074 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
15075 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
15076 case X86ISD::MOVSD: return "X86ISD::MOVSD";
15077 case X86ISD::MOVSS: return "X86ISD::MOVSS";
15078 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
15079 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
15080 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
15081 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
15082 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
15083 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
15084 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
15085 case X86ISD::VPERMV: return "X86ISD::VPERMV";
15086 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
15087 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
15088 case X86ISD::VPERMI: return "X86ISD::VPERMI";
15089 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
15090 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
15091 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15092 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
15093 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
15094 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
15095 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
15096 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
15097 case X86ISD::SAHF: return "X86ISD::SAHF";
15098 case X86ISD::RDRAND: return "X86ISD::RDRAND";
15099 case X86ISD::RDSEED: return "X86ISD::RDSEED";
15100 case X86ISD::FMADD: return "X86ISD::FMADD";
15101 case X86ISD::FMSUB: return "X86ISD::FMSUB";
15102 case X86ISD::FNMADD: return "X86ISD::FNMADD";
15103 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
15104 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
15105 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
15106 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
15107 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
15108 case X86ISD::XTEST: return "X86ISD::XTEST";
15112 // isLegalAddressingMode - Return true if the addressing mode represented
15113 // by AM is legal for this target, for a load/store of the specified type.
15114 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15116 // X86 supports extremely general addressing modes.
15117 CodeModel::Model M = getTargetMachine().getCodeModel();
15118 Reloc::Model R = getTargetMachine().getRelocationModel();
15120 // X86 allows a sign-extended 32-bit immediate field as a displacement.
15121 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15126 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15128 // If a reference to this global requires an extra load, we can't fold it.
15129 if (isGlobalStubReference(GVFlags))
15132 // If BaseGV requires a register for the PIC base, we cannot also have a
15133 // BaseReg specified.
15134 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15137 // If lower 4G is not available, then we must use rip-relative addressing.
15138 if ((M != CodeModel::Small || R != Reloc::Static) &&
15139 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15143 switch (AM.Scale) {
15149 // These scales always work.
15154 // These scales are formed with basereg+scalereg. Only accept if there is
15159 default: // Other stuff never works.
15166 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15167 unsigned Bits = Ty->getScalarSizeInBits();
15169 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15170 // particularly cheaper than those without.
15174 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15175 // variable shifts just as cheap as scalar ones.
15176 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15179 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15180 // fully general vector.
15184 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15185 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15187 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15188 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15189 return NumBits1 > NumBits2;
15192 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15193 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15196 if (!isTypeLegal(EVT::getEVT(Ty1)))
15199 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15201 // Assuming the caller doesn't have a zeroext or signext return parameter,
15202 // truncation all the way down to i1 is valid.
15206 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15207 return isInt<32>(Imm);
15210 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15211 // Can also use sub to handle negated immediates.
15212 return isInt<32>(Imm);
15215 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15216 if (!VT1.isInteger() || !VT2.isInteger())
15218 unsigned NumBits1 = VT1.getSizeInBits();
15219 unsigned NumBits2 = VT2.getSizeInBits();
15220 return NumBits1 > NumBits2;
15223 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15224 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15225 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15228 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15229 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15230 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15233 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15234 EVT VT1 = Val.getValueType();
15235 if (isZExtFree(VT1, VT2))
15238 if (Val.getOpcode() != ISD::LOAD)
15241 if (!VT1.isSimple() || !VT1.isInteger() ||
15242 !VT2.isSimple() || !VT2.isInteger())
15245 switch (VT1.getSimpleVT().SimpleTy) {
15250 // X86 has 8, 16, and 32-bit zero-extending loads.
15258 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15259 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15262 VT = VT.getScalarType();
15264 if (!VT.isSimple())
15267 switch (VT.getSimpleVT().SimpleTy) {
15278 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15279 // i16 instructions are longer (0x66 prefix) and potentially slower.
15280 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15283 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15284 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15285 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15286 /// are assumed to be legal.
15288 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15290 if (!VT.isSimple())
15293 MVT SVT = VT.getSimpleVT();
15295 // Very little shuffling can be done for 64-bit vectors right now.
15296 if (VT.getSizeInBits() == 64)
15299 // If this is a single-input shuffle with no 128 bit lane crossings we can
15300 // lower it into pshufb.
15301 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15302 (SVT.is256BitVector() && Subtarget->hasInt256())) {
15303 bool isLegal = true;
15304 for (unsigned I = 0, E = M.size(); I != E; ++I) {
15305 if (M[I] >= (int)SVT.getVectorNumElements() ||
15306 ShuffleCrosses128bitLane(SVT, I, M[I])) {
15315 // FIXME: blends, shifts.
15316 return (SVT.getVectorNumElements() == 2 ||
15317 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15318 isMOVLMask(M, SVT) ||
15319 isSHUFPMask(M, SVT) ||
15320 isPSHUFDMask(M, SVT) ||
15321 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15322 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15323 isPALIGNRMask(M, SVT, Subtarget) ||
15324 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15325 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15326 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15327 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15328 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15332 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15334 if (!VT.isSimple())
15337 MVT SVT = VT.getSimpleVT();
15338 unsigned NumElts = SVT.getVectorNumElements();
15339 // FIXME: This collection of masks seems suspect.
15342 if (NumElts == 4 && SVT.is128BitVector()) {
15343 return (isMOVLMask(Mask, SVT) ||
15344 isCommutedMOVLMask(Mask, SVT, true) ||
15345 isSHUFPMask(Mask, SVT) ||
15346 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15351 //===----------------------------------------------------------------------===//
15352 // X86 Scheduler Hooks
15353 //===----------------------------------------------------------------------===//
15355 /// Utility function to emit xbegin specifying the start of an RTM region.
15356 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15357 const TargetInstrInfo *TII) {
15358 DebugLoc DL = MI->getDebugLoc();
15360 const BasicBlock *BB = MBB->getBasicBlock();
15361 MachineFunction::iterator I = MBB;
15364 // For the v = xbegin(), we generate
15375 MachineBasicBlock *thisMBB = MBB;
15376 MachineFunction *MF = MBB->getParent();
15377 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15378 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15379 MF->insert(I, mainMBB);
15380 MF->insert(I, sinkMBB);
15382 // Transfer the remainder of BB and its successor edges to sinkMBB.
15383 sinkMBB->splice(sinkMBB->begin(), MBB,
15384 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15385 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15389 // # fallthrough to mainMBB
15390 // # abortion to sinkMBB
15391 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15392 thisMBB->addSuccessor(mainMBB);
15393 thisMBB->addSuccessor(sinkMBB);
15397 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15398 mainMBB->addSuccessor(sinkMBB);
15401 // EAX is live into the sinkMBB
15402 sinkMBB->addLiveIn(X86::EAX);
15403 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15404 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15407 MI->eraseFromParent();
15411 // Get CMPXCHG opcode for the specified data type.
15412 static unsigned getCmpXChgOpcode(EVT VT) {
15413 switch (VT.getSimpleVT().SimpleTy) {
15414 case MVT::i8: return X86::LCMPXCHG8;
15415 case MVT::i16: return X86::LCMPXCHG16;
15416 case MVT::i32: return X86::LCMPXCHG32;
15417 case MVT::i64: return X86::LCMPXCHG64;
15421 llvm_unreachable("Invalid operand size!");
15424 // Get LOAD opcode for the specified data type.
15425 static unsigned getLoadOpcode(EVT VT) {
15426 switch (VT.getSimpleVT().SimpleTy) {
15427 case MVT::i8: return X86::MOV8rm;
15428 case MVT::i16: return X86::MOV16rm;
15429 case MVT::i32: return X86::MOV32rm;
15430 case MVT::i64: return X86::MOV64rm;
15434 llvm_unreachable("Invalid operand size!");
15437 // Get opcode of the non-atomic one from the specified atomic instruction.
15438 static unsigned getNonAtomicOpcode(unsigned Opc) {
15440 case X86::ATOMAND8: return X86::AND8rr;
15441 case X86::ATOMAND16: return X86::AND16rr;
15442 case X86::ATOMAND32: return X86::AND32rr;
15443 case X86::ATOMAND64: return X86::AND64rr;
15444 case X86::ATOMOR8: return X86::OR8rr;
15445 case X86::ATOMOR16: return X86::OR16rr;
15446 case X86::ATOMOR32: return X86::OR32rr;
15447 case X86::ATOMOR64: return X86::OR64rr;
15448 case X86::ATOMXOR8: return X86::XOR8rr;
15449 case X86::ATOMXOR16: return X86::XOR16rr;
15450 case X86::ATOMXOR32: return X86::XOR32rr;
15451 case X86::ATOMXOR64: return X86::XOR64rr;
15453 llvm_unreachable("Unhandled atomic-load-op opcode!");
15456 // Get opcode of the non-atomic one from the specified atomic instruction with
15458 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15459 unsigned &ExtraOpc) {
15461 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15462 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15463 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15464 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15465 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15466 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15467 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15468 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15469 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15470 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15471 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15472 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15473 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15474 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15475 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15476 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15477 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15478 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15479 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15480 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15482 llvm_unreachable("Unhandled atomic-load-op opcode!");
15485 // Get opcode of the non-atomic one from the specified atomic instruction for
15486 // 64-bit data type on 32-bit target.
15487 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15489 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15490 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15491 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15492 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15493 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15494 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15495 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15496 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15497 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15498 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15500 llvm_unreachable("Unhandled atomic-load-op opcode!");
15503 // Get opcode of the non-atomic one from the specified atomic instruction for
15504 // 64-bit data type on 32-bit target with extra opcode.
15505 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15507 unsigned &ExtraOpc) {
15509 case X86::ATOMNAND6432:
15510 ExtraOpc = X86::NOT32r;
15511 HiOpc = X86::AND32rr;
15512 return X86::AND32rr;
15514 llvm_unreachable("Unhandled atomic-load-op opcode!");
15517 // Get pseudo CMOV opcode from the specified data type.
15518 static unsigned getPseudoCMOVOpc(EVT VT) {
15519 switch (VT.getSimpleVT().SimpleTy) {
15520 case MVT::i8: return X86::CMOV_GR8;
15521 case MVT::i16: return X86::CMOV_GR16;
15522 case MVT::i32: return X86::CMOV_GR32;
15526 llvm_unreachable("Unknown CMOV opcode!");
15529 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15530 // They will be translated into a spin-loop or compare-exchange loop from
15533 // dst = atomic-fetch-op MI.addr, MI.val
15539 // t1 = LOAD MI.addr
15541 // t4 = phi(t1, t3 / loop)
15542 // t2 = OP MI.val, t4
15544 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15550 MachineBasicBlock *
15551 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15552 MachineBasicBlock *MBB) const {
15553 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15554 DebugLoc DL = MI->getDebugLoc();
15556 MachineFunction *MF = MBB->getParent();
15557 MachineRegisterInfo &MRI = MF->getRegInfo();
15559 const BasicBlock *BB = MBB->getBasicBlock();
15560 MachineFunction::iterator I = MBB;
15563 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15564 "Unexpected number of operands");
15566 assert(MI->hasOneMemOperand() &&
15567 "Expected atomic-load-op to have one memoperand");
15569 // Memory Reference
15570 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15571 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15573 unsigned DstReg, SrcReg;
15574 unsigned MemOpndSlot;
15576 unsigned CurOp = 0;
15578 DstReg = MI->getOperand(CurOp++).getReg();
15579 MemOpndSlot = CurOp;
15580 CurOp += X86::AddrNumOperands;
15581 SrcReg = MI->getOperand(CurOp++).getReg();
15583 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15584 MVT::SimpleValueType VT = *RC->vt_begin();
15585 unsigned t1 = MRI.createVirtualRegister(RC);
15586 unsigned t2 = MRI.createVirtualRegister(RC);
15587 unsigned t3 = MRI.createVirtualRegister(RC);
15588 unsigned t4 = MRI.createVirtualRegister(RC);
15589 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15591 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15592 unsigned LOADOpc = getLoadOpcode(VT);
15594 // For the atomic load-arith operator, we generate
15597 // t1 = LOAD [MI.addr]
15599 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15600 // t1 = OP MI.val, EAX
15602 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15608 MachineBasicBlock *thisMBB = MBB;
15609 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15610 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15611 MF->insert(I, mainMBB);
15612 MF->insert(I, sinkMBB);
15614 MachineInstrBuilder MIB;
15616 // Transfer the remainder of BB and its successor edges to sinkMBB.
15617 sinkMBB->splice(sinkMBB->begin(), MBB,
15618 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15619 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15622 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15623 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15624 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15626 NewMO.setIsKill(false);
15627 MIB.addOperand(NewMO);
15629 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15630 unsigned flags = (*MMOI)->getFlags();
15631 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15632 MachineMemOperand *MMO =
15633 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15634 (*MMOI)->getSize(),
15635 (*MMOI)->getBaseAlignment(),
15636 (*MMOI)->getTBAAInfo(),
15637 (*MMOI)->getRanges());
15638 MIB.addMemOperand(MMO);
15641 thisMBB->addSuccessor(mainMBB);
15644 MachineBasicBlock *origMainMBB = mainMBB;
15647 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15648 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15650 unsigned Opc = MI->getOpcode();
15653 llvm_unreachable("Unhandled atomic-load-op opcode!");
15654 case X86::ATOMAND8:
15655 case X86::ATOMAND16:
15656 case X86::ATOMAND32:
15657 case X86::ATOMAND64:
15659 case X86::ATOMOR16:
15660 case X86::ATOMOR32:
15661 case X86::ATOMOR64:
15662 case X86::ATOMXOR8:
15663 case X86::ATOMXOR16:
15664 case X86::ATOMXOR32:
15665 case X86::ATOMXOR64: {
15666 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15667 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15671 case X86::ATOMNAND8:
15672 case X86::ATOMNAND16:
15673 case X86::ATOMNAND32:
15674 case X86::ATOMNAND64: {
15675 unsigned Tmp = MRI.createVirtualRegister(RC);
15677 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15678 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15680 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15683 case X86::ATOMMAX8:
15684 case X86::ATOMMAX16:
15685 case X86::ATOMMAX32:
15686 case X86::ATOMMAX64:
15687 case X86::ATOMMIN8:
15688 case X86::ATOMMIN16:
15689 case X86::ATOMMIN32:
15690 case X86::ATOMMIN64:
15691 case X86::ATOMUMAX8:
15692 case X86::ATOMUMAX16:
15693 case X86::ATOMUMAX32:
15694 case X86::ATOMUMAX64:
15695 case X86::ATOMUMIN8:
15696 case X86::ATOMUMIN16:
15697 case X86::ATOMUMIN32:
15698 case X86::ATOMUMIN64: {
15700 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15702 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15706 if (Subtarget->hasCMov()) {
15707 if (VT != MVT::i8) {
15709 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15713 // Promote i8 to i32 to use CMOV32
15714 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15715 const TargetRegisterClass *RC32 =
15716 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15717 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15718 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15719 unsigned Tmp = MRI.createVirtualRegister(RC32);
15721 unsigned Undef = MRI.createVirtualRegister(RC32);
15722 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15724 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15727 .addImm(X86::sub_8bit);
15728 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15731 .addImm(X86::sub_8bit);
15733 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15737 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15738 .addReg(Tmp, 0, X86::sub_8bit);
15741 // Use pseudo select and lower them.
15742 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15743 "Invalid atomic-load-op transformation!");
15744 unsigned SelOpc = getPseudoCMOVOpc(VT);
15745 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15746 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15747 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15748 .addReg(SrcReg).addReg(t4)
15750 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15751 // Replace the original PHI node as mainMBB is changed after CMOV
15753 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15754 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15755 Phi->eraseFromParent();
15761 // Copy PhyReg back from virtual register.
15762 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15765 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15766 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15767 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15769 NewMO.setIsKill(false);
15770 MIB.addOperand(NewMO);
15773 MIB.setMemRefs(MMOBegin, MMOEnd);
15775 // Copy PhyReg back to virtual register.
15776 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15779 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15781 mainMBB->addSuccessor(origMainMBB);
15782 mainMBB->addSuccessor(sinkMBB);
15785 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15786 TII->get(TargetOpcode::COPY), DstReg)
15789 MI->eraseFromParent();
15793 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15794 // instructions. They will be translated into a spin-loop or compare-exchange
15798 // dst = atomic-fetch-op MI.addr, MI.val
15804 // t1L = LOAD [MI.addr + 0]
15805 // t1H = LOAD [MI.addr + 4]
15807 // t4L = phi(t1L, t3L / loop)
15808 // t4H = phi(t1H, t3H / loop)
15809 // t2L = OP MI.val.lo, t4L
15810 // t2H = OP MI.val.hi, t4H
15815 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15823 MachineBasicBlock *
15824 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15825 MachineBasicBlock *MBB) const {
15826 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15827 DebugLoc DL = MI->getDebugLoc();
15829 MachineFunction *MF = MBB->getParent();
15830 MachineRegisterInfo &MRI = MF->getRegInfo();
15832 const BasicBlock *BB = MBB->getBasicBlock();
15833 MachineFunction::iterator I = MBB;
15836 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15837 "Unexpected number of operands");
15839 assert(MI->hasOneMemOperand() &&
15840 "Expected atomic-load-op32 to have one memoperand");
15842 // Memory Reference
15843 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15844 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15846 unsigned DstLoReg, DstHiReg;
15847 unsigned SrcLoReg, SrcHiReg;
15848 unsigned MemOpndSlot;
15850 unsigned CurOp = 0;
15852 DstLoReg = MI->getOperand(CurOp++).getReg();
15853 DstHiReg = MI->getOperand(CurOp++).getReg();
15854 MemOpndSlot = CurOp;
15855 CurOp += X86::AddrNumOperands;
15856 SrcLoReg = MI->getOperand(CurOp++).getReg();
15857 SrcHiReg = MI->getOperand(CurOp++).getReg();
15859 const TargetRegisterClass *RC = &X86::GR32RegClass;
15860 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15862 unsigned t1L = MRI.createVirtualRegister(RC);
15863 unsigned t1H = MRI.createVirtualRegister(RC);
15864 unsigned t2L = MRI.createVirtualRegister(RC);
15865 unsigned t2H = MRI.createVirtualRegister(RC);
15866 unsigned t3L = MRI.createVirtualRegister(RC);
15867 unsigned t3H = MRI.createVirtualRegister(RC);
15868 unsigned t4L = MRI.createVirtualRegister(RC);
15869 unsigned t4H = MRI.createVirtualRegister(RC);
15871 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15872 unsigned LOADOpc = X86::MOV32rm;
15874 // For the atomic load-arith operator, we generate
15877 // t1L = LOAD [MI.addr + 0]
15878 // t1H = LOAD [MI.addr + 4]
15880 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15881 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15882 // t2L = OP MI.val.lo, t4L
15883 // t2H = OP MI.val.hi, t4H
15886 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15894 MachineBasicBlock *thisMBB = MBB;
15895 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15896 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15897 MF->insert(I, mainMBB);
15898 MF->insert(I, sinkMBB);
15900 MachineInstrBuilder MIB;
15902 // Transfer the remainder of BB and its successor edges to sinkMBB.
15903 sinkMBB->splice(sinkMBB->begin(), MBB,
15904 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15905 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15909 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15910 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15911 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15913 NewMO.setIsKill(false);
15914 MIB.addOperand(NewMO);
15916 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15917 unsigned flags = (*MMOI)->getFlags();
15918 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15919 MachineMemOperand *MMO =
15920 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15921 (*MMOI)->getSize(),
15922 (*MMOI)->getBaseAlignment(),
15923 (*MMOI)->getTBAAInfo(),
15924 (*MMOI)->getRanges());
15925 MIB.addMemOperand(MMO);
15927 MachineInstr *LowMI = MIB;
15930 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15931 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15932 if (i == X86::AddrDisp) {
15933 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15935 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15937 NewMO.setIsKill(false);
15938 MIB.addOperand(NewMO);
15941 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15943 thisMBB->addSuccessor(mainMBB);
15946 MachineBasicBlock *origMainMBB = mainMBB;
15949 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15950 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15951 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15952 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15954 unsigned Opc = MI->getOpcode();
15957 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15958 case X86::ATOMAND6432:
15959 case X86::ATOMOR6432:
15960 case X86::ATOMXOR6432:
15961 case X86::ATOMADD6432:
15962 case X86::ATOMSUB6432: {
15964 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15965 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15967 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15971 case X86::ATOMNAND6432: {
15972 unsigned HiOpc, NOTOpc;
15973 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15974 unsigned TmpL = MRI.createVirtualRegister(RC);
15975 unsigned TmpH = MRI.createVirtualRegister(RC);
15976 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15978 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15980 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15981 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15984 case X86::ATOMMAX6432:
15985 case X86::ATOMMIN6432:
15986 case X86::ATOMUMAX6432:
15987 case X86::ATOMUMIN6432: {
15989 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15990 unsigned cL = MRI.createVirtualRegister(RC8);
15991 unsigned cH = MRI.createVirtualRegister(RC8);
15992 unsigned cL32 = MRI.createVirtualRegister(RC);
15993 unsigned cH32 = MRI.createVirtualRegister(RC);
15994 unsigned cc = MRI.createVirtualRegister(RC);
15995 // cl := cmp src_lo, lo
15996 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15997 .addReg(SrcLoReg).addReg(t4L);
15998 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15999 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
16000 // ch := cmp src_hi, hi
16001 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16002 .addReg(SrcHiReg).addReg(t4H);
16003 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
16004 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
16005 // cc := if (src_hi == hi) ? cl : ch;
16006 if (Subtarget->hasCMov()) {
16007 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
16008 .addReg(cH32).addReg(cL32);
16010 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
16011 .addReg(cH32).addReg(cL32)
16012 .addImm(X86::COND_E);
16013 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16015 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
16016 if (Subtarget->hasCMov()) {
16017 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16018 .addReg(SrcLoReg).addReg(t4L);
16019 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16020 .addReg(SrcHiReg).addReg(t4H);
16022 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16023 .addReg(SrcLoReg).addReg(t4L)
16024 .addImm(X86::COND_NE);
16025 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16026 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16027 // 2nd CMOV lowering.
16028 mainMBB->addLiveIn(X86::EFLAGS);
16029 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16030 .addReg(SrcHiReg).addReg(t4H)
16031 .addImm(X86::COND_NE);
16032 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16033 // Replace the original PHI node as mainMBB is changed after CMOV
16035 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16036 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16037 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16038 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16039 PhiL->eraseFromParent();
16040 PhiH->eraseFromParent();
16044 case X86::ATOMSWAP6432: {
16046 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16047 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16048 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16053 // Copy EDX:EAX back from HiReg:LoReg
16054 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16055 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16056 // Copy ECX:EBX from t1H:t1L
16057 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16058 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16060 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16061 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16062 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16064 NewMO.setIsKill(false);
16065 MIB.addOperand(NewMO);
16067 MIB.setMemRefs(MMOBegin, MMOEnd);
16069 // Copy EDX:EAX back to t3H:t3L
16070 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16071 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16073 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16075 mainMBB->addSuccessor(origMainMBB);
16076 mainMBB->addSuccessor(sinkMBB);
16079 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16080 TII->get(TargetOpcode::COPY), DstLoReg)
16082 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16083 TII->get(TargetOpcode::COPY), DstHiReg)
16086 MI->eraseFromParent();
16090 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16091 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16092 // in the .td file.
16093 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16094 const TargetInstrInfo *TII) {
16096 switch (MI->getOpcode()) {
16097 default: llvm_unreachable("illegal opcode!");
16098 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
16099 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16100 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
16101 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16102 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
16103 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16104 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
16105 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16108 DebugLoc dl = MI->getDebugLoc();
16109 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16111 unsigned NumArgs = MI->getNumOperands();
16112 for (unsigned i = 1; i < NumArgs; ++i) {
16113 MachineOperand &Op = MI->getOperand(i);
16114 if (!(Op.isReg() && Op.isImplicit()))
16115 MIB.addOperand(Op);
16117 if (MI->hasOneMemOperand())
16118 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16120 BuildMI(*BB, MI, dl,
16121 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16122 .addReg(X86::XMM0);
16124 MI->eraseFromParent();
16128 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16129 // defs in an instruction pattern
16130 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16131 const TargetInstrInfo *TII) {
16133 switch (MI->getOpcode()) {
16134 default: llvm_unreachable("illegal opcode!");
16135 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16136 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16137 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16138 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16139 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16140 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16141 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16142 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16145 DebugLoc dl = MI->getDebugLoc();
16146 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16148 unsigned NumArgs = MI->getNumOperands(); // remove the results
16149 for (unsigned i = 1; i < NumArgs; ++i) {
16150 MachineOperand &Op = MI->getOperand(i);
16151 if (!(Op.isReg() && Op.isImplicit()))
16152 MIB.addOperand(Op);
16154 if (MI->hasOneMemOperand())
16155 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16157 BuildMI(*BB, MI, dl,
16158 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16161 MI->eraseFromParent();
16165 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16166 const TargetInstrInfo *TII,
16167 const X86Subtarget* Subtarget) {
16168 DebugLoc dl = MI->getDebugLoc();
16170 // Address into RAX/EAX, other two args into ECX, EDX.
16171 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16172 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16173 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16174 for (int i = 0; i < X86::AddrNumOperands; ++i)
16175 MIB.addOperand(MI->getOperand(i));
16177 unsigned ValOps = X86::AddrNumOperands;
16178 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16179 .addReg(MI->getOperand(ValOps).getReg());
16180 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16181 .addReg(MI->getOperand(ValOps+1).getReg());
16183 // The instruction doesn't actually take any operands though.
16184 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16186 MI->eraseFromParent(); // The pseudo is gone now.
16190 MachineBasicBlock *
16191 X86TargetLowering::EmitVAARG64WithCustomInserter(
16193 MachineBasicBlock *MBB) const {
16194 // Emit va_arg instruction on X86-64.
16196 // Operands to this pseudo-instruction:
16197 // 0 ) Output : destination address (reg)
16198 // 1-5) Input : va_list address (addr, i64mem)
16199 // 6 ) ArgSize : Size (in bytes) of vararg type
16200 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16201 // 8 ) Align : Alignment of type
16202 // 9 ) EFLAGS (implicit-def)
16204 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16205 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16207 unsigned DestReg = MI->getOperand(0).getReg();
16208 MachineOperand &Base = MI->getOperand(1);
16209 MachineOperand &Scale = MI->getOperand(2);
16210 MachineOperand &Index = MI->getOperand(3);
16211 MachineOperand &Disp = MI->getOperand(4);
16212 MachineOperand &Segment = MI->getOperand(5);
16213 unsigned ArgSize = MI->getOperand(6).getImm();
16214 unsigned ArgMode = MI->getOperand(7).getImm();
16215 unsigned Align = MI->getOperand(8).getImm();
16217 // Memory Reference
16218 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16219 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16220 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16222 // Machine Information
16223 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16224 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16225 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16226 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16227 DebugLoc DL = MI->getDebugLoc();
16229 // struct va_list {
16232 // i64 overflow_area (address)
16233 // i64 reg_save_area (address)
16235 // sizeof(va_list) = 24
16236 // alignment(va_list) = 8
16238 unsigned TotalNumIntRegs = 6;
16239 unsigned TotalNumXMMRegs = 8;
16240 bool UseGPOffset = (ArgMode == 1);
16241 bool UseFPOffset = (ArgMode == 2);
16242 unsigned MaxOffset = TotalNumIntRegs * 8 +
16243 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16245 /* Align ArgSize to a multiple of 8 */
16246 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16247 bool NeedsAlign = (Align > 8);
16249 MachineBasicBlock *thisMBB = MBB;
16250 MachineBasicBlock *overflowMBB;
16251 MachineBasicBlock *offsetMBB;
16252 MachineBasicBlock *endMBB;
16254 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
16255 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
16256 unsigned OffsetReg = 0;
16258 if (!UseGPOffset && !UseFPOffset) {
16259 // If we only pull from the overflow region, we don't create a branch.
16260 // We don't need to alter control flow.
16261 OffsetDestReg = 0; // unused
16262 OverflowDestReg = DestReg;
16264 offsetMBB = nullptr;
16265 overflowMBB = thisMBB;
16268 // First emit code to check if gp_offset (or fp_offset) is below the bound.
16269 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16270 // If not, pull from overflow_area. (branch to overflowMBB)
16275 // offsetMBB overflowMBB
16280 // Registers for the PHI in endMBB
16281 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16282 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16284 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16285 MachineFunction *MF = MBB->getParent();
16286 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16287 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16288 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16290 MachineFunction::iterator MBBIter = MBB;
16293 // Insert the new basic blocks
16294 MF->insert(MBBIter, offsetMBB);
16295 MF->insert(MBBIter, overflowMBB);
16296 MF->insert(MBBIter, endMBB);
16298 // Transfer the remainder of MBB and its successor edges to endMBB.
16299 endMBB->splice(endMBB->begin(), thisMBB,
16300 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16301 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16303 // Make offsetMBB and overflowMBB successors of thisMBB
16304 thisMBB->addSuccessor(offsetMBB);
16305 thisMBB->addSuccessor(overflowMBB);
16307 // endMBB is a successor of both offsetMBB and overflowMBB
16308 offsetMBB->addSuccessor(endMBB);
16309 overflowMBB->addSuccessor(endMBB);
16311 // Load the offset value into a register
16312 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16313 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16317 .addDisp(Disp, UseFPOffset ? 4 : 0)
16318 .addOperand(Segment)
16319 .setMemRefs(MMOBegin, MMOEnd);
16321 // Check if there is enough room left to pull this argument.
16322 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16324 .addImm(MaxOffset + 8 - ArgSizeA8);
16326 // Branch to "overflowMBB" if offset >= max
16327 // Fall through to "offsetMBB" otherwise
16328 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16329 .addMBB(overflowMBB);
16332 // In offsetMBB, emit code to use the reg_save_area.
16334 assert(OffsetReg != 0);
16336 // Read the reg_save_area address.
16337 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16338 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16343 .addOperand(Segment)
16344 .setMemRefs(MMOBegin, MMOEnd);
16346 // Zero-extend the offset
16347 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16348 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16351 .addImm(X86::sub_32bit);
16353 // Add the offset to the reg_save_area to get the final address.
16354 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16355 .addReg(OffsetReg64)
16356 .addReg(RegSaveReg);
16358 // Compute the offset for the next argument
16359 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16360 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16362 .addImm(UseFPOffset ? 16 : 8);
16364 // Store it back into the va_list.
16365 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16369 .addDisp(Disp, UseFPOffset ? 4 : 0)
16370 .addOperand(Segment)
16371 .addReg(NextOffsetReg)
16372 .setMemRefs(MMOBegin, MMOEnd);
16375 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16380 // Emit code to use overflow area
16383 // Load the overflow_area address into a register.
16384 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16385 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16390 .addOperand(Segment)
16391 .setMemRefs(MMOBegin, MMOEnd);
16393 // If we need to align it, do so. Otherwise, just copy the address
16394 // to OverflowDestReg.
16396 // Align the overflow address
16397 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16398 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16400 // aligned_addr = (addr + (align-1)) & ~(align-1)
16401 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16402 .addReg(OverflowAddrReg)
16405 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16407 .addImm(~(uint64_t)(Align-1));
16409 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16410 .addReg(OverflowAddrReg);
16413 // Compute the next overflow address after this argument.
16414 // (the overflow address should be kept 8-byte aligned)
16415 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16416 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16417 .addReg(OverflowDestReg)
16418 .addImm(ArgSizeA8);
16420 // Store the new overflow address.
16421 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16426 .addOperand(Segment)
16427 .addReg(NextAddrReg)
16428 .setMemRefs(MMOBegin, MMOEnd);
16430 // If we branched, emit the PHI to the front of endMBB.
16432 BuildMI(*endMBB, endMBB->begin(), DL,
16433 TII->get(X86::PHI), DestReg)
16434 .addReg(OffsetDestReg).addMBB(offsetMBB)
16435 .addReg(OverflowDestReg).addMBB(overflowMBB);
16438 // Erase the pseudo instruction
16439 MI->eraseFromParent();
16444 MachineBasicBlock *
16445 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16447 MachineBasicBlock *MBB) const {
16448 // Emit code to save XMM registers to the stack. The ABI says that the
16449 // number of registers to save is given in %al, so it's theoretically
16450 // possible to do an indirect jump trick to avoid saving all of them,
16451 // however this code takes a simpler approach and just executes all
16452 // of the stores if %al is non-zero. It's less code, and it's probably
16453 // easier on the hardware branch predictor, and stores aren't all that
16454 // expensive anyway.
16456 // Create the new basic blocks. One block contains all the XMM stores,
16457 // and one block is the final destination regardless of whether any
16458 // stores were performed.
16459 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16460 MachineFunction *F = MBB->getParent();
16461 MachineFunction::iterator MBBIter = MBB;
16463 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16464 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16465 F->insert(MBBIter, XMMSaveMBB);
16466 F->insert(MBBIter, EndMBB);
16468 // Transfer the remainder of MBB and its successor edges to EndMBB.
16469 EndMBB->splice(EndMBB->begin(), MBB,
16470 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16471 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16473 // The original block will now fall through to the XMM save block.
16474 MBB->addSuccessor(XMMSaveMBB);
16475 // The XMMSaveMBB will fall through to the end block.
16476 XMMSaveMBB->addSuccessor(EndMBB);
16478 // Now add the instructions.
16479 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16480 DebugLoc DL = MI->getDebugLoc();
16482 unsigned CountReg = MI->getOperand(0).getReg();
16483 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16484 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16486 if (!Subtarget->isTargetWin64()) {
16487 // If %al is 0, branch around the XMM save block.
16488 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16489 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16490 MBB->addSuccessor(EndMBB);
16493 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16494 // that was just emitted, but clearly shouldn't be "saved".
16495 assert((MI->getNumOperands() <= 3 ||
16496 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16497 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16498 && "Expected last argument to be EFLAGS");
16499 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16500 // In the XMM save block, save all the XMM argument registers.
16501 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16502 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16503 MachineMemOperand *MMO =
16504 F->getMachineMemOperand(
16505 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16506 MachineMemOperand::MOStore,
16507 /*Size=*/16, /*Align=*/16);
16508 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16509 .addFrameIndex(RegSaveFrameIndex)
16510 .addImm(/*Scale=*/1)
16511 .addReg(/*IndexReg=*/0)
16512 .addImm(/*Disp=*/Offset)
16513 .addReg(/*Segment=*/0)
16514 .addReg(MI->getOperand(i).getReg())
16515 .addMemOperand(MMO);
16518 MI->eraseFromParent(); // The pseudo instruction is gone now.
16523 // The EFLAGS operand of SelectItr might be missing a kill marker
16524 // because there were multiple uses of EFLAGS, and ISel didn't know
16525 // which to mark. Figure out whether SelectItr should have had a
16526 // kill marker, and set it if it should. Returns the correct kill
16528 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16529 MachineBasicBlock* BB,
16530 const TargetRegisterInfo* TRI) {
16531 // Scan forward through BB for a use/def of EFLAGS.
16532 MachineBasicBlock::iterator miI(std::next(SelectItr));
16533 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16534 const MachineInstr& mi = *miI;
16535 if (mi.readsRegister(X86::EFLAGS))
16537 if (mi.definesRegister(X86::EFLAGS))
16538 break; // Should have kill-flag - update below.
16541 // If we hit the end of the block, check whether EFLAGS is live into a
16543 if (miI == BB->end()) {
16544 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16545 sEnd = BB->succ_end();
16546 sItr != sEnd; ++sItr) {
16547 MachineBasicBlock* succ = *sItr;
16548 if (succ->isLiveIn(X86::EFLAGS))
16553 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16554 // out. SelectMI should have a kill flag on EFLAGS.
16555 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16559 MachineBasicBlock *
16560 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16561 MachineBasicBlock *BB) const {
16562 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16563 DebugLoc DL = MI->getDebugLoc();
16565 // To "insert" a SELECT_CC instruction, we actually have to insert the
16566 // diamond control-flow pattern. The incoming instruction knows the
16567 // destination vreg to set, the condition code register to branch on, the
16568 // true/false values to select between, and a branch opcode to use.
16569 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16570 MachineFunction::iterator It = BB;
16576 // cmpTY ccX, r1, r2
16578 // fallthrough --> copy0MBB
16579 MachineBasicBlock *thisMBB = BB;
16580 MachineFunction *F = BB->getParent();
16581 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16582 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16583 F->insert(It, copy0MBB);
16584 F->insert(It, sinkMBB);
16586 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16587 // live into the sink and copy blocks.
16588 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16589 if (!MI->killsRegister(X86::EFLAGS) &&
16590 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16591 copy0MBB->addLiveIn(X86::EFLAGS);
16592 sinkMBB->addLiveIn(X86::EFLAGS);
16595 // Transfer the remainder of BB and its successor edges to sinkMBB.
16596 sinkMBB->splice(sinkMBB->begin(), BB,
16597 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16598 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16600 // Add the true and fallthrough blocks as its successors.
16601 BB->addSuccessor(copy0MBB);
16602 BB->addSuccessor(sinkMBB);
16604 // Create the conditional branch instruction.
16606 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16607 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16610 // %FalseValue = ...
16611 // # fallthrough to sinkMBB
16612 copy0MBB->addSuccessor(sinkMBB);
16615 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16617 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16618 TII->get(X86::PHI), MI->getOperand(0).getReg())
16619 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16620 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16622 MI->eraseFromParent(); // The pseudo instruction is gone now.
16626 MachineBasicBlock *
16627 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16628 bool Is64Bit) const {
16629 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16630 DebugLoc DL = MI->getDebugLoc();
16631 MachineFunction *MF = BB->getParent();
16632 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16634 assert(MF->shouldSplitStack());
16636 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16637 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16640 // ... [Till the alloca]
16641 // If stacklet is not large enough, jump to mallocMBB
16644 // Allocate by subtracting from RSP
16645 // Jump to continueMBB
16648 // Allocate by call to runtime
16652 // [rest of original BB]
16655 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16656 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16657 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16659 MachineRegisterInfo &MRI = MF->getRegInfo();
16660 const TargetRegisterClass *AddrRegClass =
16661 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16663 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16664 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16665 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16666 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16667 sizeVReg = MI->getOperand(1).getReg(),
16668 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16670 MachineFunction::iterator MBBIter = BB;
16673 MF->insert(MBBIter, bumpMBB);
16674 MF->insert(MBBIter, mallocMBB);
16675 MF->insert(MBBIter, continueMBB);
16677 continueMBB->splice(continueMBB->begin(), BB,
16678 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16679 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16681 // Add code to the main basic block to check if the stack limit has been hit,
16682 // and if so, jump to mallocMBB otherwise to bumpMBB.
16683 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16684 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16685 .addReg(tmpSPVReg).addReg(sizeVReg);
16686 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16687 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16688 .addReg(SPLimitVReg);
16689 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16691 // bumpMBB simply decreases the stack pointer, since we know the current
16692 // stacklet has enough space.
16693 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16694 .addReg(SPLimitVReg);
16695 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16696 .addReg(SPLimitVReg);
16697 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16699 // Calls into a routine in libgcc to allocate more space from the heap.
16700 const uint32_t *RegMask =
16701 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16703 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16705 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16706 .addExternalSymbol("__morestack_allocate_stack_space")
16707 .addRegMask(RegMask)
16708 .addReg(X86::RDI, RegState::Implicit)
16709 .addReg(X86::RAX, RegState::ImplicitDefine);
16711 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16713 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16714 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16715 .addExternalSymbol("__morestack_allocate_stack_space")
16716 .addRegMask(RegMask)
16717 .addReg(X86::EAX, RegState::ImplicitDefine);
16721 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16724 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16725 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16726 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16728 // Set up the CFG correctly.
16729 BB->addSuccessor(bumpMBB);
16730 BB->addSuccessor(mallocMBB);
16731 mallocMBB->addSuccessor(continueMBB);
16732 bumpMBB->addSuccessor(continueMBB);
16734 // Take care of the PHI nodes.
16735 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16736 MI->getOperand(0).getReg())
16737 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16738 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16740 // Delete the original pseudo instruction.
16741 MI->eraseFromParent();
16744 return continueMBB;
16747 MachineBasicBlock *
16748 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16749 MachineBasicBlock *BB) const {
16750 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16751 DebugLoc DL = MI->getDebugLoc();
16753 assert(!Subtarget->isTargetMacho());
16755 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16756 // non-trivial part is impdef of ESP.
16758 if (Subtarget->isTargetWin64()) {
16759 if (Subtarget->isTargetCygMing()) {
16760 // ___chkstk(Mingw64):
16761 // Clobbers R10, R11, RAX and EFLAGS.
16763 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16764 .addExternalSymbol("___chkstk")
16765 .addReg(X86::RAX, RegState::Implicit)
16766 .addReg(X86::RSP, RegState::Implicit)
16767 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16768 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16769 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16771 // __chkstk(MSVCRT): does not update stack pointer.
16772 // Clobbers R10, R11 and EFLAGS.
16773 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16774 .addExternalSymbol("__chkstk")
16775 .addReg(X86::RAX, RegState::Implicit)
16776 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16777 // RAX has the offset to be subtracted from RSP.
16778 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16783 const char *StackProbeSymbol =
16784 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16786 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16787 .addExternalSymbol(StackProbeSymbol)
16788 .addReg(X86::EAX, RegState::Implicit)
16789 .addReg(X86::ESP, RegState::Implicit)
16790 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16791 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16792 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16795 MI->eraseFromParent(); // The pseudo instruction is gone now.
16799 MachineBasicBlock *
16800 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16801 MachineBasicBlock *BB) const {
16802 // This is pretty easy. We're taking the value that we received from
16803 // our load from the relocation, sticking it in either RDI (x86-64)
16804 // or EAX and doing an indirect call. The return value will then
16805 // be in the normal return register.
16806 const X86InstrInfo *TII
16807 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16808 DebugLoc DL = MI->getDebugLoc();
16809 MachineFunction *F = BB->getParent();
16811 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16812 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16814 // Get a register mask for the lowered call.
16815 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16816 // proper register mask.
16817 const uint32_t *RegMask =
16818 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16819 if (Subtarget->is64Bit()) {
16820 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16821 TII->get(X86::MOV64rm), X86::RDI)
16823 .addImm(0).addReg(0)
16824 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16825 MI->getOperand(3).getTargetFlags())
16827 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16828 addDirectMem(MIB, X86::RDI);
16829 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16830 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16831 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16832 TII->get(X86::MOV32rm), X86::EAX)
16834 .addImm(0).addReg(0)
16835 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16836 MI->getOperand(3).getTargetFlags())
16838 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16839 addDirectMem(MIB, X86::EAX);
16840 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16842 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16843 TII->get(X86::MOV32rm), X86::EAX)
16844 .addReg(TII->getGlobalBaseReg(F))
16845 .addImm(0).addReg(0)
16846 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16847 MI->getOperand(3).getTargetFlags())
16849 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16850 addDirectMem(MIB, X86::EAX);
16851 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16854 MI->eraseFromParent(); // The pseudo instruction is gone now.
16858 MachineBasicBlock *
16859 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16860 MachineBasicBlock *MBB) const {
16861 DebugLoc DL = MI->getDebugLoc();
16862 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16864 MachineFunction *MF = MBB->getParent();
16865 MachineRegisterInfo &MRI = MF->getRegInfo();
16867 const BasicBlock *BB = MBB->getBasicBlock();
16868 MachineFunction::iterator I = MBB;
16871 // Memory Reference
16872 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16873 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16876 unsigned MemOpndSlot = 0;
16878 unsigned CurOp = 0;
16880 DstReg = MI->getOperand(CurOp++).getReg();
16881 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16882 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16883 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16884 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16886 MemOpndSlot = CurOp;
16888 MVT PVT = getPointerTy();
16889 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16890 "Invalid Pointer Size!");
16892 // For v = setjmp(buf), we generate
16895 // buf[LabelOffset] = restoreMBB
16896 // SjLjSetup restoreMBB
16902 // v = phi(main, restore)
16907 MachineBasicBlock *thisMBB = MBB;
16908 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16909 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16910 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16911 MF->insert(I, mainMBB);
16912 MF->insert(I, sinkMBB);
16913 MF->push_back(restoreMBB);
16915 MachineInstrBuilder MIB;
16917 // Transfer the remainder of BB and its successor edges to sinkMBB.
16918 sinkMBB->splice(sinkMBB->begin(), MBB,
16919 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16920 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16923 unsigned PtrStoreOpc = 0;
16924 unsigned LabelReg = 0;
16925 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16926 Reloc::Model RM = getTargetMachine().getRelocationModel();
16927 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16928 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16930 // Prepare IP either in reg or imm.
16931 if (!UseImmLabel) {
16932 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16933 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16934 LabelReg = MRI.createVirtualRegister(PtrRC);
16935 if (Subtarget->is64Bit()) {
16936 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16940 .addMBB(restoreMBB)
16943 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16944 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16945 .addReg(XII->getGlobalBaseReg(MF))
16948 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16952 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16954 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16955 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16956 if (i == X86::AddrDisp)
16957 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16959 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16962 MIB.addReg(LabelReg);
16964 MIB.addMBB(restoreMBB);
16965 MIB.setMemRefs(MMOBegin, MMOEnd);
16967 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16968 .addMBB(restoreMBB);
16970 const X86RegisterInfo *RegInfo =
16971 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16972 MIB.addRegMask(RegInfo->getNoPreservedMask());
16973 thisMBB->addSuccessor(mainMBB);
16974 thisMBB->addSuccessor(restoreMBB);
16978 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16979 mainMBB->addSuccessor(sinkMBB);
16982 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16983 TII->get(X86::PHI), DstReg)
16984 .addReg(mainDstReg).addMBB(mainMBB)
16985 .addReg(restoreDstReg).addMBB(restoreMBB);
16988 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16989 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16990 restoreMBB->addSuccessor(sinkMBB);
16992 MI->eraseFromParent();
16996 MachineBasicBlock *
16997 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16998 MachineBasicBlock *MBB) const {
16999 DebugLoc DL = MI->getDebugLoc();
17000 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17002 MachineFunction *MF = MBB->getParent();
17003 MachineRegisterInfo &MRI = MF->getRegInfo();
17005 // Memory Reference
17006 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17007 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17009 MVT PVT = getPointerTy();
17010 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17011 "Invalid Pointer Size!");
17013 const TargetRegisterClass *RC =
17014 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17015 unsigned Tmp = MRI.createVirtualRegister(RC);
17016 // Since FP is only updated here but NOT referenced, it's treated as GPR.
17017 const X86RegisterInfo *RegInfo =
17018 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
17019 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17020 unsigned SP = RegInfo->getStackRegister();
17022 MachineInstrBuilder MIB;
17024 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17025 const int64_t SPOffset = 2 * PVT.getStoreSize();
17027 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17028 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17031 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17032 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17033 MIB.addOperand(MI->getOperand(i));
17034 MIB.setMemRefs(MMOBegin, MMOEnd);
17036 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17037 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17038 if (i == X86::AddrDisp)
17039 MIB.addDisp(MI->getOperand(i), LabelOffset);
17041 MIB.addOperand(MI->getOperand(i));
17043 MIB.setMemRefs(MMOBegin, MMOEnd);
17045 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17046 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17047 if (i == X86::AddrDisp)
17048 MIB.addDisp(MI->getOperand(i), SPOffset);
17050 MIB.addOperand(MI->getOperand(i));
17052 MIB.setMemRefs(MMOBegin, MMOEnd);
17054 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17056 MI->eraseFromParent();
17060 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17061 // accumulator loops. Writing back to the accumulator allows the coalescer
17062 // to remove extra copies in the loop.
17063 MachineBasicBlock *
17064 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17065 MachineBasicBlock *MBB) const {
17066 MachineOperand &AddendOp = MI->getOperand(3);
17068 // Bail out early if the addend isn't a register - we can't switch these.
17069 if (!AddendOp.isReg())
17072 MachineFunction &MF = *MBB->getParent();
17073 MachineRegisterInfo &MRI = MF.getRegInfo();
17075 // Check whether the addend is defined by a PHI:
17076 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17077 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17078 if (!AddendDef.isPHI())
17081 // Look for the following pattern:
17083 // %addend = phi [%entry, 0], [%loop, %result]
17085 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17089 // %addend = phi [%entry, 0], [%loop, %result]
17091 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17093 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17094 assert(AddendDef.getOperand(i).isReg());
17095 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17096 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17097 if (&PHISrcInst == MI) {
17098 // Found a matching instruction.
17099 unsigned NewFMAOpc = 0;
17100 switch (MI->getOpcode()) {
17101 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17102 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17103 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17104 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17105 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17106 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17107 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17108 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17109 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17110 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17111 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17112 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17113 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17114 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17115 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17116 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17117 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17118 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17119 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17120 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17121 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17122 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17123 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17124 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17125 default: llvm_unreachable("Unrecognized FMA variant.");
17128 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17129 MachineInstrBuilder MIB =
17130 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17131 .addOperand(MI->getOperand(0))
17132 .addOperand(MI->getOperand(3))
17133 .addOperand(MI->getOperand(2))
17134 .addOperand(MI->getOperand(1));
17135 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17136 MI->eraseFromParent();
17143 MachineBasicBlock *
17144 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17145 MachineBasicBlock *BB) const {
17146 switch (MI->getOpcode()) {
17147 default: llvm_unreachable("Unexpected instr type to insert");
17148 case X86::TAILJMPd64:
17149 case X86::TAILJMPr64:
17150 case X86::TAILJMPm64:
17151 llvm_unreachable("TAILJMP64 would not be touched here.");
17152 case X86::TCRETURNdi64:
17153 case X86::TCRETURNri64:
17154 case X86::TCRETURNmi64:
17156 case X86::WIN_ALLOCA:
17157 return EmitLoweredWinAlloca(MI, BB);
17158 case X86::SEG_ALLOCA_32:
17159 return EmitLoweredSegAlloca(MI, BB, false);
17160 case X86::SEG_ALLOCA_64:
17161 return EmitLoweredSegAlloca(MI, BB, true);
17162 case X86::TLSCall_32:
17163 case X86::TLSCall_64:
17164 return EmitLoweredTLSCall(MI, BB);
17165 case X86::CMOV_GR8:
17166 case X86::CMOV_FR32:
17167 case X86::CMOV_FR64:
17168 case X86::CMOV_V4F32:
17169 case X86::CMOV_V2F64:
17170 case X86::CMOV_V2I64:
17171 case X86::CMOV_V8F32:
17172 case X86::CMOV_V4F64:
17173 case X86::CMOV_V4I64:
17174 case X86::CMOV_V16F32:
17175 case X86::CMOV_V8F64:
17176 case X86::CMOV_V8I64:
17177 case X86::CMOV_GR16:
17178 case X86::CMOV_GR32:
17179 case X86::CMOV_RFP32:
17180 case X86::CMOV_RFP64:
17181 case X86::CMOV_RFP80:
17182 return EmitLoweredSelect(MI, BB);
17184 case X86::FP32_TO_INT16_IN_MEM:
17185 case X86::FP32_TO_INT32_IN_MEM:
17186 case X86::FP32_TO_INT64_IN_MEM:
17187 case X86::FP64_TO_INT16_IN_MEM:
17188 case X86::FP64_TO_INT32_IN_MEM:
17189 case X86::FP64_TO_INT64_IN_MEM:
17190 case X86::FP80_TO_INT16_IN_MEM:
17191 case X86::FP80_TO_INT32_IN_MEM:
17192 case X86::FP80_TO_INT64_IN_MEM: {
17193 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17194 DebugLoc DL = MI->getDebugLoc();
17196 // Change the floating point control register to use "round towards zero"
17197 // mode when truncating to an integer value.
17198 MachineFunction *F = BB->getParent();
17199 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17200 addFrameReference(BuildMI(*BB, MI, DL,
17201 TII->get(X86::FNSTCW16m)), CWFrameIdx);
17203 // Load the old value of the high byte of the control word...
17205 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17206 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17209 // Set the high part to be round to zero...
17210 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17213 // Reload the modified control word now...
17214 addFrameReference(BuildMI(*BB, MI, DL,
17215 TII->get(X86::FLDCW16m)), CWFrameIdx);
17217 // Restore the memory image of control word to original value
17218 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17221 // Get the X86 opcode to use.
17223 switch (MI->getOpcode()) {
17224 default: llvm_unreachable("illegal opcode!");
17225 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17226 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17227 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17228 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17229 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17230 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17231 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17232 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17233 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17237 MachineOperand &Op = MI->getOperand(0);
17239 AM.BaseType = X86AddressMode::RegBase;
17240 AM.Base.Reg = Op.getReg();
17242 AM.BaseType = X86AddressMode::FrameIndexBase;
17243 AM.Base.FrameIndex = Op.getIndex();
17245 Op = MI->getOperand(1);
17247 AM.Scale = Op.getImm();
17248 Op = MI->getOperand(2);
17250 AM.IndexReg = Op.getImm();
17251 Op = MI->getOperand(3);
17252 if (Op.isGlobal()) {
17253 AM.GV = Op.getGlobal();
17255 AM.Disp = Op.getImm();
17257 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17258 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17260 // Reload the original control word now.
17261 addFrameReference(BuildMI(*BB, MI, DL,
17262 TII->get(X86::FLDCW16m)), CWFrameIdx);
17264 MI->eraseFromParent(); // The pseudo instruction is gone now.
17267 // String/text processing lowering.
17268 case X86::PCMPISTRM128REG:
17269 case X86::VPCMPISTRM128REG:
17270 case X86::PCMPISTRM128MEM:
17271 case X86::VPCMPISTRM128MEM:
17272 case X86::PCMPESTRM128REG:
17273 case X86::VPCMPESTRM128REG:
17274 case X86::PCMPESTRM128MEM:
17275 case X86::VPCMPESTRM128MEM:
17276 assert(Subtarget->hasSSE42() &&
17277 "Target must have SSE4.2 or AVX features enabled");
17278 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17280 // String/text processing lowering.
17281 case X86::PCMPISTRIREG:
17282 case X86::VPCMPISTRIREG:
17283 case X86::PCMPISTRIMEM:
17284 case X86::VPCMPISTRIMEM:
17285 case X86::PCMPESTRIREG:
17286 case X86::VPCMPESTRIREG:
17287 case X86::PCMPESTRIMEM:
17288 case X86::VPCMPESTRIMEM:
17289 assert(Subtarget->hasSSE42() &&
17290 "Target must have SSE4.2 or AVX features enabled");
17291 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17293 // Thread synchronization.
17295 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17299 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17301 // Atomic Lowering.
17302 case X86::ATOMAND8:
17303 case X86::ATOMAND16:
17304 case X86::ATOMAND32:
17305 case X86::ATOMAND64:
17308 case X86::ATOMOR16:
17309 case X86::ATOMOR32:
17310 case X86::ATOMOR64:
17312 case X86::ATOMXOR16:
17313 case X86::ATOMXOR8:
17314 case X86::ATOMXOR32:
17315 case X86::ATOMXOR64:
17317 case X86::ATOMNAND8:
17318 case X86::ATOMNAND16:
17319 case X86::ATOMNAND32:
17320 case X86::ATOMNAND64:
17322 case X86::ATOMMAX8:
17323 case X86::ATOMMAX16:
17324 case X86::ATOMMAX32:
17325 case X86::ATOMMAX64:
17327 case X86::ATOMMIN8:
17328 case X86::ATOMMIN16:
17329 case X86::ATOMMIN32:
17330 case X86::ATOMMIN64:
17332 case X86::ATOMUMAX8:
17333 case X86::ATOMUMAX16:
17334 case X86::ATOMUMAX32:
17335 case X86::ATOMUMAX64:
17337 case X86::ATOMUMIN8:
17338 case X86::ATOMUMIN16:
17339 case X86::ATOMUMIN32:
17340 case X86::ATOMUMIN64:
17341 return EmitAtomicLoadArith(MI, BB);
17343 // This group does 64-bit operations on a 32-bit host.
17344 case X86::ATOMAND6432:
17345 case X86::ATOMOR6432:
17346 case X86::ATOMXOR6432:
17347 case X86::ATOMNAND6432:
17348 case X86::ATOMADD6432:
17349 case X86::ATOMSUB6432:
17350 case X86::ATOMMAX6432:
17351 case X86::ATOMMIN6432:
17352 case X86::ATOMUMAX6432:
17353 case X86::ATOMUMIN6432:
17354 case X86::ATOMSWAP6432:
17355 return EmitAtomicLoadArith6432(MI, BB);
17357 case X86::VASTART_SAVE_XMM_REGS:
17358 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17360 case X86::VAARG_64:
17361 return EmitVAARG64WithCustomInserter(MI, BB);
17363 case X86::EH_SjLj_SetJmp32:
17364 case X86::EH_SjLj_SetJmp64:
17365 return emitEHSjLjSetJmp(MI, BB);
17367 case X86::EH_SjLj_LongJmp32:
17368 case X86::EH_SjLj_LongJmp64:
17369 return emitEHSjLjLongJmp(MI, BB);
17371 case TargetOpcode::STACKMAP:
17372 case TargetOpcode::PATCHPOINT:
17373 return emitPatchPoint(MI, BB);
17375 case X86::VFMADDPDr213r:
17376 case X86::VFMADDPSr213r:
17377 case X86::VFMADDSDr213r:
17378 case X86::VFMADDSSr213r:
17379 case X86::VFMSUBPDr213r:
17380 case X86::VFMSUBPSr213r:
17381 case X86::VFMSUBSDr213r:
17382 case X86::VFMSUBSSr213r:
17383 case X86::VFNMADDPDr213r:
17384 case X86::VFNMADDPSr213r:
17385 case X86::VFNMADDSDr213r:
17386 case X86::VFNMADDSSr213r:
17387 case X86::VFNMSUBPDr213r:
17388 case X86::VFNMSUBPSr213r:
17389 case X86::VFNMSUBSDr213r:
17390 case X86::VFNMSUBSSr213r:
17391 case X86::VFMADDPDr213rY:
17392 case X86::VFMADDPSr213rY:
17393 case X86::VFMSUBPDr213rY:
17394 case X86::VFMSUBPSr213rY:
17395 case X86::VFNMADDPDr213rY:
17396 case X86::VFNMADDPSr213rY:
17397 case X86::VFNMSUBPDr213rY:
17398 case X86::VFNMSUBPSr213rY:
17399 return emitFMA3Instr(MI, BB);
17403 //===----------------------------------------------------------------------===//
17404 // X86 Optimization Hooks
17405 //===----------------------------------------------------------------------===//
17407 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17410 const SelectionDAG &DAG,
17411 unsigned Depth) const {
17412 unsigned BitWidth = KnownZero.getBitWidth();
17413 unsigned Opc = Op.getOpcode();
17414 assert((Opc >= ISD::BUILTIN_OP_END ||
17415 Opc == ISD::INTRINSIC_WO_CHAIN ||
17416 Opc == ISD::INTRINSIC_W_CHAIN ||
17417 Opc == ISD::INTRINSIC_VOID) &&
17418 "Should use MaskedValueIsZero if you don't know whether Op"
17419 " is a target node!");
17421 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17435 // These nodes' second result is a boolean.
17436 if (Op.getResNo() == 0)
17439 case X86ISD::SETCC:
17440 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17442 case ISD::INTRINSIC_WO_CHAIN: {
17443 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17444 unsigned NumLoBits = 0;
17447 case Intrinsic::x86_sse_movmsk_ps:
17448 case Intrinsic::x86_avx_movmsk_ps_256:
17449 case Intrinsic::x86_sse2_movmsk_pd:
17450 case Intrinsic::x86_avx_movmsk_pd_256:
17451 case Intrinsic::x86_mmx_pmovmskb:
17452 case Intrinsic::x86_sse2_pmovmskb_128:
17453 case Intrinsic::x86_avx2_pmovmskb: {
17454 // High bits of movmskp{s|d}, pmovmskb are known zero.
17456 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17457 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17458 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17459 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17460 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17461 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17462 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17463 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17465 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17474 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17476 const SelectionDAG &,
17477 unsigned Depth) const {
17478 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17479 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17480 return Op.getValueType().getScalarType().getSizeInBits();
17486 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17487 /// node is a GlobalAddress + offset.
17488 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17489 const GlobalValue* &GA,
17490 int64_t &Offset) const {
17491 if (N->getOpcode() == X86ISD::Wrapper) {
17492 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17493 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17494 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17498 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17501 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17502 /// same as extracting the high 128-bit part of 256-bit vector and then
17503 /// inserting the result into the low part of a new 256-bit vector
17504 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17505 EVT VT = SVOp->getValueType(0);
17506 unsigned NumElems = VT.getVectorNumElements();
17508 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17509 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17510 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17511 SVOp->getMaskElt(j) >= 0)
17517 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17518 /// same as extracting the low 128-bit part of 256-bit vector and then
17519 /// inserting the result into the high part of a new 256-bit vector
17520 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17521 EVT VT = SVOp->getValueType(0);
17522 unsigned NumElems = VT.getVectorNumElements();
17524 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17525 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17526 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17527 SVOp->getMaskElt(j) >= 0)
17533 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17534 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17535 TargetLowering::DAGCombinerInfo &DCI,
17536 const X86Subtarget* Subtarget) {
17538 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17539 SDValue V1 = SVOp->getOperand(0);
17540 SDValue V2 = SVOp->getOperand(1);
17541 EVT VT = SVOp->getValueType(0);
17542 unsigned NumElems = VT.getVectorNumElements();
17544 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17545 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17549 // V UNDEF BUILD_VECTOR UNDEF
17551 // CONCAT_VECTOR CONCAT_VECTOR
17554 // RESULT: V + zero extended
17556 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17557 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17558 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17561 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17564 // To match the shuffle mask, the first half of the mask should
17565 // be exactly the first vector, and all the rest a splat with the
17566 // first element of the second one.
17567 for (unsigned i = 0; i != NumElems/2; ++i)
17568 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17569 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17572 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17573 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17574 if (Ld->hasNUsesOfValue(1, 0)) {
17575 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17576 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17578 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17580 Ld->getPointerInfo(),
17581 Ld->getAlignment(),
17582 false/*isVolatile*/, true/*ReadMem*/,
17583 false/*WriteMem*/);
17585 // Make sure the newly-created LOAD is in the same position as Ld in
17586 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17587 // and update uses of Ld's output chain to use the TokenFactor.
17588 if (Ld->hasAnyUseOfValue(1)) {
17589 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17590 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17591 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17592 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17593 SDValue(ResNode.getNode(), 1));
17596 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17600 // Emit a zeroed vector and insert the desired subvector on its
17602 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17603 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17604 return DCI.CombineTo(N, InsV);
17607 //===--------------------------------------------------------------------===//
17608 // Combine some shuffles into subvector extracts and inserts:
17611 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17612 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17613 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17614 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17615 return DCI.CombineTo(N, InsV);
17618 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17619 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17620 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17621 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17622 return DCI.CombineTo(N, InsV);
17628 /// PerformShuffleCombine - Performs several different shuffle combines.
17629 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17630 TargetLowering::DAGCombinerInfo &DCI,
17631 const X86Subtarget *Subtarget) {
17633 SDValue N0 = N->getOperand(0);
17634 SDValue N1 = N->getOperand(1);
17635 EVT VT = N->getValueType(0);
17637 // Don't create instructions with illegal types after legalize types has run.
17638 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17639 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17642 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17643 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17644 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17645 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17647 // During Type Legalization, when promoting illegal vector types,
17648 // the backend might introduce new shuffle dag nodes and bitcasts.
17650 // This code performs the following transformation:
17651 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17652 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17654 // We do this only if both the bitcast and the BINOP dag nodes have
17655 // one use. Also, perform this transformation only if the new binary
17656 // operation is legal. This is to avoid introducing dag nodes that
17657 // potentially need to be further expanded (or custom lowered) into a
17658 // less optimal sequence of dag nodes.
17659 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17660 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17661 N0.getOpcode() == ISD::BITCAST) {
17662 SDValue BC0 = N0.getOperand(0);
17663 EVT SVT = BC0.getValueType();
17664 unsigned Opcode = BC0.getOpcode();
17665 unsigned NumElts = VT.getVectorNumElements();
17667 if (BC0.hasOneUse() && SVT.isVector() &&
17668 SVT.getVectorNumElements() * 2 == NumElts &&
17669 TLI.isOperationLegal(Opcode, VT)) {
17670 bool CanFold = false;
17682 unsigned SVTNumElts = SVT.getVectorNumElements();
17683 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17684 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17685 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17686 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17687 CanFold = SVOp->getMaskElt(i) < 0;
17690 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17691 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17692 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17693 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17698 // Only handle 128 wide vector from here on.
17699 if (!VT.is128BitVector())
17702 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17703 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17704 // consecutive, non-overlapping, and in the right order.
17705 SmallVector<SDValue, 16> Elts;
17706 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17707 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17709 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17712 /// PerformTruncateCombine - Converts truncate operation to
17713 /// a sequence of vector shuffle operations.
17714 /// It is possible when we truncate 256-bit vector to 128-bit vector
17715 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17716 TargetLowering::DAGCombinerInfo &DCI,
17717 const X86Subtarget *Subtarget) {
17721 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17722 /// specific shuffle of a load can be folded into a single element load.
17723 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17724 /// shuffles have been customed lowered so we need to handle those here.
17725 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17726 TargetLowering::DAGCombinerInfo &DCI) {
17727 if (DCI.isBeforeLegalizeOps())
17730 SDValue InVec = N->getOperand(0);
17731 SDValue EltNo = N->getOperand(1);
17733 if (!isa<ConstantSDNode>(EltNo))
17736 EVT VT = InVec.getValueType();
17738 bool HasShuffleIntoBitcast = false;
17739 if (InVec.getOpcode() == ISD::BITCAST) {
17740 // Don't duplicate a load with other uses.
17741 if (!InVec.hasOneUse())
17743 EVT BCVT = InVec.getOperand(0).getValueType();
17744 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17746 InVec = InVec.getOperand(0);
17747 HasShuffleIntoBitcast = true;
17750 if (!isTargetShuffle(InVec.getOpcode()))
17753 // Don't duplicate a load with other uses.
17754 if (!InVec.hasOneUse())
17757 SmallVector<int, 16> ShuffleMask;
17759 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17763 // Select the input vector, guarding against out of range extract vector.
17764 unsigned NumElems = VT.getVectorNumElements();
17765 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17766 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17767 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17768 : InVec.getOperand(1);
17770 // If inputs to shuffle are the same for both ops, then allow 2 uses
17771 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17773 if (LdNode.getOpcode() == ISD::BITCAST) {
17774 // Don't duplicate a load with other uses.
17775 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17778 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17779 LdNode = LdNode.getOperand(0);
17782 if (!ISD::isNormalLoad(LdNode.getNode()))
17785 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17787 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17790 if (HasShuffleIntoBitcast) {
17791 // If there's a bitcast before the shuffle, check if the load type and
17792 // alignment is valid.
17793 unsigned Align = LN0->getAlignment();
17794 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17795 unsigned NewAlign = TLI.getDataLayout()->
17796 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17798 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17802 // All checks match so transform back to vector_shuffle so that DAG combiner
17803 // can finish the job
17806 // Create shuffle node taking into account the case that its a unary shuffle
17807 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17808 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17809 InVec.getOperand(0), Shuffle,
17811 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17812 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17816 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17817 /// generation and convert it from being a bunch of shuffles and extracts
17818 /// to a simple store and scalar loads to extract the elements.
17819 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17820 TargetLowering::DAGCombinerInfo &DCI) {
17821 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17822 if (NewOp.getNode())
17825 SDValue InputVector = N->getOperand(0);
17827 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17828 // from mmx to v2i32 has a single usage.
17829 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17830 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17831 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17832 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17833 N->getValueType(0),
17834 InputVector.getNode()->getOperand(0));
17836 // Only operate on vectors of 4 elements, where the alternative shuffling
17837 // gets to be more expensive.
17838 if (InputVector.getValueType() != MVT::v4i32)
17841 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17842 // single use which is a sign-extend or zero-extend, and all elements are
17844 SmallVector<SDNode *, 4> Uses;
17845 unsigned ExtractedElements = 0;
17846 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17847 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17848 if (UI.getUse().getResNo() != InputVector.getResNo())
17851 SDNode *Extract = *UI;
17852 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17855 if (Extract->getValueType(0) != MVT::i32)
17857 if (!Extract->hasOneUse())
17859 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17860 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17862 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17865 // Record which element was extracted.
17866 ExtractedElements |=
17867 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17869 Uses.push_back(Extract);
17872 // If not all the elements were used, this may not be worthwhile.
17873 if (ExtractedElements != 15)
17876 // Ok, we've now decided to do the transformation.
17877 SDLoc dl(InputVector);
17879 // Store the value to a temporary stack slot.
17880 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17881 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17882 MachinePointerInfo(), false, false, 0);
17884 // Replace each use (extract) with a load of the appropriate element.
17885 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17886 UE = Uses.end(); UI != UE; ++UI) {
17887 SDNode *Extract = *UI;
17889 // cOMpute the element's address.
17890 SDValue Idx = Extract->getOperand(1);
17892 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17893 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17894 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17895 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17897 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17898 StackPtr, OffsetVal);
17900 // Load the scalar.
17901 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17902 ScalarAddr, MachinePointerInfo(),
17903 false, false, false, 0);
17905 // Replace the exact with the load.
17906 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17909 // The replacement was made in place; don't return anything.
17913 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17914 static std::pair<unsigned, bool>
17915 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17916 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17917 if (!VT.isVector())
17918 return std::make_pair(0, false);
17920 bool NeedSplit = false;
17921 switch (VT.getSimpleVT().SimpleTy) {
17922 default: return std::make_pair(0, false);
17926 if (!Subtarget->hasAVX2())
17928 if (!Subtarget->hasAVX())
17929 return std::make_pair(0, false);
17934 if (!Subtarget->hasSSE2())
17935 return std::make_pair(0, false);
17938 // SSE2 has only a small subset of the operations.
17939 bool hasUnsigned = Subtarget->hasSSE41() ||
17940 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17941 bool hasSigned = Subtarget->hasSSE41() ||
17942 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17944 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17947 // Check for x CC y ? x : y.
17948 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17949 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17954 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17957 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17960 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17963 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17965 // Check for x CC y ? y : x -- a min/max with reversed arms.
17966 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17967 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17972 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17975 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17978 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17981 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17985 return std::make_pair(Opc, NeedSplit);
17989 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
17990 const X86Subtarget *Subtarget) {
17992 SDValue Cond = N->getOperand(0);
17993 SDValue LHS = N->getOperand(1);
17994 SDValue RHS = N->getOperand(2);
17996 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
17997 SDValue CondSrc = Cond->getOperand(0);
17998 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
17999 Cond = CondSrc->getOperand(0);
18002 MVT VT = N->getSimpleValueType(0);
18003 MVT EltVT = VT.getVectorElementType();
18004 unsigned NumElems = VT.getVectorNumElements();
18005 // There is no blend with immediate in AVX-512.
18006 if (VT.is512BitVector())
18009 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
18011 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
18014 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
18017 unsigned MaskValue = 0;
18018 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18021 SmallVector<int, 8> ShuffleMask(NumElems, -1);
18022 for (unsigned i = 0; i < NumElems; ++i) {
18023 // Be sure we emit undef where we can.
18024 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18025 ShuffleMask[i] = -1;
18027 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18030 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18033 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18035 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18036 TargetLowering::DAGCombinerInfo &DCI,
18037 const X86Subtarget *Subtarget) {
18039 SDValue Cond = N->getOperand(0);
18040 // Get the LHS/RHS of the select.
18041 SDValue LHS = N->getOperand(1);
18042 SDValue RHS = N->getOperand(2);
18043 EVT VT = LHS.getValueType();
18044 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18046 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18047 // instructions match the semantics of the common C idiom x<y?x:y but not
18048 // x<=y?x:y, because of how they handle negative zero (which can be
18049 // ignored in unsafe-math mode).
18050 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18051 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18052 (Subtarget->hasSSE2() ||
18053 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18054 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18056 unsigned Opcode = 0;
18057 // Check for x CC y ? x : y.
18058 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18059 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18063 // Converting this to a min would handle NaNs incorrectly, and swapping
18064 // the operands would cause it to handle comparisons between positive
18065 // and negative zero incorrectly.
18066 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18067 if (!DAG.getTarget().Options.UnsafeFPMath &&
18068 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18070 std::swap(LHS, RHS);
18072 Opcode = X86ISD::FMIN;
18075 // Converting this to a min would handle comparisons between positive
18076 // and negative zero incorrectly.
18077 if (!DAG.getTarget().Options.UnsafeFPMath &&
18078 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18080 Opcode = X86ISD::FMIN;
18083 // Converting this to a min would handle both negative zeros and NaNs
18084 // incorrectly, but we can swap the operands to fix both.
18085 std::swap(LHS, RHS);
18089 Opcode = X86ISD::FMIN;
18093 // Converting this to a max would handle comparisons between positive
18094 // and negative zero incorrectly.
18095 if (!DAG.getTarget().Options.UnsafeFPMath &&
18096 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18098 Opcode = X86ISD::FMAX;
18101 // Converting this to a max would handle NaNs incorrectly, and swapping
18102 // the operands would cause it to handle comparisons between positive
18103 // and negative zero incorrectly.
18104 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18105 if (!DAG.getTarget().Options.UnsafeFPMath &&
18106 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18108 std::swap(LHS, RHS);
18110 Opcode = X86ISD::FMAX;
18113 // Converting this to a max would handle both negative zeros and NaNs
18114 // incorrectly, but we can swap the operands to fix both.
18115 std::swap(LHS, RHS);
18119 Opcode = X86ISD::FMAX;
18122 // Check for x CC y ? y : x -- a min/max with reversed arms.
18123 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18124 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18128 // Converting this to a min would handle comparisons between positive
18129 // and negative zero incorrectly, and swapping the operands would
18130 // cause it to handle NaNs incorrectly.
18131 if (!DAG.getTarget().Options.UnsafeFPMath &&
18132 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18133 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18135 std::swap(LHS, RHS);
18137 Opcode = X86ISD::FMIN;
18140 // Converting this to a min would handle NaNs incorrectly.
18141 if (!DAG.getTarget().Options.UnsafeFPMath &&
18142 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18144 Opcode = X86ISD::FMIN;
18147 // Converting this to a min would handle both negative zeros and NaNs
18148 // incorrectly, but we can swap the operands to fix both.
18149 std::swap(LHS, RHS);
18153 Opcode = X86ISD::FMIN;
18157 // Converting this to a max would handle NaNs incorrectly.
18158 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18160 Opcode = X86ISD::FMAX;
18163 // Converting this to a max would handle comparisons between positive
18164 // and negative zero incorrectly, and swapping the operands would
18165 // cause it to handle NaNs incorrectly.
18166 if (!DAG.getTarget().Options.UnsafeFPMath &&
18167 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18168 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18170 std::swap(LHS, RHS);
18172 Opcode = X86ISD::FMAX;
18175 // Converting this to a max would handle both negative zeros and NaNs
18176 // incorrectly, but we can swap the operands to fix both.
18177 std::swap(LHS, RHS);
18181 Opcode = X86ISD::FMAX;
18187 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18190 EVT CondVT = Cond.getValueType();
18191 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18192 CondVT.getVectorElementType() == MVT::i1) {
18193 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18194 // lowering on AVX-512. In this case we convert it to
18195 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18196 // The same situation for all 128 and 256-bit vectors of i8 and i16
18197 EVT OpVT = LHS.getValueType();
18198 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18199 (OpVT.getVectorElementType() == MVT::i8 ||
18200 OpVT.getVectorElementType() == MVT::i16)) {
18201 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18202 DCI.AddToWorklist(Cond.getNode());
18203 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18206 // If this is a select between two integer constants, try to do some
18208 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18209 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18210 // Don't do this for crazy integer types.
18211 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18212 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18213 // so that TrueC (the true value) is larger than FalseC.
18214 bool NeedsCondInvert = false;
18216 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18217 // Efficiently invertible.
18218 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
18219 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
18220 isa<ConstantSDNode>(Cond.getOperand(1))))) {
18221 NeedsCondInvert = true;
18222 std::swap(TrueC, FalseC);
18225 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
18226 if (FalseC->getAPIntValue() == 0 &&
18227 TrueC->getAPIntValue().isPowerOf2()) {
18228 if (NeedsCondInvert) // Invert the condition if needed.
18229 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18230 DAG.getConstant(1, Cond.getValueType()));
18232 // Zero extend the condition if needed.
18233 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18235 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18236 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18237 DAG.getConstant(ShAmt, MVT::i8));
18240 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18241 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18242 if (NeedsCondInvert) // Invert the condition if needed.
18243 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18244 DAG.getConstant(1, Cond.getValueType()));
18246 // Zero extend the condition if needed.
18247 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18248 FalseC->getValueType(0), Cond);
18249 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18250 SDValue(FalseC, 0));
18253 // Optimize cases that will turn into an LEA instruction. This requires
18254 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18255 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18256 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18257 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18259 bool isFastMultiplier = false;
18261 switch ((unsigned char)Diff) {
18263 case 1: // result = add base, cond
18264 case 2: // result = lea base( , cond*2)
18265 case 3: // result = lea base(cond, cond*2)
18266 case 4: // result = lea base( , cond*4)
18267 case 5: // result = lea base(cond, cond*4)
18268 case 8: // result = lea base( , cond*8)
18269 case 9: // result = lea base(cond, cond*8)
18270 isFastMultiplier = true;
18275 if (isFastMultiplier) {
18276 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18277 if (NeedsCondInvert) // Invert the condition if needed.
18278 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18279 DAG.getConstant(1, Cond.getValueType()));
18281 // Zero extend the condition if needed.
18282 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18284 // Scale the condition by the difference.
18286 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18287 DAG.getConstant(Diff, Cond.getValueType()));
18289 // Add the base if non-zero.
18290 if (FalseC->getAPIntValue() != 0)
18291 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18292 SDValue(FalseC, 0));
18299 // Canonicalize max and min:
18300 // (x > y) ? x : y -> (x >= y) ? x : y
18301 // (x < y) ? x : y -> (x <= y) ? x : y
18302 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18303 // the need for an extra compare
18304 // against zero. e.g.
18305 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18307 // testl %edi, %edi
18309 // cmovgl %edi, %eax
18313 // cmovsl %eax, %edi
18314 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18315 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18316 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18317 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18322 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18323 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18324 Cond.getOperand(0), Cond.getOperand(1), NewCC);
18325 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18330 // Early exit check
18331 if (!TLI.isTypeLegal(VT))
18334 // Match VSELECTs into subs with unsigned saturation.
18335 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18336 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18337 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18338 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18339 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18341 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18342 // left side invert the predicate to simplify logic below.
18344 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18346 CC = ISD::getSetCCInverse(CC, true);
18347 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18351 if (Other.getNode() && Other->getNumOperands() == 2 &&
18352 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18353 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18354 SDValue CondRHS = Cond->getOperand(1);
18356 // Look for a general sub with unsigned saturation first.
18357 // x >= y ? x-y : 0 --> subus x, y
18358 // x > y ? x-y : 0 --> subus x, y
18359 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18360 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18361 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18363 // If the RHS is a constant we have to reverse the const canonicalization.
18364 // x > C-1 ? x+-C : 0 --> subus x, C
18365 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18366 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18367 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18368 if (CondRHS.getConstantOperandVal(0) == -A-1)
18369 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18370 DAG.getConstant(-A, VT));
18373 // Another special case: If C was a sign bit, the sub has been
18374 // canonicalized into a xor.
18375 // FIXME: Would it be better to use computeKnownBits to determine whether
18376 // it's safe to decanonicalize the xor?
18377 // x s< 0 ? x^C : 0 --> subus x, C
18378 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18379 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18380 isSplatVector(OpRHS.getNode())) {
18381 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18383 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18388 // Try to match a min/max vector operation.
18389 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18390 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18391 unsigned Opc = ret.first;
18392 bool NeedSplit = ret.second;
18394 if (Opc && NeedSplit) {
18395 unsigned NumElems = VT.getVectorNumElements();
18396 // Extract the LHS vectors
18397 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18398 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18400 // Extract the RHS vectors
18401 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18402 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18404 // Create min/max for each subvector
18405 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18406 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18408 // Merge the result
18409 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18411 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18414 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18415 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18416 // Check if SETCC has already been promoted
18417 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18418 // Check that condition value type matches vselect operand type
18421 assert(Cond.getValueType().isVector() &&
18422 "vector select expects a vector selector!");
18424 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18425 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18427 if (!TValIsAllOnes && !FValIsAllZeros) {
18428 // Try invert the condition if true value is not all 1s and false value
18430 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18431 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18433 if (TValIsAllZeros || FValIsAllOnes) {
18434 SDValue CC = Cond.getOperand(2);
18435 ISD::CondCode NewCC =
18436 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18437 Cond.getOperand(0).getValueType().isInteger());
18438 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18439 std::swap(LHS, RHS);
18440 TValIsAllOnes = FValIsAllOnes;
18441 FValIsAllZeros = TValIsAllZeros;
18445 if (TValIsAllOnes || FValIsAllZeros) {
18448 if (TValIsAllOnes && FValIsAllZeros)
18450 else if (TValIsAllOnes)
18451 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18452 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18453 else if (FValIsAllZeros)
18454 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18455 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18457 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18461 // Try to fold this VSELECT into a MOVSS/MOVSD
18462 if (N->getOpcode() == ISD::VSELECT &&
18463 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18464 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18465 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18466 bool CanFold = false;
18467 unsigned NumElems = Cond.getNumOperands();
18471 if (isZero(Cond.getOperand(0))) {
18474 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18475 // fold (vselect <0,-1> -> (movsd A, B)
18476 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18477 CanFold = isAllOnes(Cond.getOperand(i));
18478 } else if (isAllOnes(Cond.getOperand(0))) {
18482 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18483 // fold (vselect <-1,0> -> (movsd B, A)
18484 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18485 CanFold = isZero(Cond.getOperand(i));
18489 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18490 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18491 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18494 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18495 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18496 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18497 // (v2i64 (bitcast B)))))
18499 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18500 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18501 // (v2f64 (bitcast B)))))
18503 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18504 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18505 // (v2i64 (bitcast A)))))
18507 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18508 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18509 // (v2f64 (bitcast A)))))
18511 CanFold = (isZero(Cond.getOperand(0)) &&
18512 isZero(Cond.getOperand(1)) &&
18513 isAllOnes(Cond.getOperand(2)) &&
18514 isAllOnes(Cond.getOperand(3)));
18516 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18517 isAllOnes(Cond.getOperand(1)) &&
18518 isZero(Cond.getOperand(2)) &&
18519 isZero(Cond.getOperand(3))) {
18521 std::swap(LHS, RHS);
18525 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18526 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18527 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18528 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18530 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18536 // If we know that this node is legal then we know that it is going to be
18537 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18538 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18539 // to simplify previous instructions.
18540 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18541 !DCI.isBeforeLegalize() &&
18542 // We explicitly check against v8i16 and v16i16 because, although
18543 // they're marked as Custom, they might only be legal when Cond is a
18544 // build_vector of constants. This will be taken care in a later
18546 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18547 VT != MVT::v8i16)) {
18548 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18550 // Don't optimize vector selects that map to mask-registers.
18554 // Check all uses of that condition operand to check whether it will be
18555 // consumed by non-BLEND instructions, which may depend on all bits are set
18557 for (SDNode::use_iterator I = Cond->use_begin(),
18558 E = Cond->use_end(); I != E; ++I)
18559 if (I->getOpcode() != ISD::VSELECT)
18560 // TODO: Add other opcodes eventually lowered into BLEND.
18563 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18564 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18566 APInt KnownZero, KnownOne;
18567 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18568 DCI.isBeforeLegalizeOps());
18569 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18570 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18571 DCI.CommitTargetLoweringOpt(TLO);
18574 // We should generate an X86ISD::BLENDI from a vselect if its argument
18575 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18576 // constants. This specific pattern gets generated when we split a
18577 // selector for a 512 bit vector in a machine without AVX512 (but with
18578 // 256-bit vectors), during legalization:
18580 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18582 // Iff we find this pattern and the build_vectors are built from
18583 // constants, we translate the vselect into a shuffle_vector that we
18584 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18585 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18586 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18587 if (Shuffle.getNode())
18594 // Check whether a boolean test is testing a boolean value generated by
18595 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18598 // Simplify the following patterns:
18599 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18600 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18601 // to (Op EFLAGS Cond)
18603 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18604 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18605 // to (Op EFLAGS !Cond)
18607 // where Op could be BRCOND or CMOV.
18609 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18610 // Quit if not CMP and SUB with its value result used.
18611 if (Cmp.getOpcode() != X86ISD::CMP &&
18612 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18615 // Quit if not used as a boolean value.
18616 if (CC != X86::COND_E && CC != X86::COND_NE)
18619 // Check CMP operands. One of them should be 0 or 1 and the other should be
18620 // an SetCC or extended from it.
18621 SDValue Op1 = Cmp.getOperand(0);
18622 SDValue Op2 = Cmp.getOperand(1);
18625 const ConstantSDNode* C = nullptr;
18626 bool needOppositeCond = (CC == X86::COND_E);
18627 bool checkAgainstTrue = false; // Is it a comparison against 1?
18629 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18631 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18633 else // Quit if all operands are not constants.
18636 if (C->getZExtValue() == 1) {
18637 needOppositeCond = !needOppositeCond;
18638 checkAgainstTrue = true;
18639 } else if (C->getZExtValue() != 0)
18640 // Quit if the constant is neither 0 or 1.
18643 bool truncatedToBoolWithAnd = false;
18644 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18645 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18646 SetCC.getOpcode() == ISD::TRUNCATE ||
18647 SetCC.getOpcode() == ISD::AND) {
18648 if (SetCC.getOpcode() == ISD::AND) {
18650 ConstantSDNode *CS;
18651 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18652 CS->getZExtValue() == 1)
18654 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18655 CS->getZExtValue() == 1)
18659 SetCC = SetCC.getOperand(OpIdx);
18660 truncatedToBoolWithAnd = true;
18662 SetCC = SetCC.getOperand(0);
18665 switch (SetCC.getOpcode()) {
18666 case X86ISD::SETCC_CARRY:
18667 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18668 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18669 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18670 // truncated to i1 using 'and'.
18671 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18673 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18674 "Invalid use of SETCC_CARRY!");
18676 case X86ISD::SETCC:
18677 // Set the condition code or opposite one if necessary.
18678 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18679 if (needOppositeCond)
18680 CC = X86::GetOppositeBranchCondition(CC);
18681 return SetCC.getOperand(1);
18682 case X86ISD::CMOV: {
18683 // Check whether false/true value has canonical one, i.e. 0 or 1.
18684 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18685 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18686 // Quit if true value is not a constant.
18689 // Quit if false value is not a constant.
18691 SDValue Op = SetCC.getOperand(0);
18692 // Skip 'zext' or 'trunc' node.
18693 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18694 Op.getOpcode() == ISD::TRUNCATE)
18695 Op = Op.getOperand(0);
18696 // A special case for rdrand/rdseed, where 0 is set if false cond is
18698 if ((Op.getOpcode() != X86ISD::RDRAND &&
18699 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18702 // Quit if false value is not the constant 0 or 1.
18703 bool FValIsFalse = true;
18704 if (FVal && FVal->getZExtValue() != 0) {
18705 if (FVal->getZExtValue() != 1)
18707 // If FVal is 1, opposite cond is needed.
18708 needOppositeCond = !needOppositeCond;
18709 FValIsFalse = false;
18711 // Quit if TVal is not the constant opposite of FVal.
18712 if (FValIsFalse && TVal->getZExtValue() != 1)
18714 if (!FValIsFalse && TVal->getZExtValue() != 0)
18716 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18717 if (needOppositeCond)
18718 CC = X86::GetOppositeBranchCondition(CC);
18719 return SetCC.getOperand(3);
18726 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18727 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18728 TargetLowering::DAGCombinerInfo &DCI,
18729 const X86Subtarget *Subtarget) {
18732 // If the flag operand isn't dead, don't touch this CMOV.
18733 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18736 SDValue FalseOp = N->getOperand(0);
18737 SDValue TrueOp = N->getOperand(1);
18738 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18739 SDValue Cond = N->getOperand(3);
18741 if (CC == X86::COND_E || CC == X86::COND_NE) {
18742 switch (Cond.getOpcode()) {
18746 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18747 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18748 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18754 Flags = checkBoolTestSetCCCombine(Cond, CC);
18755 if (Flags.getNode() &&
18756 // Extra check as FCMOV only supports a subset of X86 cond.
18757 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18758 SDValue Ops[] = { FalseOp, TrueOp,
18759 DAG.getConstant(CC, MVT::i8), Flags };
18760 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18763 // If this is a select between two integer constants, try to do some
18764 // optimizations. Note that the operands are ordered the opposite of SELECT
18766 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18767 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18768 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18769 // larger than FalseC (the false value).
18770 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18771 CC = X86::GetOppositeBranchCondition(CC);
18772 std::swap(TrueC, FalseC);
18773 std::swap(TrueOp, FalseOp);
18776 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18777 // This is efficient for any integer data type (including i8/i16) and
18779 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18780 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18781 DAG.getConstant(CC, MVT::i8), Cond);
18783 // Zero extend the condition if needed.
18784 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18786 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18787 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18788 DAG.getConstant(ShAmt, MVT::i8));
18789 if (N->getNumValues() == 2) // Dead flag value?
18790 return DCI.CombineTo(N, Cond, SDValue());
18794 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18795 // for any integer data type, including i8/i16.
18796 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18797 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18798 DAG.getConstant(CC, MVT::i8), Cond);
18800 // Zero extend the condition if needed.
18801 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18802 FalseC->getValueType(0), Cond);
18803 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18804 SDValue(FalseC, 0));
18806 if (N->getNumValues() == 2) // Dead flag value?
18807 return DCI.CombineTo(N, Cond, SDValue());
18811 // Optimize cases that will turn into an LEA instruction. This requires
18812 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18813 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18814 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18815 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18817 bool isFastMultiplier = false;
18819 switch ((unsigned char)Diff) {
18821 case 1: // result = add base, cond
18822 case 2: // result = lea base( , cond*2)
18823 case 3: // result = lea base(cond, cond*2)
18824 case 4: // result = lea base( , cond*4)
18825 case 5: // result = lea base(cond, cond*4)
18826 case 8: // result = lea base( , cond*8)
18827 case 9: // result = lea base(cond, cond*8)
18828 isFastMultiplier = true;
18833 if (isFastMultiplier) {
18834 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18835 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18836 DAG.getConstant(CC, MVT::i8), Cond);
18837 // Zero extend the condition if needed.
18838 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18840 // Scale the condition by the difference.
18842 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18843 DAG.getConstant(Diff, Cond.getValueType()));
18845 // Add the base if non-zero.
18846 if (FalseC->getAPIntValue() != 0)
18847 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18848 SDValue(FalseC, 0));
18849 if (N->getNumValues() == 2) // Dead flag value?
18850 return DCI.CombineTo(N, Cond, SDValue());
18857 // Handle these cases:
18858 // (select (x != c), e, c) -> select (x != c), e, x),
18859 // (select (x == c), c, e) -> select (x == c), x, e)
18860 // where the c is an integer constant, and the "select" is the combination
18861 // of CMOV and CMP.
18863 // The rationale for this change is that the conditional-move from a constant
18864 // needs two instructions, however, conditional-move from a register needs
18865 // only one instruction.
18867 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18868 // some instruction-combining opportunities. This opt needs to be
18869 // postponed as late as possible.
18871 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18872 // the DCI.xxxx conditions are provided to postpone the optimization as
18873 // late as possible.
18875 ConstantSDNode *CmpAgainst = nullptr;
18876 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18877 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18878 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18880 if (CC == X86::COND_NE &&
18881 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18882 CC = X86::GetOppositeBranchCondition(CC);
18883 std::swap(TrueOp, FalseOp);
18886 if (CC == X86::COND_E &&
18887 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18888 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18889 DAG.getConstant(CC, MVT::i8), Cond };
18890 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18898 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18899 const X86Subtarget *Subtarget) {
18900 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18902 default: return SDValue();
18903 // SSE/AVX/AVX2 blend intrinsics.
18904 case Intrinsic::x86_avx2_pblendvb:
18905 case Intrinsic::x86_avx2_pblendw:
18906 case Intrinsic::x86_avx2_pblendd_128:
18907 case Intrinsic::x86_avx2_pblendd_256:
18908 // Don't try to simplify this intrinsic if we don't have AVX2.
18909 if (!Subtarget->hasAVX2())
18912 case Intrinsic::x86_avx_blend_pd_256:
18913 case Intrinsic::x86_avx_blend_ps_256:
18914 case Intrinsic::x86_avx_blendv_pd_256:
18915 case Intrinsic::x86_avx_blendv_ps_256:
18916 // Don't try to simplify this intrinsic if we don't have AVX.
18917 if (!Subtarget->hasAVX())
18920 case Intrinsic::x86_sse41_pblendw:
18921 case Intrinsic::x86_sse41_blendpd:
18922 case Intrinsic::x86_sse41_blendps:
18923 case Intrinsic::x86_sse41_blendvps:
18924 case Intrinsic::x86_sse41_blendvpd:
18925 case Intrinsic::x86_sse41_pblendvb: {
18926 SDValue Op0 = N->getOperand(1);
18927 SDValue Op1 = N->getOperand(2);
18928 SDValue Mask = N->getOperand(3);
18930 // Don't try to simplify this intrinsic if we don't have SSE4.1.
18931 if (!Subtarget->hasSSE41())
18934 // fold (blend A, A, Mask) -> A
18937 // fold (blend A, B, allZeros) -> A
18938 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18940 // fold (blend A, B, allOnes) -> B
18941 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18944 // Simplify the case where the mask is a constant i32 value.
18945 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18946 if (C->isNullValue())
18948 if (C->isAllOnesValue())
18953 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18954 case Intrinsic::x86_sse2_psrai_w:
18955 case Intrinsic::x86_sse2_psrai_d:
18956 case Intrinsic::x86_avx2_psrai_w:
18957 case Intrinsic::x86_avx2_psrai_d:
18958 case Intrinsic::x86_sse2_psra_w:
18959 case Intrinsic::x86_sse2_psra_d:
18960 case Intrinsic::x86_avx2_psra_w:
18961 case Intrinsic::x86_avx2_psra_d: {
18962 SDValue Op0 = N->getOperand(1);
18963 SDValue Op1 = N->getOperand(2);
18964 EVT VT = Op0.getValueType();
18965 assert(VT.isVector() && "Expected a vector type!");
18967 if (isa<BuildVectorSDNode>(Op1))
18968 Op1 = Op1.getOperand(0);
18970 if (!isa<ConstantSDNode>(Op1))
18973 EVT SVT = VT.getVectorElementType();
18974 unsigned SVTBits = SVT.getSizeInBits();
18976 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18977 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18978 uint64_t ShAmt = C.getZExtValue();
18980 // Don't try to convert this shift into a ISD::SRA if the shift
18981 // count is bigger than or equal to the element size.
18982 if (ShAmt >= SVTBits)
18985 // Trivial case: if the shift count is zero, then fold this
18986 // into the first operand.
18990 // Replace this packed shift intrinsic with a target independent
18992 SDValue Splat = DAG.getConstant(C, VT);
18993 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18998 /// PerformMulCombine - Optimize a single multiply with constant into two
18999 /// in order to implement it with two cheaper instructions, e.g.
19000 /// LEA + SHL, LEA + LEA.
19001 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
19002 TargetLowering::DAGCombinerInfo &DCI) {
19003 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
19006 EVT VT = N->getValueType(0);
19007 if (VT != MVT::i64)
19010 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
19013 uint64_t MulAmt = C->getZExtValue();
19014 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
19017 uint64_t MulAmt1 = 0;
19018 uint64_t MulAmt2 = 0;
19019 if ((MulAmt % 9) == 0) {
19021 MulAmt2 = MulAmt / 9;
19022 } else if ((MulAmt % 5) == 0) {
19024 MulAmt2 = MulAmt / 5;
19025 } else if ((MulAmt % 3) == 0) {
19027 MulAmt2 = MulAmt / 3;
19030 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19033 if (isPowerOf2_64(MulAmt2) &&
19034 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19035 // If second multiplifer is pow2, issue it first. We want the multiply by
19036 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19038 std::swap(MulAmt1, MulAmt2);
19041 if (isPowerOf2_64(MulAmt1))
19042 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19043 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19045 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19046 DAG.getConstant(MulAmt1, VT));
19048 if (isPowerOf2_64(MulAmt2))
19049 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19050 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19052 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19053 DAG.getConstant(MulAmt2, VT));
19055 // Do not add new nodes to DAG combiner worklist.
19056 DCI.CombineTo(N, NewMul, false);
19061 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19062 SDValue N0 = N->getOperand(0);
19063 SDValue N1 = N->getOperand(1);
19064 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19065 EVT VT = N0.getValueType();
19067 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19068 // since the result of setcc_c is all zero's or all ones.
19069 if (VT.isInteger() && !VT.isVector() &&
19070 N1C && N0.getOpcode() == ISD::AND &&
19071 N0.getOperand(1).getOpcode() == ISD::Constant) {
19072 SDValue N00 = N0.getOperand(0);
19073 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19074 ((N00.getOpcode() == ISD::ANY_EXTEND ||
19075 N00.getOpcode() == ISD::ZERO_EXTEND) &&
19076 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19077 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19078 APInt ShAmt = N1C->getAPIntValue();
19079 Mask = Mask.shl(ShAmt);
19081 return DAG.getNode(ISD::AND, SDLoc(N), VT,
19082 N00, DAG.getConstant(Mask, VT));
19086 // Hardware support for vector shifts is sparse which makes us scalarize the
19087 // vector operations in many cases. Also, on sandybridge ADD is faster than
19089 // (shl V, 1) -> add V,V
19090 if (isSplatVector(N1.getNode())) {
19091 assert(N0.getValueType().isVector() && "Invalid vector shift type");
19092 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19093 // We shift all of the values by one. In many cases we do not have
19094 // hardware support for this operation. This is better expressed as an ADD
19096 if (N1C && (1 == N1C->getZExtValue())) {
19097 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19104 /// \brief Returns a vector of 0s if the node in input is a vector logical
19105 /// shift by a constant amount which is known to be bigger than or equal
19106 /// to the vector element size in bits.
19107 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19108 const X86Subtarget *Subtarget) {
19109 EVT VT = N->getValueType(0);
19111 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19112 (!Subtarget->hasInt256() ||
19113 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19116 SDValue Amt = N->getOperand(1);
19118 if (isSplatVector(Amt.getNode())) {
19119 SDValue SclrAmt = Amt->getOperand(0);
19120 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19121 APInt ShiftAmt = C->getAPIntValue();
19122 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19124 // SSE2/AVX2 logical shifts always return a vector of 0s
19125 // if the shift amount is bigger than or equal to
19126 // the element size. The constant shift amount will be
19127 // encoded as a 8-bit immediate.
19128 if (ShiftAmt.trunc(8).uge(MaxAmount))
19129 return getZeroVector(VT, Subtarget, DAG, DL);
19136 /// PerformShiftCombine - Combine shifts.
19137 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19138 TargetLowering::DAGCombinerInfo &DCI,
19139 const X86Subtarget *Subtarget) {
19140 if (N->getOpcode() == ISD::SHL) {
19141 SDValue V = PerformSHLCombine(N, DAG);
19142 if (V.getNode()) return V;
19145 if (N->getOpcode() != ISD::SRA) {
19146 // Try to fold this logical shift into a zero vector.
19147 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19148 if (V.getNode()) return V;
19154 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
19155 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19156 // and friends. Likewise for OR -> CMPNEQSS.
19157 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19158 TargetLowering::DAGCombinerInfo &DCI,
19159 const X86Subtarget *Subtarget) {
19162 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19163 // we're requiring SSE2 for both.
19164 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19165 SDValue N0 = N->getOperand(0);
19166 SDValue N1 = N->getOperand(1);
19167 SDValue CMP0 = N0->getOperand(1);
19168 SDValue CMP1 = N1->getOperand(1);
19171 // The SETCCs should both refer to the same CMP.
19172 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19175 SDValue CMP00 = CMP0->getOperand(0);
19176 SDValue CMP01 = CMP0->getOperand(1);
19177 EVT VT = CMP00.getValueType();
19179 if (VT == MVT::f32 || VT == MVT::f64) {
19180 bool ExpectingFlags = false;
19181 // Check for any users that want flags:
19182 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19183 !ExpectingFlags && UI != UE; ++UI)
19184 switch (UI->getOpcode()) {
19189 ExpectingFlags = true;
19191 case ISD::CopyToReg:
19192 case ISD::SIGN_EXTEND:
19193 case ISD::ZERO_EXTEND:
19194 case ISD::ANY_EXTEND:
19198 if (!ExpectingFlags) {
19199 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19200 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19202 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19203 X86::CondCode tmp = cc0;
19208 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
19209 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19210 // FIXME: need symbolic constants for these magic numbers.
19211 // See X86ATTInstPrinter.cpp:printSSECC().
19212 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19213 if (Subtarget->hasAVX512()) {
19214 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19215 CMP01, DAG.getConstant(x86cc, MVT::i8));
19216 if (N->getValueType(0) != MVT::i1)
19217 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19221 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19222 CMP00.getValueType(), CMP00, CMP01,
19223 DAG.getConstant(x86cc, MVT::i8));
19225 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19226 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19228 if (is64BitFP && !Subtarget->is64Bit()) {
19229 // On a 32-bit target, we cannot bitcast the 64-bit float to a
19230 // 64-bit integer, since that's not a legal type. Since
19231 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19232 // bits, but can do this little dance to extract the lowest 32 bits
19233 // and work with those going forward.
19234 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19236 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19238 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19239 Vector32, DAG.getIntPtrConstant(0));
19243 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19244 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19245 DAG.getConstant(1, IntVT));
19246 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19247 return OneBitOfTruth;
19255 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19256 /// so it can be folded inside ANDNP.
19257 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19258 EVT VT = N->getValueType(0);
19260 // Match direct AllOnes for 128 and 256-bit vectors
19261 if (ISD::isBuildVectorAllOnes(N))
19264 // Look through a bit convert.
19265 if (N->getOpcode() == ISD::BITCAST)
19266 N = N->getOperand(0).getNode();
19268 // Sometimes the operand may come from a insert_subvector building a 256-bit
19270 if (VT.is256BitVector() &&
19271 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19272 SDValue V1 = N->getOperand(0);
19273 SDValue V2 = N->getOperand(1);
19275 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19276 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19277 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19278 ISD::isBuildVectorAllOnes(V2.getNode()))
19285 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19286 // register. In most cases we actually compare or select YMM-sized registers
19287 // and mixing the two types creates horrible code. This method optimizes
19288 // some of the transition sequences.
19289 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19290 TargetLowering::DAGCombinerInfo &DCI,
19291 const X86Subtarget *Subtarget) {
19292 EVT VT = N->getValueType(0);
19293 if (!VT.is256BitVector())
19296 assert((N->getOpcode() == ISD::ANY_EXTEND ||
19297 N->getOpcode() == ISD::ZERO_EXTEND ||
19298 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19300 SDValue Narrow = N->getOperand(0);
19301 EVT NarrowVT = Narrow->getValueType(0);
19302 if (!NarrowVT.is128BitVector())
19305 if (Narrow->getOpcode() != ISD::XOR &&
19306 Narrow->getOpcode() != ISD::AND &&
19307 Narrow->getOpcode() != ISD::OR)
19310 SDValue N0 = Narrow->getOperand(0);
19311 SDValue N1 = Narrow->getOperand(1);
19314 // The Left side has to be a trunc.
19315 if (N0.getOpcode() != ISD::TRUNCATE)
19318 // The type of the truncated inputs.
19319 EVT WideVT = N0->getOperand(0)->getValueType(0);
19323 // The right side has to be a 'trunc' or a constant vector.
19324 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19325 bool RHSConst = (isSplatVector(N1.getNode()) &&
19326 isa<ConstantSDNode>(N1->getOperand(0)));
19327 if (!RHSTrunc && !RHSConst)
19330 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19332 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19335 // Set N0 and N1 to hold the inputs to the new wide operation.
19336 N0 = N0->getOperand(0);
19338 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19339 N1->getOperand(0));
19340 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19341 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19342 } else if (RHSTrunc) {
19343 N1 = N1->getOperand(0);
19346 // Generate the wide operation.
19347 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19348 unsigned Opcode = N->getOpcode();
19350 case ISD::ANY_EXTEND:
19352 case ISD::ZERO_EXTEND: {
19353 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19354 APInt Mask = APInt::getAllOnesValue(InBits);
19355 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19356 return DAG.getNode(ISD::AND, DL, VT,
19357 Op, DAG.getConstant(Mask, VT));
19359 case ISD::SIGN_EXTEND:
19360 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19361 Op, DAG.getValueType(NarrowVT));
19363 llvm_unreachable("Unexpected opcode");
19367 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19368 TargetLowering::DAGCombinerInfo &DCI,
19369 const X86Subtarget *Subtarget) {
19370 EVT VT = N->getValueType(0);
19371 if (DCI.isBeforeLegalizeOps())
19374 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19378 // Create BEXTR instructions
19379 // BEXTR is ((X >> imm) & (2**size-1))
19380 if (VT == MVT::i32 || VT == MVT::i64) {
19381 SDValue N0 = N->getOperand(0);
19382 SDValue N1 = N->getOperand(1);
19385 // Check for BEXTR.
19386 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19387 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19388 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19389 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19390 if (MaskNode && ShiftNode) {
19391 uint64_t Mask = MaskNode->getZExtValue();
19392 uint64_t Shift = ShiftNode->getZExtValue();
19393 if (isMask_64(Mask)) {
19394 uint64_t MaskSize = CountPopulation_64(Mask);
19395 if (Shift + MaskSize <= VT.getSizeInBits())
19396 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19397 DAG.getConstant(Shift | (MaskSize << 8), VT));
19405 // Want to form ANDNP nodes:
19406 // 1) In the hopes of then easily combining them with OR and AND nodes
19407 // to form PBLEND/PSIGN.
19408 // 2) To match ANDN packed intrinsics
19409 if (VT != MVT::v2i64 && VT != MVT::v4i64)
19412 SDValue N0 = N->getOperand(0);
19413 SDValue N1 = N->getOperand(1);
19416 // Check LHS for vnot
19417 if (N0.getOpcode() == ISD::XOR &&
19418 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19419 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19420 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19422 // Check RHS for vnot
19423 if (N1.getOpcode() == ISD::XOR &&
19424 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19425 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19426 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19431 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19432 TargetLowering::DAGCombinerInfo &DCI,
19433 const X86Subtarget *Subtarget) {
19434 if (DCI.isBeforeLegalizeOps())
19437 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19441 SDValue N0 = N->getOperand(0);
19442 SDValue N1 = N->getOperand(1);
19443 EVT VT = N->getValueType(0);
19445 // look for psign/blend
19446 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19447 if (!Subtarget->hasSSSE3() ||
19448 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19451 // Canonicalize pandn to RHS
19452 if (N0.getOpcode() == X86ISD::ANDNP)
19454 // or (and (m, y), (pandn m, x))
19455 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19456 SDValue Mask = N1.getOperand(0);
19457 SDValue X = N1.getOperand(1);
19459 if (N0.getOperand(0) == Mask)
19460 Y = N0.getOperand(1);
19461 if (N0.getOperand(1) == Mask)
19462 Y = N0.getOperand(0);
19464 // Check to see if the mask appeared in both the AND and ANDNP and
19468 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19469 // Look through mask bitcast.
19470 if (Mask.getOpcode() == ISD::BITCAST)
19471 Mask = Mask.getOperand(0);
19472 if (X.getOpcode() == ISD::BITCAST)
19473 X = X.getOperand(0);
19474 if (Y.getOpcode() == ISD::BITCAST)
19475 Y = Y.getOperand(0);
19477 EVT MaskVT = Mask.getValueType();
19479 // Validate that the Mask operand is a vector sra node.
19480 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19481 // there is no psrai.b
19482 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19483 unsigned SraAmt = ~0;
19484 if (Mask.getOpcode() == ISD::SRA) {
19485 SDValue Amt = Mask.getOperand(1);
19486 if (isSplatVector(Amt.getNode())) {
19487 SDValue SclrAmt = Amt->getOperand(0);
19488 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19489 SraAmt = C->getZExtValue();
19491 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19492 SDValue SraC = Mask.getOperand(1);
19493 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19495 if ((SraAmt + 1) != EltBits)
19500 // Now we know we at least have a plendvb with the mask val. See if
19501 // we can form a psignb/w/d.
19502 // psign = x.type == y.type == mask.type && y = sub(0, x);
19503 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19504 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19505 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19506 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19507 "Unsupported VT for PSIGN");
19508 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19509 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19511 // PBLENDVB only available on SSE 4.1
19512 if (!Subtarget->hasSSE41())
19515 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19517 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19518 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19519 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19520 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19521 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19525 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19528 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19529 MachineFunction &MF = DAG.getMachineFunction();
19530 bool OptForSize = MF.getFunction()->getAttributes().
19531 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19533 // SHLD/SHRD instructions have lower register pressure, but on some
19534 // platforms they have higher latency than the equivalent
19535 // series of shifts/or that would otherwise be generated.
19536 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19537 // have higher latencies and we are not optimizing for size.
19538 if (!OptForSize && Subtarget->isSHLDSlow())
19541 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19543 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19545 if (!N0.hasOneUse() || !N1.hasOneUse())
19548 SDValue ShAmt0 = N0.getOperand(1);
19549 if (ShAmt0.getValueType() != MVT::i8)
19551 SDValue ShAmt1 = N1.getOperand(1);
19552 if (ShAmt1.getValueType() != MVT::i8)
19554 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19555 ShAmt0 = ShAmt0.getOperand(0);
19556 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19557 ShAmt1 = ShAmt1.getOperand(0);
19560 unsigned Opc = X86ISD::SHLD;
19561 SDValue Op0 = N0.getOperand(0);
19562 SDValue Op1 = N1.getOperand(0);
19563 if (ShAmt0.getOpcode() == ISD::SUB) {
19564 Opc = X86ISD::SHRD;
19565 std::swap(Op0, Op1);
19566 std::swap(ShAmt0, ShAmt1);
19569 unsigned Bits = VT.getSizeInBits();
19570 if (ShAmt1.getOpcode() == ISD::SUB) {
19571 SDValue Sum = ShAmt1.getOperand(0);
19572 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19573 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19574 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19575 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19576 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19577 return DAG.getNode(Opc, DL, VT,
19579 DAG.getNode(ISD::TRUNCATE, DL,
19582 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19583 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19585 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19586 return DAG.getNode(Opc, DL, VT,
19587 N0.getOperand(0), N1.getOperand(0),
19588 DAG.getNode(ISD::TRUNCATE, DL,
19595 // Generate NEG and CMOV for integer abs.
19596 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19597 EVT VT = N->getValueType(0);
19599 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19600 // 8-bit integer abs to NEG and CMOV.
19601 if (VT.isInteger() && VT.getSizeInBits() == 8)
19604 SDValue N0 = N->getOperand(0);
19605 SDValue N1 = N->getOperand(1);
19608 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19609 // and change it to SUB and CMOV.
19610 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19611 N0.getOpcode() == ISD::ADD &&
19612 N0.getOperand(1) == N1 &&
19613 N1.getOpcode() == ISD::SRA &&
19614 N1.getOperand(0) == N0.getOperand(0))
19615 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19616 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19617 // Generate SUB & CMOV.
19618 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19619 DAG.getConstant(0, VT), N0.getOperand(0));
19621 SDValue Ops[] = { N0.getOperand(0), Neg,
19622 DAG.getConstant(X86::COND_GE, MVT::i8),
19623 SDValue(Neg.getNode(), 1) };
19624 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19629 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19630 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19631 TargetLowering::DAGCombinerInfo &DCI,
19632 const X86Subtarget *Subtarget) {
19633 if (DCI.isBeforeLegalizeOps())
19636 if (Subtarget->hasCMov()) {
19637 SDValue RV = performIntegerAbsCombine(N, DAG);
19645 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19646 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19647 TargetLowering::DAGCombinerInfo &DCI,
19648 const X86Subtarget *Subtarget) {
19649 LoadSDNode *Ld = cast<LoadSDNode>(N);
19650 EVT RegVT = Ld->getValueType(0);
19651 EVT MemVT = Ld->getMemoryVT();
19653 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19654 unsigned RegSz = RegVT.getSizeInBits();
19656 // On Sandybridge unaligned 256bit loads are inefficient.
19657 ISD::LoadExtType Ext = Ld->getExtensionType();
19658 unsigned Alignment = Ld->getAlignment();
19659 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19660 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19661 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19662 unsigned NumElems = RegVT.getVectorNumElements();
19666 SDValue Ptr = Ld->getBasePtr();
19667 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19669 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19671 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19672 Ld->getPointerInfo(), Ld->isVolatile(),
19673 Ld->isNonTemporal(), Ld->isInvariant(),
19675 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19676 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19677 Ld->getPointerInfo(), Ld->isVolatile(),
19678 Ld->isNonTemporal(), Ld->isInvariant(),
19679 std::min(16U, Alignment));
19680 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19682 Load2.getValue(1));
19684 SDValue NewVec = DAG.getUNDEF(RegVT);
19685 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19686 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19687 return DCI.CombineTo(N, NewVec, TF, true);
19690 // If this is a vector EXT Load then attempt to optimize it using a
19691 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19692 // expansion is still better than scalar code.
19693 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19694 // emit a shuffle and a arithmetic shift.
19695 // TODO: It is possible to support ZExt by zeroing the undef values
19696 // during the shuffle phase or after the shuffle.
19697 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19698 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19699 assert(MemVT != RegVT && "Cannot extend to the same type");
19700 assert(MemVT.isVector() && "Must load a vector from memory");
19702 unsigned NumElems = RegVT.getVectorNumElements();
19703 unsigned MemSz = MemVT.getSizeInBits();
19704 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19706 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19709 // All sizes must be a power of two.
19710 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19713 // Attempt to load the original value using scalar loads.
19714 // Find the largest scalar type that divides the total loaded size.
19715 MVT SclrLoadTy = MVT::i8;
19716 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19717 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19718 MVT Tp = (MVT::SimpleValueType)tp;
19719 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19724 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19725 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19727 SclrLoadTy = MVT::f64;
19729 // Calculate the number of scalar loads that we need to perform
19730 // in order to load our vector from memory.
19731 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19732 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19735 unsigned loadRegZize = RegSz;
19736 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19739 // Represent our vector as a sequence of elements which are the
19740 // largest scalar that we can load.
19741 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19742 loadRegZize/SclrLoadTy.getSizeInBits());
19744 // Represent the data using the same element type that is stored in
19745 // memory. In practice, we ''widen'' MemVT.
19747 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19748 loadRegZize/MemVT.getScalarType().getSizeInBits());
19750 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19751 "Invalid vector type");
19753 // We can't shuffle using an illegal type.
19754 if (!TLI.isTypeLegal(WideVecVT))
19757 SmallVector<SDValue, 8> Chains;
19758 SDValue Ptr = Ld->getBasePtr();
19759 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19760 TLI.getPointerTy());
19761 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19763 for (unsigned i = 0; i < NumLoads; ++i) {
19764 // Perform a single load.
19765 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19766 Ptr, Ld->getPointerInfo(),
19767 Ld->isVolatile(), Ld->isNonTemporal(),
19768 Ld->isInvariant(), Ld->getAlignment());
19769 Chains.push_back(ScalarLoad.getValue(1));
19770 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19771 // another round of DAGCombining.
19773 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19775 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19776 ScalarLoad, DAG.getIntPtrConstant(i));
19778 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19781 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19783 // Bitcast the loaded value to a vector of the original element type, in
19784 // the size of the target vector type.
19785 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19786 unsigned SizeRatio = RegSz/MemSz;
19788 if (Ext == ISD::SEXTLOAD) {
19789 // If we have SSE4.1 we can directly emit a VSEXT node.
19790 if (Subtarget->hasSSE41()) {
19791 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19792 return DCI.CombineTo(N, Sext, TF, true);
19795 // Otherwise we'll shuffle the small elements in the high bits of the
19796 // larger type and perform an arithmetic shift. If the shift is not legal
19797 // it's better to scalarize.
19798 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19801 // Redistribute the loaded elements into the different locations.
19802 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19803 for (unsigned i = 0; i != NumElems; ++i)
19804 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19806 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19807 DAG.getUNDEF(WideVecVT),
19810 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19812 // Build the arithmetic shift.
19813 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19814 MemVT.getVectorElementType().getSizeInBits();
19815 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19816 DAG.getConstant(Amt, RegVT));
19818 return DCI.CombineTo(N, Shuff, TF, true);
19821 // Redistribute the loaded elements into the different locations.
19822 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19823 for (unsigned i = 0; i != NumElems; ++i)
19824 ShuffleVec[i*SizeRatio] = i;
19826 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19827 DAG.getUNDEF(WideVecVT),
19830 // Bitcast to the requested type.
19831 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19832 // Replace the original load with the new sequence
19833 // and return the new chain.
19834 return DCI.CombineTo(N, Shuff, TF, true);
19840 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19841 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19842 const X86Subtarget *Subtarget) {
19843 StoreSDNode *St = cast<StoreSDNode>(N);
19844 EVT VT = St->getValue().getValueType();
19845 EVT StVT = St->getMemoryVT();
19847 SDValue StoredVal = St->getOperand(1);
19848 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19850 // If we are saving a concatenation of two XMM registers, perform two stores.
19851 // On Sandy Bridge, 256-bit memory operations are executed by two
19852 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19853 // memory operation.
19854 unsigned Alignment = St->getAlignment();
19855 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19856 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19857 StVT == VT && !IsAligned) {
19858 unsigned NumElems = VT.getVectorNumElements();
19862 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19863 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19865 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19866 SDValue Ptr0 = St->getBasePtr();
19867 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19869 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19870 St->getPointerInfo(), St->isVolatile(),
19871 St->isNonTemporal(), Alignment);
19872 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19873 St->getPointerInfo(), St->isVolatile(),
19874 St->isNonTemporal(),
19875 std::min(16U, Alignment));
19876 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19879 // Optimize trunc store (of multiple scalars) to shuffle and store.
19880 // First, pack all of the elements in one place. Next, store to memory
19881 // in fewer chunks.
19882 if (St->isTruncatingStore() && VT.isVector()) {
19883 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19884 unsigned NumElems = VT.getVectorNumElements();
19885 assert(StVT != VT && "Cannot truncate to the same type");
19886 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19887 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19889 // From, To sizes and ElemCount must be pow of two
19890 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19891 // We are going to use the original vector elt for storing.
19892 // Accumulated smaller vector elements must be a multiple of the store size.
19893 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19895 unsigned SizeRatio = FromSz / ToSz;
19897 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19899 // Create a type on which we perform the shuffle
19900 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19901 StVT.getScalarType(), NumElems*SizeRatio);
19903 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19905 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19906 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19907 for (unsigned i = 0; i != NumElems; ++i)
19908 ShuffleVec[i] = i * SizeRatio;
19910 // Can't shuffle using an illegal type.
19911 if (!TLI.isTypeLegal(WideVecVT))
19914 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19915 DAG.getUNDEF(WideVecVT),
19917 // At this point all of the data is stored at the bottom of the
19918 // register. We now need to save it to mem.
19920 // Find the largest store unit
19921 MVT StoreType = MVT::i8;
19922 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19923 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19924 MVT Tp = (MVT::SimpleValueType)tp;
19925 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19929 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19930 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19931 (64 <= NumElems * ToSz))
19932 StoreType = MVT::f64;
19934 // Bitcast the original vector into a vector of store-size units
19935 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19936 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19937 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19938 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19939 SmallVector<SDValue, 8> Chains;
19940 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19941 TLI.getPointerTy());
19942 SDValue Ptr = St->getBasePtr();
19944 // Perform one or more big stores into memory.
19945 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19946 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19947 StoreType, ShuffWide,
19948 DAG.getIntPtrConstant(i));
19949 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19950 St->getPointerInfo(), St->isVolatile(),
19951 St->isNonTemporal(), St->getAlignment());
19952 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19953 Chains.push_back(Ch);
19956 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19959 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19960 // the FP state in cases where an emms may be missing.
19961 // A preferable solution to the general problem is to figure out the right
19962 // places to insert EMMS. This qualifies as a quick hack.
19964 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19965 if (VT.getSizeInBits() != 64)
19968 const Function *F = DAG.getMachineFunction().getFunction();
19969 bool NoImplicitFloatOps = F->getAttributes().
19970 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19971 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19972 && Subtarget->hasSSE2();
19973 if ((VT.isVector() ||
19974 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19975 isa<LoadSDNode>(St->getValue()) &&
19976 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19977 St->getChain().hasOneUse() && !St->isVolatile()) {
19978 SDNode* LdVal = St->getValue().getNode();
19979 LoadSDNode *Ld = nullptr;
19980 int TokenFactorIndex = -1;
19981 SmallVector<SDValue, 8> Ops;
19982 SDNode* ChainVal = St->getChain().getNode();
19983 // Must be a store of a load. We currently handle two cases: the load
19984 // is a direct child, and it's under an intervening TokenFactor. It is
19985 // possible to dig deeper under nested TokenFactors.
19986 if (ChainVal == LdVal)
19987 Ld = cast<LoadSDNode>(St->getChain());
19988 else if (St->getValue().hasOneUse() &&
19989 ChainVal->getOpcode() == ISD::TokenFactor) {
19990 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19991 if (ChainVal->getOperand(i).getNode() == LdVal) {
19992 TokenFactorIndex = i;
19993 Ld = cast<LoadSDNode>(St->getValue());
19995 Ops.push_back(ChainVal->getOperand(i));
19999 if (!Ld || !ISD::isNormalLoad(Ld))
20002 // If this is not the MMX case, i.e. we are just turning i64 load/store
20003 // into f64 load/store, avoid the transformation if there are multiple
20004 // uses of the loaded value.
20005 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
20010 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
20011 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
20013 if (Subtarget->is64Bit() || F64IsLegal) {
20014 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
20015 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
20016 Ld->getPointerInfo(), Ld->isVolatile(),
20017 Ld->isNonTemporal(), Ld->isInvariant(),
20018 Ld->getAlignment());
20019 SDValue NewChain = NewLd.getValue(1);
20020 if (TokenFactorIndex != -1) {
20021 Ops.push_back(NewChain);
20022 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20024 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20025 St->getPointerInfo(),
20026 St->isVolatile(), St->isNonTemporal(),
20027 St->getAlignment());
20030 // Otherwise, lower to two pairs of 32-bit loads / stores.
20031 SDValue LoAddr = Ld->getBasePtr();
20032 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20033 DAG.getConstant(4, MVT::i32));
20035 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20036 Ld->getPointerInfo(),
20037 Ld->isVolatile(), Ld->isNonTemporal(),
20038 Ld->isInvariant(), Ld->getAlignment());
20039 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20040 Ld->getPointerInfo().getWithOffset(4),
20041 Ld->isVolatile(), Ld->isNonTemporal(),
20043 MinAlign(Ld->getAlignment(), 4));
20045 SDValue NewChain = LoLd.getValue(1);
20046 if (TokenFactorIndex != -1) {
20047 Ops.push_back(LoLd);
20048 Ops.push_back(HiLd);
20049 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20052 LoAddr = St->getBasePtr();
20053 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20054 DAG.getConstant(4, MVT::i32));
20056 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20057 St->getPointerInfo(),
20058 St->isVolatile(), St->isNonTemporal(),
20059 St->getAlignment());
20060 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20061 St->getPointerInfo().getWithOffset(4),
20063 St->isNonTemporal(),
20064 MinAlign(St->getAlignment(), 4));
20065 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20070 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20071 /// and return the operands for the horizontal operation in LHS and RHS. A
20072 /// horizontal operation performs the binary operation on successive elements
20073 /// of its first operand, then on successive elements of its second operand,
20074 /// returning the resulting values in a vector. For example, if
20075 /// A = < float a0, float a1, float a2, float a3 >
20077 /// B = < float b0, float b1, float b2, float b3 >
20078 /// then the result of doing a horizontal operation on A and B is
20079 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20080 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20081 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20082 /// set to A, RHS to B, and the routine returns 'true'.
20083 /// Note that the binary operation should have the property that if one of the
20084 /// operands is UNDEF then the result is UNDEF.
20085 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20086 // Look for the following pattern: if
20087 // A = < float a0, float a1, float a2, float a3 >
20088 // B = < float b0, float b1, float b2, float b3 >
20090 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20091 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20092 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20093 // which is A horizontal-op B.
20095 // At least one of the operands should be a vector shuffle.
20096 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20097 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20100 MVT VT = LHS.getSimpleValueType();
20102 assert((VT.is128BitVector() || VT.is256BitVector()) &&
20103 "Unsupported vector type for horizontal add/sub");
20105 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20106 // operate independently on 128-bit lanes.
20107 unsigned NumElts = VT.getVectorNumElements();
20108 unsigned NumLanes = VT.getSizeInBits()/128;
20109 unsigned NumLaneElts = NumElts / NumLanes;
20110 assert((NumLaneElts % 2 == 0) &&
20111 "Vector type should have an even number of elements in each lane");
20112 unsigned HalfLaneElts = NumLaneElts/2;
20114 // View LHS in the form
20115 // LHS = VECTOR_SHUFFLE A, B, LMask
20116 // If LHS is not a shuffle then pretend it is the shuffle
20117 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20118 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20121 SmallVector<int, 16> LMask(NumElts);
20122 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20123 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20124 A = LHS.getOperand(0);
20125 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20126 B = LHS.getOperand(1);
20127 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20128 std::copy(Mask.begin(), Mask.end(), LMask.begin());
20130 if (LHS.getOpcode() != ISD::UNDEF)
20132 for (unsigned i = 0; i != NumElts; ++i)
20136 // Likewise, view RHS in the form
20137 // RHS = VECTOR_SHUFFLE C, D, RMask
20139 SmallVector<int, 16> RMask(NumElts);
20140 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20141 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20142 C = RHS.getOperand(0);
20143 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20144 D = RHS.getOperand(1);
20145 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20146 std::copy(Mask.begin(), Mask.end(), RMask.begin());
20148 if (RHS.getOpcode() != ISD::UNDEF)
20150 for (unsigned i = 0; i != NumElts; ++i)
20154 // Check that the shuffles are both shuffling the same vectors.
20155 if (!(A == C && B == D) && !(A == D && B == C))
20158 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20159 if (!A.getNode() && !B.getNode())
20162 // If A and B occur in reverse order in RHS, then "swap" them (which means
20163 // rewriting the mask).
20165 CommuteVectorShuffleMask(RMask, NumElts);
20167 // At this point LHS and RHS are equivalent to
20168 // LHS = VECTOR_SHUFFLE A, B, LMask
20169 // RHS = VECTOR_SHUFFLE A, B, RMask
20170 // Check that the masks correspond to performing a horizontal operation.
20171 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20172 for (unsigned i = 0; i != NumLaneElts; ++i) {
20173 int LIdx = LMask[i+l], RIdx = RMask[i+l];
20175 // Ignore any UNDEF components.
20176 if (LIdx < 0 || RIdx < 0 ||
20177 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20178 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20181 // Check that successive elements are being operated on. If not, this is
20182 // not a horizontal operation.
20183 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20184 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20185 if (!(LIdx == Index && RIdx == Index + 1) &&
20186 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20191 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20192 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20196 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20197 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20198 const X86Subtarget *Subtarget) {
20199 EVT VT = N->getValueType(0);
20200 SDValue LHS = N->getOperand(0);
20201 SDValue RHS = N->getOperand(1);
20203 // Try to synthesize horizontal adds from adds of shuffles.
20204 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20205 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20206 isHorizontalBinOp(LHS, RHS, true))
20207 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20211 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20212 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20213 const X86Subtarget *Subtarget) {
20214 EVT VT = N->getValueType(0);
20215 SDValue LHS = N->getOperand(0);
20216 SDValue RHS = N->getOperand(1);
20218 // Try to synthesize horizontal subs from subs of shuffles.
20219 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20220 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20221 isHorizontalBinOp(LHS, RHS, false))
20222 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20226 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20227 /// X86ISD::FXOR nodes.
20228 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20229 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20230 // F[X]OR(0.0, x) -> x
20231 // F[X]OR(x, 0.0) -> x
20232 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20233 if (C->getValueAPF().isPosZero())
20234 return N->getOperand(1);
20235 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20236 if (C->getValueAPF().isPosZero())
20237 return N->getOperand(0);
20241 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20242 /// X86ISD::FMAX nodes.
20243 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20244 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20246 // Only perform optimizations if UnsafeMath is used.
20247 if (!DAG.getTarget().Options.UnsafeFPMath)
20250 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20251 // into FMINC and FMAXC, which are Commutative operations.
20252 unsigned NewOp = 0;
20253 switch (N->getOpcode()) {
20254 default: llvm_unreachable("unknown opcode");
20255 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
20256 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
20259 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20260 N->getOperand(0), N->getOperand(1));
20263 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20264 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20265 // FAND(0.0, x) -> 0.0
20266 // FAND(x, 0.0) -> 0.0
20267 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20268 if (C->getValueAPF().isPosZero())
20269 return N->getOperand(0);
20270 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20271 if (C->getValueAPF().isPosZero())
20272 return N->getOperand(1);
20276 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20277 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20278 // FANDN(x, 0.0) -> 0.0
20279 // FANDN(0.0, x) -> x
20280 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20281 if (C->getValueAPF().isPosZero())
20282 return N->getOperand(1);
20283 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20284 if (C->getValueAPF().isPosZero())
20285 return N->getOperand(1);
20289 static SDValue PerformBTCombine(SDNode *N,
20291 TargetLowering::DAGCombinerInfo &DCI) {
20292 // BT ignores high bits in the bit index operand.
20293 SDValue Op1 = N->getOperand(1);
20294 if (Op1.hasOneUse()) {
20295 unsigned BitWidth = Op1.getValueSizeInBits();
20296 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20297 APInt KnownZero, KnownOne;
20298 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20299 !DCI.isBeforeLegalizeOps());
20300 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20301 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20302 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20303 DCI.CommitTargetLoweringOpt(TLO);
20308 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20309 SDValue Op = N->getOperand(0);
20310 if (Op.getOpcode() == ISD::BITCAST)
20311 Op = Op.getOperand(0);
20312 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20313 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20314 VT.getVectorElementType().getSizeInBits() ==
20315 OpVT.getVectorElementType().getSizeInBits()) {
20316 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20321 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20322 const X86Subtarget *Subtarget) {
20323 EVT VT = N->getValueType(0);
20324 if (!VT.isVector())
20327 SDValue N0 = N->getOperand(0);
20328 SDValue N1 = N->getOperand(1);
20329 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20332 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20333 // both SSE and AVX2 since there is no sign-extended shift right
20334 // operation on a vector with 64-bit elements.
20335 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20336 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20337 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20338 N0.getOpcode() == ISD::SIGN_EXTEND)) {
20339 SDValue N00 = N0.getOperand(0);
20341 // EXTLOAD has a better solution on AVX2,
20342 // it may be replaced with X86ISD::VSEXT node.
20343 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20344 if (!ISD::isNormalLoad(N00.getNode()))
20347 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20348 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20350 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20356 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20357 TargetLowering::DAGCombinerInfo &DCI,
20358 const X86Subtarget *Subtarget) {
20359 if (!DCI.isBeforeLegalizeOps())
20362 if (!Subtarget->hasFp256())
20365 EVT VT = N->getValueType(0);
20366 if (VT.isVector() && VT.getSizeInBits() == 256) {
20367 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20375 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20376 const X86Subtarget* Subtarget) {
20378 EVT VT = N->getValueType(0);
20380 // Let legalize expand this if it isn't a legal type yet.
20381 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20384 EVT ScalarVT = VT.getScalarType();
20385 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20386 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20389 SDValue A = N->getOperand(0);
20390 SDValue B = N->getOperand(1);
20391 SDValue C = N->getOperand(2);
20393 bool NegA = (A.getOpcode() == ISD::FNEG);
20394 bool NegB = (B.getOpcode() == ISD::FNEG);
20395 bool NegC = (C.getOpcode() == ISD::FNEG);
20397 // Negative multiplication when NegA xor NegB
20398 bool NegMul = (NegA != NegB);
20400 A = A.getOperand(0);
20402 B = B.getOperand(0);
20404 C = C.getOperand(0);
20408 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20410 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20412 return DAG.getNode(Opcode, dl, VT, A, B, C);
20415 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20416 TargetLowering::DAGCombinerInfo &DCI,
20417 const X86Subtarget *Subtarget) {
20418 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
20419 // (and (i32 x86isd::setcc_carry), 1)
20420 // This eliminates the zext. This transformation is necessary because
20421 // ISD::SETCC is always legalized to i8.
20423 SDValue N0 = N->getOperand(0);
20424 EVT VT = N->getValueType(0);
20426 if (N0.getOpcode() == ISD::AND &&
20428 N0.getOperand(0).hasOneUse()) {
20429 SDValue N00 = N0.getOperand(0);
20430 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20431 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20432 if (!C || C->getZExtValue() != 1)
20434 return DAG.getNode(ISD::AND, dl, VT,
20435 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20436 N00.getOperand(0), N00.getOperand(1)),
20437 DAG.getConstant(1, VT));
20441 if (N0.getOpcode() == ISD::TRUNCATE &&
20443 N0.getOperand(0).hasOneUse()) {
20444 SDValue N00 = N0.getOperand(0);
20445 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20446 return DAG.getNode(ISD::AND, dl, VT,
20447 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20448 N00.getOperand(0), N00.getOperand(1)),
20449 DAG.getConstant(1, VT));
20452 if (VT.is256BitVector()) {
20453 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20461 // Optimize x == -y --> x+y == 0
20462 // x != -y --> x+y != 0
20463 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20464 const X86Subtarget* Subtarget) {
20465 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20466 SDValue LHS = N->getOperand(0);
20467 SDValue RHS = N->getOperand(1);
20468 EVT VT = N->getValueType(0);
20471 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20473 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20474 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20475 LHS.getValueType(), RHS, LHS.getOperand(1));
20476 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20477 addV, DAG.getConstant(0, addV.getValueType()), CC);
20479 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20480 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20481 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20482 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20483 RHS.getValueType(), LHS, RHS.getOperand(1));
20484 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20485 addV, DAG.getConstant(0, addV.getValueType()), CC);
20488 if (VT.getScalarType() == MVT::i1) {
20489 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20490 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20491 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20492 if (!IsSEXT0 && !IsVZero0)
20494 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20495 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20496 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20498 if (!IsSEXT1 && !IsVZero1)
20501 if (IsSEXT0 && IsVZero1) {
20502 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20503 if (CC == ISD::SETEQ)
20504 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20505 return LHS.getOperand(0);
20507 if (IsSEXT1 && IsVZero0) {
20508 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20509 if (CC == ISD::SETEQ)
20510 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20511 return RHS.getOperand(0);
20518 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20519 const X86Subtarget *Subtarget) {
20521 MVT VT = N->getOperand(1)->getSimpleValueType(0);
20522 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20523 "X86insertps is only defined for v4x32");
20525 SDValue Ld = N->getOperand(1);
20526 if (MayFoldLoad(Ld)) {
20527 // Extract the countS bits from the immediate so we can get the proper
20528 // address when narrowing the vector load to a specific element.
20529 // When the second source op is a memory address, interps doesn't use
20530 // countS and just gets an f32 from that address.
20531 unsigned DestIndex =
20532 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20533 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20537 // Create this as a scalar to vector to match the instruction pattern.
20538 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20539 // countS bits are ignored when loading from memory on insertps, which
20540 // means we don't need to explicitly set them to 0.
20541 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20542 LoadScalarToVector, N->getOperand(2));
20545 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20546 // as "sbb reg,reg", since it can be extended without zext and produces
20547 // an all-ones bit which is more useful than 0/1 in some cases.
20548 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20551 return DAG.getNode(ISD::AND, DL, VT,
20552 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20553 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20554 DAG.getConstant(1, VT));
20555 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20556 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20557 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20558 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20561 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20562 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20563 TargetLowering::DAGCombinerInfo &DCI,
20564 const X86Subtarget *Subtarget) {
20566 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20567 SDValue EFLAGS = N->getOperand(1);
20569 if (CC == X86::COND_A) {
20570 // Try to convert COND_A into COND_B in an attempt to facilitate
20571 // materializing "setb reg".
20573 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20574 // cannot take an immediate as its first operand.
20576 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20577 EFLAGS.getValueType().isInteger() &&
20578 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20579 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20580 EFLAGS.getNode()->getVTList(),
20581 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20582 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20583 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20587 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20588 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20590 if (CC == X86::COND_B)
20591 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20595 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20596 if (Flags.getNode()) {
20597 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20598 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20604 // Optimize branch condition evaluation.
20606 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20607 TargetLowering::DAGCombinerInfo &DCI,
20608 const X86Subtarget *Subtarget) {
20610 SDValue Chain = N->getOperand(0);
20611 SDValue Dest = N->getOperand(1);
20612 SDValue EFLAGS = N->getOperand(3);
20613 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20617 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20618 if (Flags.getNode()) {
20619 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20620 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20627 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20628 const X86TargetLowering *XTLI) {
20629 SDValue Op0 = N->getOperand(0);
20630 EVT InVT = Op0->getValueType(0);
20632 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20633 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20635 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20636 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20637 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20640 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20641 // a 32-bit target where SSE doesn't support i64->FP operations.
20642 if (Op0.getOpcode() == ISD::LOAD) {
20643 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20644 EVT VT = Ld->getValueType(0);
20645 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20646 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20647 !XTLI->getSubtarget()->is64Bit() &&
20649 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20650 Ld->getChain(), Op0, DAG);
20651 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20658 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20659 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20660 X86TargetLowering::DAGCombinerInfo &DCI) {
20661 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20662 // the result is either zero or one (depending on the input carry bit).
20663 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20664 if (X86::isZeroNode(N->getOperand(0)) &&
20665 X86::isZeroNode(N->getOperand(1)) &&
20666 // We don't have a good way to replace an EFLAGS use, so only do this when
20668 SDValue(N, 1).use_empty()) {
20670 EVT VT = N->getValueType(0);
20671 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20672 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20673 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20674 DAG.getConstant(X86::COND_B,MVT::i8),
20676 DAG.getConstant(1, VT));
20677 return DCI.CombineTo(N, Res1, CarryOut);
20683 // fold (add Y, (sete X, 0)) -> adc 0, Y
20684 // (add Y, (setne X, 0)) -> sbb -1, Y
20685 // (sub (sete X, 0), Y) -> sbb 0, Y
20686 // (sub (setne X, 0), Y) -> adc -1, Y
20687 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20690 // Look through ZExts.
20691 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20692 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20695 SDValue SetCC = Ext.getOperand(0);
20696 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20699 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20700 if (CC != X86::COND_E && CC != X86::COND_NE)
20703 SDValue Cmp = SetCC.getOperand(1);
20704 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20705 !X86::isZeroNode(Cmp.getOperand(1)) ||
20706 !Cmp.getOperand(0).getValueType().isInteger())
20709 SDValue CmpOp0 = Cmp.getOperand(0);
20710 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20711 DAG.getConstant(1, CmpOp0.getValueType()));
20713 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20714 if (CC == X86::COND_NE)
20715 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20716 DL, OtherVal.getValueType(), OtherVal,
20717 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20718 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20719 DL, OtherVal.getValueType(), OtherVal,
20720 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20723 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20724 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20725 const X86Subtarget *Subtarget) {
20726 EVT VT = N->getValueType(0);
20727 SDValue Op0 = N->getOperand(0);
20728 SDValue Op1 = N->getOperand(1);
20730 // Try to synthesize horizontal adds from adds of shuffles.
20731 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20732 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20733 isHorizontalBinOp(Op0, Op1, true))
20734 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20736 return OptimizeConditionalInDecrement(N, DAG);
20739 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20740 const X86Subtarget *Subtarget) {
20741 SDValue Op0 = N->getOperand(0);
20742 SDValue Op1 = N->getOperand(1);
20744 // X86 can't encode an immediate LHS of a sub. See if we can push the
20745 // negation into a preceding instruction.
20746 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20747 // If the RHS of the sub is a XOR with one use and a constant, invert the
20748 // immediate. Then add one to the LHS of the sub so we can turn
20749 // X-Y -> X+~Y+1, saving one register.
20750 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20751 isa<ConstantSDNode>(Op1.getOperand(1))) {
20752 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20753 EVT VT = Op0.getValueType();
20754 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20756 DAG.getConstant(~XorC, VT));
20757 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20758 DAG.getConstant(C->getAPIntValue()+1, VT));
20762 // Try to synthesize horizontal adds from adds of shuffles.
20763 EVT VT = N->getValueType(0);
20764 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20765 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20766 isHorizontalBinOp(Op0, Op1, true))
20767 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20769 return OptimizeConditionalInDecrement(N, DAG);
20772 /// performVZEXTCombine - Performs build vector combines
20773 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20774 TargetLowering::DAGCombinerInfo &DCI,
20775 const X86Subtarget *Subtarget) {
20776 // (vzext (bitcast (vzext (x)) -> (vzext x)
20777 SDValue In = N->getOperand(0);
20778 while (In.getOpcode() == ISD::BITCAST)
20779 In = In.getOperand(0);
20781 if (In.getOpcode() != X86ISD::VZEXT)
20784 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20788 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20789 DAGCombinerInfo &DCI) const {
20790 SelectionDAG &DAG = DCI.DAG;
20791 switch (N->getOpcode()) {
20793 case ISD::EXTRACT_VECTOR_ELT:
20794 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20796 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20797 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20798 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20799 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20800 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20801 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20804 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20805 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20806 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20807 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20808 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20809 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20810 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20811 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20812 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20814 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20816 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20817 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20818 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20819 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20820 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20821 case ISD::ANY_EXTEND:
20822 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20823 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20824 case ISD::SIGN_EXTEND_INREG:
20825 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20826 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20827 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20828 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20829 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20830 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20831 case X86ISD::SHUFP: // Handle all target specific shuffles
20832 case X86ISD::PALIGNR:
20833 case X86ISD::UNPCKH:
20834 case X86ISD::UNPCKL:
20835 case X86ISD::MOVHLPS:
20836 case X86ISD::MOVLHPS:
20837 case X86ISD::PSHUFD:
20838 case X86ISD::PSHUFHW:
20839 case X86ISD::PSHUFLW:
20840 case X86ISD::MOVSS:
20841 case X86ISD::MOVSD:
20842 case X86ISD::VPERMILP:
20843 case X86ISD::VPERM2X128:
20844 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20845 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20846 case ISD::INTRINSIC_WO_CHAIN:
20847 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20848 case X86ISD::INSERTPS:
20849 return PerformINSERTPSCombine(N, DAG, Subtarget);
20850 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
20856 /// isTypeDesirableForOp - Return true if the target has native support for
20857 /// the specified value type and it is 'desirable' to use the type for the
20858 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20859 /// instruction encodings are longer and some i16 instructions are slow.
20860 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20861 if (!isTypeLegal(VT))
20863 if (VT != MVT::i16)
20870 case ISD::SIGN_EXTEND:
20871 case ISD::ZERO_EXTEND:
20872 case ISD::ANY_EXTEND:
20885 /// IsDesirableToPromoteOp - This method query the target whether it is
20886 /// beneficial for dag combiner to promote the specified node. If true, it
20887 /// should return the desired promotion type by reference.
20888 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20889 EVT VT = Op.getValueType();
20890 if (VT != MVT::i16)
20893 bool Promote = false;
20894 bool Commute = false;
20895 switch (Op.getOpcode()) {
20898 LoadSDNode *LD = cast<LoadSDNode>(Op);
20899 // If the non-extending load has a single use and it's not live out, then it
20900 // might be folded.
20901 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20902 Op.hasOneUse()*/) {
20903 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20904 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20905 // The only case where we'd want to promote LOAD (rather then it being
20906 // promoted as an operand is when it's only use is liveout.
20907 if (UI->getOpcode() != ISD::CopyToReg)
20914 case ISD::SIGN_EXTEND:
20915 case ISD::ZERO_EXTEND:
20916 case ISD::ANY_EXTEND:
20921 SDValue N0 = Op.getOperand(0);
20922 // Look out for (store (shl (load), x)).
20923 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20936 SDValue N0 = Op.getOperand(0);
20937 SDValue N1 = Op.getOperand(1);
20938 if (!Commute && MayFoldLoad(N1))
20940 // Avoid disabling potential load folding opportunities.
20941 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20943 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20953 //===----------------------------------------------------------------------===//
20954 // X86 Inline Assembly Support
20955 //===----------------------------------------------------------------------===//
20958 // Helper to match a string separated by whitespace.
20959 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20960 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20962 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20963 StringRef piece(*args[i]);
20964 if (!s.startswith(piece)) // Check if the piece matches.
20967 s = s.substr(piece.size());
20968 StringRef::size_type pos = s.find_first_not_of(" \t");
20969 if (pos == 0) // We matched a prefix.
20977 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20980 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20982 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20983 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20984 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20985 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20987 if (AsmPieces.size() == 3)
20989 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20996 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20997 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20999 std::string AsmStr = IA->getAsmString();
21001 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
21002 if (!Ty || Ty->getBitWidth() % 16 != 0)
21005 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
21006 SmallVector<StringRef, 4> AsmPieces;
21007 SplitString(AsmStr, AsmPieces, ";\n");
21009 switch (AsmPieces.size()) {
21010 default: return false;
21012 // FIXME: this should verify that we are targeting a 486 or better. If not,
21013 // we will turn this bswap into something that will be lowered to logical
21014 // ops instead of emitting the bswap asm. For now, we don't support 486 or
21015 // lower so don't worry about this.
21017 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21018 matchAsm(AsmPieces[0], "bswapl", "$0") ||
21019 matchAsm(AsmPieces[0], "bswapq", "$0") ||
21020 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21021 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21022 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21023 // No need to check constraints, nothing other than the equivalent of
21024 // "=r,0" would be valid here.
21025 return IntrinsicLowering::LowerToByteSwap(CI);
21028 // rorw $$8, ${0:w} --> llvm.bswap.i16
21029 if (CI->getType()->isIntegerTy(16) &&
21030 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21031 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21032 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21034 const std::string &ConstraintsStr = IA->getConstraintString();
21035 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21036 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21037 if (clobbersFlagRegisters(AsmPieces))
21038 return IntrinsicLowering::LowerToByteSwap(CI);
21042 if (CI->getType()->isIntegerTy(32) &&
21043 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21044 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21045 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21046 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21048 const std::string &ConstraintsStr = IA->getConstraintString();
21049 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21050 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21051 if (clobbersFlagRegisters(AsmPieces))
21052 return IntrinsicLowering::LowerToByteSwap(CI);
21055 if (CI->getType()->isIntegerTy(64)) {
21056 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21057 if (Constraints.size() >= 2 &&
21058 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21059 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21060 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
21061 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21062 matchAsm(AsmPieces[1], "bswap", "%edx") &&
21063 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21064 return IntrinsicLowering::LowerToByteSwap(CI);
21072 /// getConstraintType - Given a constraint letter, return the type of
21073 /// constraint it is for this target.
21074 X86TargetLowering::ConstraintType
21075 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21076 if (Constraint.size() == 1) {
21077 switch (Constraint[0]) {
21088 return C_RegisterClass;
21112 return TargetLowering::getConstraintType(Constraint);
21115 /// Examine constraint type and operand type and determine a weight value.
21116 /// This object must already have been set up with the operand type
21117 /// and the current alternative constraint selected.
21118 TargetLowering::ConstraintWeight
21119 X86TargetLowering::getSingleConstraintMatchWeight(
21120 AsmOperandInfo &info, const char *constraint) const {
21121 ConstraintWeight weight = CW_Invalid;
21122 Value *CallOperandVal = info.CallOperandVal;
21123 // If we don't have a value, we can't do a match,
21124 // but allow it at the lowest weight.
21125 if (!CallOperandVal)
21127 Type *type = CallOperandVal->getType();
21128 // Look at the constraint type.
21129 switch (*constraint) {
21131 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21142 if (CallOperandVal->getType()->isIntegerTy())
21143 weight = CW_SpecificReg;
21148 if (type->isFloatingPointTy())
21149 weight = CW_SpecificReg;
21152 if (type->isX86_MMXTy() && Subtarget->hasMMX())
21153 weight = CW_SpecificReg;
21157 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21158 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21159 weight = CW_Register;
21162 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21163 if (C->getZExtValue() <= 31)
21164 weight = CW_Constant;
21168 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21169 if (C->getZExtValue() <= 63)
21170 weight = CW_Constant;
21174 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21175 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21176 weight = CW_Constant;
21180 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21181 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21182 weight = CW_Constant;
21186 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21187 if (C->getZExtValue() <= 3)
21188 weight = CW_Constant;
21192 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21193 if (C->getZExtValue() <= 0xff)
21194 weight = CW_Constant;
21199 if (dyn_cast<ConstantFP>(CallOperandVal)) {
21200 weight = CW_Constant;
21204 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21205 if ((C->getSExtValue() >= -0x80000000LL) &&
21206 (C->getSExtValue() <= 0x7fffffffLL))
21207 weight = CW_Constant;
21211 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21212 if (C->getZExtValue() <= 0xffffffff)
21213 weight = CW_Constant;
21220 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21221 /// with another that has more specific requirements based on the type of the
21222 /// corresponding operand.
21223 const char *X86TargetLowering::
21224 LowerXConstraint(EVT ConstraintVT) const {
21225 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21226 // 'f' like normal targets.
21227 if (ConstraintVT.isFloatingPoint()) {
21228 if (Subtarget->hasSSE2())
21230 if (Subtarget->hasSSE1())
21234 return TargetLowering::LowerXConstraint(ConstraintVT);
21237 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21238 /// vector. If it is invalid, don't add anything to Ops.
21239 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21240 std::string &Constraint,
21241 std::vector<SDValue>&Ops,
21242 SelectionDAG &DAG) const {
21245 // Only support length 1 constraints for now.
21246 if (Constraint.length() > 1) return;
21248 char ConstraintLetter = Constraint[0];
21249 switch (ConstraintLetter) {
21252 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21253 if (C->getZExtValue() <= 31) {
21254 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21260 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21261 if (C->getZExtValue() <= 63) {
21262 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21268 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21269 if (isInt<8>(C->getSExtValue())) {
21270 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21276 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21277 if (C->getZExtValue() <= 255) {
21278 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21284 // 32-bit signed value
21285 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21286 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21287 C->getSExtValue())) {
21288 // Widen to 64 bits here to get it sign extended.
21289 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21292 // FIXME gcc accepts some relocatable values here too, but only in certain
21293 // memory models; it's complicated.
21298 // 32-bit unsigned value
21299 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21300 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21301 C->getZExtValue())) {
21302 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21306 // FIXME gcc accepts some relocatable values here too, but only in certain
21307 // memory models; it's complicated.
21311 // Literal immediates are always ok.
21312 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21313 // Widen to 64 bits here to get it sign extended.
21314 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21318 // In any sort of PIC mode addresses need to be computed at runtime by
21319 // adding in a register or some sort of table lookup. These can't
21320 // be used as immediates.
21321 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21324 // If we are in non-pic codegen mode, we allow the address of a global (with
21325 // an optional displacement) to be used with 'i'.
21326 GlobalAddressSDNode *GA = nullptr;
21327 int64_t Offset = 0;
21329 // Match either (GA), (GA+C), (GA+C1+C2), etc.
21331 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21332 Offset += GA->getOffset();
21334 } else if (Op.getOpcode() == ISD::ADD) {
21335 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21336 Offset += C->getZExtValue();
21337 Op = Op.getOperand(0);
21340 } else if (Op.getOpcode() == ISD::SUB) {
21341 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21342 Offset += -C->getZExtValue();
21343 Op = Op.getOperand(0);
21348 // Otherwise, this isn't something we can handle, reject it.
21352 const GlobalValue *GV = GA->getGlobal();
21353 // If we require an extra load to get this address, as in PIC mode, we
21354 // can't accept it.
21355 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
21356 getTargetMachine())))
21359 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21360 GA->getValueType(0), Offset);
21365 if (Result.getNode()) {
21366 Ops.push_back(Result);
21369 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21372 std::pair<unsigned, const TargetRegisterClass*>
21373 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21375 // First, see if this is a constraint that directly corresponds to an LLVM
21377 if (Constraint.size() == 1) {
21378 // GCC Constraint Letters
21379 switch (Constraint[0]) {
21381 // TODO: Slight differences here in allocation order and leaving
21382 // RIP in the class. Do they matter any more here than they do
21383 // in the normal allocation?
21384 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21385 if (Subtarget->is64Bit()) {
21386 if (VT == MVT::i32 || VT == MVT::f32)
21387 return std::make_pair(0U, &X86::GR32RegClass);
21388 if (VT == MVT::i16)
21389 return std::make_pair(0U, &X86::GR16RegClass);
21390 if (VT == MVT::i8 || VT == MVT::i1)
21391 return std::make_pair(0U, &X86::GR8RegClass);
21392 if (VT == MVT::i64 || VT == MVT::f64)
21393 return std::make_pair(0U, &X86::GR64RegClass);
21396 // 32-bit fallthrough
21397 case 'Q': // Q_REGS
21398 if (VT == MVT::i32 || VT == MVT::f32)
21399 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21400 if (VT == MVT::i16)
21401 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21402 if (VT == MVT::i8 || VT == MVT::i1)
21403 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21404 if (VT == MVT::i64)
21405 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21407 case 'r': // GENERAL_REGS
21408 case 'l': // INDEX_REGS
21409 if (VT == MVT::i8 || VT == MVT::i1)
21410 return std::make_pair(0U, &X86::GR8RegClass);
21411 if (VT == MVT::i16)
21412 return std::make_pair(0U, &X86::GR16RegClass);
21413 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21414 return std::make_pair(0U, &X86::GR32RegClass);
21415 return std::make_pair(0U, &X86::GR64RegClass);
21416 case 'R': // LEGACY_REGS
21417 if (VT == MVT::i8 || VT == MVT::i1)
21418 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21419 if (VT == MVT::i16)
21420 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21421 if (VT == MVT::i32 || !Subtarget->is64Bit())
21422 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21423 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21424 case 'f': // FP Stack registers.
21425 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21426 // value to the correct fpstack register class.
21427 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21428 return std::make_pair(0U, &X86::RFP32RegClass);
21429 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21430 return std::make_pair(0U, &X86::RFP64RegClass);
21431 return std::make_pair(0U, &X86::RFP80RegClass);
21432 case 'y': // MMX_REGS if MMX allowed.
21433 if (!Subtarget->hasMMX()) break;
21434 return std::make_pair(0U, &X86::VR64RegClass);
21435 case 'Y': // SSE_REGS if SSE2 allowed
21436 if (!Subtarget->hasSSE2()) break;
21438 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21439 if (!Subtarget->hasSSE1()) break;
21441 switch (VT.SimpleTy) {
21443 // Scalar SSE types.
21446 return std::make_pair(0U, &X86::FR32RegClass);
21449 return std::make_pair(0U, &X86::FR64RegClass);
21457 return std::make_pair(0U, &X86::VR128RegClass);
21465 return std::make_pair(0U, &X86::VR256RegClass);
21470 return std::make_pair(0U, &X86::VR512RegClass);
21476 // Use the default implementation in TargetLowering to convert the register
21477 // constraint into a member of a register class.
21478 std::pair<unsigned, const TargetRegisterClass*> Res;
21479 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21481 // Not found as a standard register?
21483 // Map st(0) -> st(7) -> ST0
21484 if (Constraint.size() == 7 && Constraint[0] == '{' &&
21485 tolower(Constraint[1]) == 's' &&
21486 tolower(Constraint[2]) == 't' &&
21487 Constraint[3] == '(' &&
21488 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21489 Constraint[5] == ')' &&
21490 Constraint[6] == '}') {
21492 Res.first = X86::ST0+Constraint[4]-'0';
21493 Res.second = &X86::RFP80RegClass;
21497 // GCC allows "st(0)" to be called just plain "st".
21498 if (StringRef("{st}").equals_lower(Constraint)) {
21499 Res.first = X86::ST0;
21500 Res.second = &X86::RFP80RegClass;
21505 if (StringRef("{flags}").equals_lower(Constraint)) {
21506 Res.first = X86::EFLAGS;
21507 Res.second = &X86::CCRRegClass;
21511 // 'A' means EAX + EDX.
21512 if (Constraint == "A") {
21513 Res.first = X86::EAX;
21514 Res.second = &X86::GR32_ADRegClass;
21520 // Otherwise, check to see if this is a register class of the wrong value
21521 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21522 // turn into {ax},{dx}.
21523 if (Res.second->hasType(VT))
21524 return Res; // Correct type already, nothing to do.
21526 // All of the single-register GCC register classes map their values onto
21527 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21528 // really want an 8-bit or 32-bit register, map to the appropriate register
21529 // class and return the appropriate register.
21530 if (Res.second == &X86::GR16RegClass) {
21531 if (VT == MVT::i8 || VT == MVT::i1) {
21532 unsigned DestReg = 0;
21533 switch (Res.first) {
21535 case X86::AX: DestReg = X86::AL; break;
21536 case X86::DX: DestReg = X86::DL; break;
21537 case X86::CX: DestReg = X86::CL; break;
21538 case X86::BX: DestReg = X86::BL; break;
21541 Res.first = DestReg;
21542 Res.second = &X86::GR8RegClass;
21544 } else if (VT == MVT::i32 || VT == MVT::f32) {
21545 unsigned DestReg = 0;
21546 switch (Res.first) {
21548 case X86::AX: DestReg = X86::EAX; break;
21549 case X86::DX: DestReg = X86::EDX; break;
21550 case X86::CX: DestReg = X86::ECX; break;
21551 case X86::BX: DestReg = X86::EBX; break;
21552 case X86::SI: DestReg = X86::ESI; break;
21553 case X86::DI: DestReg = X86::EDI; break;
21554 case X86::BP: DestReg = X86::EBP; break;
21555 case X86::SP: DestReg = X86::ESP; break;
21558 Res.first = DestReg;
21559 Res.second = &X86::GR32RegClass;
21561 } else if (VT == MVT::i64 || VT == MVT::f64) {
21562 unsigned DestReg = 0;
21563 switch (Res.first) {
21565 case X86::AX: DestReg = X86::RAX; break;
21566 case X86::DX: DestReg = X86::RDX; break;
21567 case X86::CX: DestReg = X86::RCX; break;
21568 case X86::BX: DestReg = X86::RBX; break;
21569 case X86::SI: DestReg = X86::RSI; break;
21570 case X86::DI: DestReg = X86::RDI; break;
21571 case X86::BP: DestReg = X86::RBP; break;
21572 case X86::SP: DestReg = X86::RSP; break;
21575 Res.first = DestReg;
21576 Res.second = &X86::GR64RegClass;
21579 } else if (Res.second == &X86::FR32RegClass ||
21580 Res.second == &X86::FR64RegClass ||
21581 Res.second == &X86::VR128RegClass ||
21582 Res.second == &X86::VR256RegClass ||
21583 Res.second == &X86::FR32XRegClass ||
21584 Res.second == &X86::FR64XRegClass ||
21585 Res.second == &X86::VR128XRegClass ||
21586 Res.second == &X86::VR256XRegClass ||
21587 Res.second == &X86::VR512RegClass) {
21588 // Handle references to XMM physical registers that got mapped into the
21589 // wrong class. This can happen with constraints like {xmm0} where the
21590 // target independent register mapper will just pick the first match it can
21591 // find, ignoring the required type.
21593 if (VT == MVT::f32 || VT == MVT::i32)
21594 Res.second = &X86::FR32RegClass;
21595 else if (VT == MVT::f64 || VT == MVT::i64)
21596 Res.second = &X86::FR64RegClass;
21597 else if (X86::VR128RegClass.hasType(VT))
21598 Res.second = &X86::VR128RegClass;
21599 else if (X86::VR256RegClass.hasType(VT))
21600 Res.second = &X86::VR256RegClass;
21601 else if (X86::VR512RegClass.hasType(VT))
21602 Res.second = &X86::VR512RegClass;
21608 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21610 // Scaling factors are not free at all.
21611 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21612 // will take 2 allocations in the out of order engine instead of 1
21613 // for plain addressing mode, i.e. inst (reg1).
21615 // vaddps (%rsi,%drx), %ymm0, %ymm1
21616 // Requires two allocations (one for the load, one for the computation)
21618 // vaddps (%rsi), %ymm0, %ymm1
21619 // Requires just 1 allocation, i.e., freeing allocations for other operations
21620 // and having less micro operations to execute.
21622 // For some X86 architectures, this is even worse because for instance for
21623 // stores, the complex addressing mode forces the instruction to use the
21624 // "load" ports instead of the dedicated "store" port.
21625 // E.g., on Haswell:
21626 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21627 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21628 if (isLegalAddressingMode(AM, Ty))
21629 // Scale represents reg2 * scale, thus account for 1
21630 // as soon as we use a second register.
21631 return AM.Scale != 0;
21635 bool X86TargetLowering::isTargetFTOL() const {
21636 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();