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 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
19 #include "X86CallingConv.h"
20 #include "X86InstrBuilder.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.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 STATISTIC(NumTailCalls, "Number of tail calls");
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
62 SelectionDAG &DAG, SDLoc dl,
63 unsigned vectorWidth) {
64 assert((vectorWidth == 128 || vectorWidth == 256) &&
65 "Unsupported vector width");
66 EVT VT = Vec.getValueType();
67 EVT ElVT = VT.getVectorElementType();
68 unsigned Factor = VT.getSizeInBits()/vectorWidth;
69 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
70 VT.getVectorNumElements()/Factor);
72 // Extract from UNDEF is UNDEF.
73 if (Vec.getOpcode() == ISD::UNDEF)
74 return DAG.getUNDEF(ResultVT);
76 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
77 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
79 // This is the index of the first element of the vectorWidth-bit chunk
81 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
84 // If the input is a buildvector just emit a smaller one.
85 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
86 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
87 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
89 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
90 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
96 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
99 /// instructions or a simple subregister reference. Idx is an index in the
100 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
101 /// lowering EXTRACT_VECTOR_ELT operations easier.
102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
103 SelectionDAG &DAG, SDLoc dl) {
104 assert((Vec.getValueType().is256BitVector() ||
105 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
106 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
109 /// Generate a DAG to grab 256-bits from a 512-bit vector.
110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
111 SelectionDAG &DAG, SDLoc dl) {
112 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
113 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
116 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
117 unsigned IdxVal, SelectionDAG &DAG,
118 SDLoc dl, unsigned vectorWidth) {
119 assert((vectorWidth == 128 || vectorWidth == 256) &&
120 "Unsupported vector width");
121 // Inserting UNDEF is Result
122 if (Vec.getOpcode() == ISD::UNDEF)
124 EVT VT = Vec.getValueType();
125 EVT ElVT = VT.getVectorElementType();
126 EVT ResultVT = Result.getValueType();
128 // Insert the relevant vectorWidth bits.
129 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
131 // This is the index of the first element of the vectorWidth-bit chunk
133 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
136 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
137 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
140 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
143 /// simple superregister reference. Idx is an index in the 128 bits
144 /// we want. It need not be aligned to a 128-bit bounday. That makes
145 /// lowering INSERT_VECTOR_ELT operations easier.
146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
147 unsigned IdxVal, SelectionDAG &DAG,
149 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
150 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
154 unsigned IdxVal, SelectionDAG &DAG,
156 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
157 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
161 /// instructions. This is used because creating CONCAT_VECTOR nodes of
162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
163 /// large BUILD_VECTORS.
164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
165 unsigned NumElems, SelectionDAG &DAG,
167 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
168 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
172 unsigned NumElems, SelectionDAG &DAG,
174 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
175 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
179 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
180 bool is64Bit = Subtarget->is64Bit();
182 if (Subtarget->isTargetMacho()) {
184 return new X86_64MachoTargetObjectFile();
185 return new TargetLoweringObjectFileMachO();
188 if (Subtarget->isTargetLinux())
189 return new X86LinuxTargetObjectFile();
190 if (Subtarget->isTargetELF())
191 return new TargetLoweringObjectFileELF();
192 if (Subtarget->isTargetWindows())
193 return new X86WindowsTargetObjectFile();
194 if (Subtarget->isTargetCOFF())
195 return new TargetLoweringObjectFileCOFF();
196 llvm_unreachable("unknown subtarget type");
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200 : TargetLowering(TM, createTLOF(TM)) {
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->isTargetWindows() && !Subtarget->isTargetCygMing()) {
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, 0);
269 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
270 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
271 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
274 if (Subtarget->isTargetDarwin()) {
275 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
276 setUseUnderscoreSetJmp(false);
277 setUseUnderscoreLongJmp(false);
278 } else if (Subtarget->isTargetMingw()) {
279 // MS runtime is weird: it exports _setjmp, but longjmp!
280 setUseUnderscoreSetJmp(true);
281 setUseUnderscoreLongJmp(false);
283 setUseUnderscoreSetJmp(true);
284 setUseUnderscoreLongJmp(true);
287 // Set up the register classes.
288 addRegisterClass(MVT::i8, &X86::GR8RegClass);
289 addRegisterClass(MVT::i16, &X86::GR16RegClass);
290 addRegisterClass(MVT::i32, &X86::GR32RegClass);
291 if (Subtarget->is64Bit())
292 addRegisterClass(MVT::i64, &X86::GR64RegClass);
294 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296 // We don't accept any truncstore of integer registers.
297 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
304 // SETOEQ and SETUNE require checking two conditions.
305 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
312 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
314 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
315 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
316 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
318 if (Subtarget->is64Bit()) {
319 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
320 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
321 } else if (!TM.Options.UseSoftFloat) {
322 // We have an algorithm for SSE2->double, and we turn this into a
323 // 64-bit FILD followed by conditional FADD for other targets.
324 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
325 // We have an algorithm for SSE2, and we turn this into a 64-bit
326 // FILD for other targets.
327 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
330 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
332 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
333 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
335 if (!TM.Options.UseSoftFloat) {
336 // SSE has no i16 to fp conversion, only i32
337 if (X86ScalarSSEf32) {
338 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
339 // f32 and f64 cases are Legal, f80 case is not
340 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
342 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
343 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
346 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
347 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
350 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
351 // are Legal, f80 is custom lowered.
352 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
353 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
355 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
357 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
358 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
360 if (X86ScalarSSEf32) {
361 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
362 // f32 and f64 cases are Legal, f80 case is not
363 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
365 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
366 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
369 // Handle FP_TO_UINT by promoting the destination to a larger signed
371 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
372 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
373 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
375 if (Subtarget->is64Bit()) {
376 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
377 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
378 } else if (!TM.Options.UseSoftFloat) {
379 // Since AVX is a superset of SSE3, only check for SSE here.
380 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381 // Expand FP_TO_UINT into a select.
382 // FIXME: We would like to use a Custom expander here eventually to do
383 // the optimal thing for SSE vs. the default expansion in the legalizer.
384 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
386 // With SSE3 we can use fisttpll to convert to a signed i64; without
387 // SSE, we're stuck with a fistpll.
388 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
391 if (isTargetFTOL()) {
392 // Use the _ftol2 runtime function, which has a pseudo-instruction
393 // to handle its weird calling convention.
394 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
397 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398 if (!X86ScalarSSEf64) {
399 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
400 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
401 if (Subtarget->is64Bit()) {
402 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
403 // Without SSE, i64->f64 goes through memory.
404 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
408 // Scalar integer divide and remainder are lowered to use operations that
409 // produce two results, to match the available instructions. This exposes
410 // the two-result form to trivial CSE, which is able to combine x/y and x%y
411 // into a single instruction.
413 // Scalar integer multiply-high is also lowered to use two-result
414 // operations, to match the available instructions. However, plain multiply
415 // (low) operations are left as Legal, as there are single-result
416 // instructions for this in x86. Using the two-result multiply instructions
417 // when both high and low results are needed must be arranged by dagcombine.
418 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
420 setOperationAction(ISD::MULHS, VT, Expand);
421 setOperationAction(ISD::MULHU, VT, Expand);
422 setOperationAction(ISD::SDIV, VT, Expand);
423 setOperationAction(ISD::UDIV, VT, Expand);
424 setOperationAction(ISD::SREM, VT, Expand);
425 setOperationAction(ISD::UREM, VT, Expand);
427 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428 setOperationAction(ISD::ADDC, VT, Custom);
429 setOperationAction(ISD::ADDE, VT, Custom);
430 setOperationAction(ISD::SUBC, VT, Custom);
431 setOperationAction(ISD::SUBE, VT, Custom);
434 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
435 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
436 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
437 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
438 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
439 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
443 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
444 if (Subtarget->is64Bit())
445 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
449 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
450 setOperationAction(ISD::FREM , MVT::f32 , Expand);
451 setOperationAction(ISD::FREM , MVT::f64 , Expand);
452 setOperationAction(ISD::FREM , MVT::f80 , Expand);
453 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
455 // Promote the i8 variants and force them on up to i32 which has a shorter
457 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
458 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
459 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
460 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
461 if (Subtarget->hasBMI()) {
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
464 if (Subtarget->is64Bit())
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
467 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
468 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
469 if (Subtarget->is64Bit())
470 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
473 if (Subtarget->hasLZCNT()) {
474 // When promoting the i8 variants, force them to i32 for a shorter
476 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
477 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
478 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
482 if (Subtarget->is64Bit())
483 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
485 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
486 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
487 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
491 if (Subtarget->is64Bit()) {
492 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
493 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
497 if (Subtarget->hasPOPCNT()) {
498 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
500 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
501 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
502 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
507 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
509 if (!Subtarget->hasMOVBE())
510 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
512 // These should be promoted to a larger select which is supported.
513 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
514 // X86 wants to expand cmov itself.
515 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
516 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
517 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
518 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
519 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
521 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
522 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
524 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
525 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
527 if (Subtarget->is64Bit()) {
528 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
529 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
531 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
532 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
533 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
534 // support continuation, user-level threading, and etc.. As a result, no
535 // other SjLj exception interfaces are implemented and please don't build
536 // your own exception handling based on them.
537 // LLVM/Clang supports zero-cost DWARF exception handling.
538 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
539 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
542 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
543 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
544 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
545 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
546 if (Subtarget->is64Bit())
547 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
548 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
549 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
550 if (Subtarget->is64Bit()) {
551 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
552 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
553 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
554 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
555 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
557 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
558 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
559 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
560 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
561 if (Subtarget->is64Bit()) {
562 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
563 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
564 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
567 if (Subtarget->hasSSE1())
568 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
570 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
572 // Expand certain atomics
573 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
575 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
576 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
577 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
580 if (!Subtarget->is64Bit()) {
581 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
582 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
595 if (Subtarget->hasCmpxchg16b()) {
596 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
599 // FIXME - use subtarget debug flags
600 if (!Subtarget->isTargetDarwin() &&
601 !Subtarget->isTargetELF() &&
602 !Subtarget->isTargetCygMing()) {
603 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
606 if (Subtarget->is64Bit()) {
607 setExceptionPointerRegister(X86::RAX);
608 setExceptionSelectorRegister(X86::RDX);
610 setExceptionPointerRegister(X86::EAX);
611 setExceptionSelectorRegister(X86::EDX);
613 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
614 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
616 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
617 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
619 setOperationAction(ISD::TRAP, MVT::Other, Legal);
620 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
622 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
623 setOperationAction(ISD::VASTART , MVT::Other, Custom);
624 setOperationAction(ISD::VAEND , MVT::Other, Expand);
625 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
626 // TargetInfo::X86_64ABIBuiltinVaList
627 setOperationAction(ISD::VAARG , MVT::Other, Custom);
628 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
630 // TargetInfo::CharPtrBuiltinVaList
631 setOperationAction(ISD::VAARG , MVT::Other, Expand);
632 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
635 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
636 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
638 if (Subtarget->isOSWindows() && !Subtarget->isTargetMacho())
639 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640 MVT::i64 : MVT::i32, Custom);
641 else if (TM.Options.EnableSegmentedStacks)
642 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
643 MVT::i64 : MVT::i32, Custom);
645 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
646 MVT::i64 : MVT::i32, Expand);
648 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
649 // f32 and f64 use SSE.
650 // Set up the FP register classes.
651 addRegisterClass(MVT::f32, &X86::FR32RegClass);
652 addRegisterClass(MVT::f64, &X86::FR64RegClass);
654 // Use ANDPD to simulate FABS.
655 setOperationAction(ISD::FABS , MVT::f64, Custom);
656 setOperationAction(ISD::FABS , MVT::f32, Custom);
658 // Use XORP to simulate FNEG.
659 setOperationAction(ISD::FNEG , MVT::f64, Custom);
660 setOperationAction(ISD::FNEG , MVT::f32, Custom);
662 // Use ANDPD and ORPD to simulate FCOPYSIGN.
663 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
664 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
666 // Lower this to FGETSIGNx86 plus an AND.
667 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
668 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
670 // We don't support sin/cos/fmod
671 setOperationAction(ISD::FSIN , MVT::f64, Expand);
672 setOperationAction(ISD::FCOS , MVT::f64, Expand);
673 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
674 setOperationAction(ISD::FSIN , MVT::f32, Expand);
675 setOperationAction(ISD::FCOS , MVT::f32, Expand);
676 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
678 // Expand FP immediates into loads from the stack, except for the special
680 addLegalFPImmediate(APFloat(+0.0)); // xorpd
681 addLegalFPImmediate(APFloat(+0.0f)); // xorps
682 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
683 // Use SSE for f32, x87 for f64.
684 // Set up the FP register classes.
685 addRegisterClass(MVT::f32, &X86::FR32RegClass);
686 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
688 // Use ANDPS to simulate FABS.
689 setOperationAction(ISD::FABS , MVT::f32, Custom);
691 // Use XORP to simulate FNEG.
692 setOperationAction(ISD::FNEG , MVT::f32, Custom);
694 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
696 // Use ANDPS and ORPS to simulate FCOPYSIGN.
697 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
698 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
700 // We don't support sin/cos/fmod
701 setOperationAction(ISD::FSIN , MVT::f32, Expand);
702 setOperationAction(ISD::FCOS , MVT::f32, Expand);
703 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
705 // Special cases we handle for FP constants.
706 addLegalFPImmediate(APFloat(+0.0f)); // xorps
707 addLegalFPImmediate(APFloat(+0.0)); // FLD0
708 addLegalFPImmediate(APFloat(+1.0)); // FLD1
709 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
710 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
712 if (!TM.Options.UnsafeFPMath) {
713 setOperationAction(ISD::FSIN , MVT::f64, Expand);
714 setOperationAction(ISD::FCOS , MVT::f64, Expand);
715 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
717 } else if (!TM.Options.UseSoftFloat) {
718 // f32 and f64 in x87.
719 // Set up the FP register classes.
720 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
721 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
723 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
724 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
725 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
726 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
728 if (!TM.Options.UnsafeFPMath) {
729 setOperationAction(ISD::FSIN , MVT::f64, Expand);
730 setOperationAction(ISD::FSIN , MVT::f32, Expand);
731 setOperationAction(ISD::FCOS , MVT::f64, Expand);
732 setOperationAction(ISD::FCOS , MVT::f32, Expand);
733 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
734 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
736 addLegalFPImmediate(APFloat(+0.0)); // FLD0
737 addLegalFPImmediate(APFloat(+1.0)); // FLD1
738 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
739 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
740 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
741 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
742 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
743 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
746 // We don't support FMA.
747 setOperationAction(ISD::FMA, MVT::f64, Expand);
748 setOperationAction(ISD::FMA, MVT::f32, Expand);
750 // Long double always uses X87.
751 if (!TM.Options.UseSoftFloat) {
752 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
753 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
754 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
756 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
757 addLegalFPImmediate(TmpFlt); // FLD0
759 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
762 APFloat TmpFlt2(+1.0);
763 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
765 addLegalFPImmediate(TmpFlt2); // FLD1
766 TmpFlt2.changeSign();
767 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
770 if (!TM.Options.UnsafeFPMath) {
771 setOperationAction(ISD::FSIN , MVT::f80, Expand);
772 setOperationAction(ISD::FCOS , MVT::f80, Expand);
773 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
776 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
777 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
778 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
779 setOperationAction(ISD::FRINT, MVT::f80, Expand);
780 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
781 setOperationAction(ISD::FMA, MVT::f80, Expand);
784 // Always use a library call for pow.
785 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
786 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
787 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
789 setOperationAction(ISD::FLOG, MVT::f80, Expand);
790 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
791 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
792 setOperationAction(ISD::FEXP, MVT::f80, Expand);
793 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
795 // First set operation action for all vector types to either promote
796 // (for widening) or expand (for scalarization). Then we will selectively
797 // turn on ones that can be effectively codegen'd.
798 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
799 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
800 MVT VT = (MVT::SimpleValueType)i;
801 setOperationAction(ISD::ADD , VT, Expand);
802 setOperationAction(ISD::SUB , VT, Expand);
803 setOperationAction(ISD::FADD, VT, Expand);
804 setOperationAction(ISD::FNEG, VT, Expand);
805 setOperationAction(ISD::FSUB, VT, Expand);
806 setOperationAction(ISD::MUL , VT, Expand);
807 setOperationAction(ISD::FMUL, VT, Expand);
808 setOperationAction(ISD::SDIV, VT, Expand);
809 setOperationAction(ISD::UDIV, VT, Expand);
810 setOperationAction(ISD::FDIV, VT, Expand);
811 setOperationAction(ISD::SREM, VT, Expand);
812 setOperationAction(ISD::UREM, VT, Expand);
813 setOperationAction(ISD::LOAD, VT, Expand);
814 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
816 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
817 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
818 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
819 setOperationAction(ISD::FABS, VT, Expand);
820 setOperationAction(ISD::FSIN, VT, Expand);
821 setOperationAction(ISD::FSINCOS, VT, Expand);
822 setOperationAction(ISD::FCOS, VT, Expand);
823 setOperationAction(ISD::FSINCOS, VT, Expand);
824 setOperationAction(ISD::FREM, VT, Expand);
825 setOperationAction(ISD::FMA, VT, Expand);
826 setOperationAction(ISD::FPOWI, VT, Expand);
827 setOperationAction(ISD::FSQRT, VT, Expand);
828 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
829 setOperationAction(ISD::FFLOOR, VT, Expand);
830 setOperationAction(ISD::FCEIL, VT, Expand);
831 setOperationAction(ISD::FTRUNC, VT, Expand);
832 setOperationAction(ISD::FRINT, VT, Expand);
833 setOperationAction(ISD::FNEARBYINT, VT, Expand);
834 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
835 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
836 setOperationAction(ISD::SDIVREM, VT, Expand);
837 setOperationAction(ISD::UDIVREM, VT, Expand);
838 setOperationAction(ISD::FPOW, VT, Expand);
839 setOperationAction(ISD::CTPOP, VT, Expand);
840 setOperationAction(ISD::CTTZ, VT, Expand);
841 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
842 setOperationAction(ISD::CTLZ, VT, Expand);
843 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
844 setOperationAction(ISD::SHL, VT, Expand);
845 setOperationAction(ISD::SRA, VT, Expand);
846 setOperationAction(ISD::SRL, VT, Expand);
847 setOperationAction(ISD::ROTL, VT, Expand);
848 setOperationAction(ISD::ROTR, VT, Expand);
849 setOperationAction(ISD::BSWAP, VT, Expand);
850 setOperationAction(ISD::SETCC, VT, Expand);
851 setOperationAction(ISD::FLOG, VT, Expand);
852 setOperationAction(ISD::FLOG2, VT, Expand);
853 setOperationAction(ISD::FLOG10, VT, Expand);
854 setOperationAction(ISD::FEXP, VT, Expand);
855 setOperationAction(ISD::FEXP2, VT, Expand);
856 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
857 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
858 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
859 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
860 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
861 setOperationAction(ISD::TRUNCATE, VT, Expand);
862 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
863 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
864 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
865 setOperationAction(ISD::VSELECT, VT, Expand);
866 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
867 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
868 setTruncStoreAction(VT,
869 (MVT::SimpleValueType)InnerVT, Expand);
870 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
871 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
872 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
875 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
876 // with -msoft-float, disable use of MMX as well.
877 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
878 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
879 // No operations on x86mmx supported, everything uses intrinsics.
882 // MMX-sized vectors (other than x86mmx) are expected to be expanded
883 // into smaller operations.
884 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
885 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
886 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
887 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
888 setOperationAction(ISD::AND, MVT::v8i8, Expand);
889 setOperationAction(ISD::AND, MVT::v4i16, Expand);
890 setOperationAction(ISD::AND, MVT::v2i32, Expand);
891 setOperationAction(ISD::AND, MVT::v1i64, Expand);
892 setOperationAction(ISD::OR, MVT::v8i8, Expand);
893 setOperationAction(ISD::OR, MVT::v4i16, Expand);
894 setOperationAction(ISD::OR, MVT::v2i32, Expand);
895 setOperationAction(ISD::OR, MVT::v1i64, Expand);
896 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
897 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
898 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
899 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
900 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
901 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
902 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
903 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
904 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
905 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
906 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
907 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
908 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
909 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
910 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
911 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
912 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
914 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
915 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
917 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
918 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
919 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
920 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
921 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
922 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
923 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
924 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
925 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
926 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
927 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
928 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
931 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
932 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
934 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
935 // registers cannot be used even for integer operations.
936 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
937 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
938 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
939 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
941 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
942 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
943 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
944 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
945 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
946 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
947 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
948 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
949 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
950 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
951 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
952 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
953 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
954 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
955 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
956 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
957 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
958 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
960 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
961 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
962 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
963 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
965 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
966 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
971 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
972 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
973 MVT VT = (MVT::SimpleValueType)i;
974 // Do not attempt to custom lower non-power-of-2 vectors
975 if (!isPowerOf2_32(VT.getVectorNumElements()))
977 // Do not attempt to custom lower non-128-bit vectors
978 if (!VT.is128BitVector())
980 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
981 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
982 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
985 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
986 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
987 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
988 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
989 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
992 if (Subtarget->is64Bit()) {
993 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
994 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
997 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
998 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
999 MVT VT = (MVT::SimpleValueType)i;
1001 // Do not attempt to promote non-128-bit vectors
1002 if (!VT.is128BitVector())
1005 setOperationAction(ISD::AND, VT, Promote);
1006 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1007 setOperationAction(ISD::OR, VT, Promote);
1008 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1009 setOperationAction(ISD::XOR, VT, Promote);
1010 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1011 setOperationAction(ISD::LOAD, VT, Promote);
1012 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1013 setOperationAction(ISD::SELECT, VT, Promote);
1014 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1017 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1019 // Custom lower v2i64 and v2f64 selects.
1020 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1021 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1022 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1023 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1025 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1026 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1028 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1029 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1030 // As there is no 64-bit GPR available, we need build a special custom
1031 // sequence to convert from v2i32 to v2f32.
1032 if (!Subtarget->is64Bit())
1033 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1035 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1036 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1038 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1041 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1042 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1043 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1044 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1045 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1046 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1047 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1048 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1049 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1050 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1051 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1053 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1054 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1055 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1056 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1057 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1058 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1059 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1060 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1061 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1062 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1064 // FIXME: Do we need to handle scalar-to-vector here?
1065 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1068 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1069 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1073 // i8 and i16 vectors are custom , because the source register and source
1074 // source memory operand types are not the same width. f32 vectors are
1075 // custom since the immediate controlling the insert encodes additional
1077 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1078 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1079 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1080 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1082 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1083 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1084 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1085 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1087 // FIXME: these should be Legal but thats only for the case where
1088 // the index is constant. For now custom expand to deal with that.
1089 if (Subtarget->is64Bit()) {
1090 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1091 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1095 if (Subtarget->hasSSE2()) {
1096 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1097 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1099 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1100 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1102 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1103 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1105 // In the customized shift lowering, the legal cases in AVX2 will be
1107 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1108 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1110 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1111 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1113 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1115 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1116 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1119 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1120 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1122 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1123 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1124 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1125 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1127 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1128 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1129 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1131 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1140 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1142 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1144 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1153 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1154 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1155 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1157 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1158 // even though v8i16 is a legal type.
1159 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1160 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1161 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1163 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1164 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1165 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1167 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1168 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1170 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1172 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1176 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1183 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1184 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1185 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1186 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1188 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1189 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1190 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1192 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1193 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1194 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1195 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1197 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1198 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1199 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1200 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1201 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1202 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1203 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1204 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1205 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1206 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1207 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1208 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1210 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1211 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1212 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1213 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1214 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1215 setOperationAction(ISD::FMA, MVT::f32, Legal);
1216 setOperationAction(ISD::FMA, MVT::f64, Legal);
1219 if (Subtarget->hasInt256()) {
1220 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1221 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1222 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1223 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1225 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1226 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1227 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1228 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1230 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1231 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1232 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1233 // Don't lower v32i8 because there is no 128-bit byte mul
1235 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1237 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1239 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1240 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1241 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1242 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1244 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1245 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1246 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1247 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1249 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1250 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1251 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1252 // Don't lower v32i8 because there is no 128-bit byte mul
1255 // In the customized shift lowering, the legal cases in AVX2 will be
1257 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1258 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1260 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1261 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1263 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1265 // Custom lower several nodes for 256-bit types.
1266 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1267 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1268 MVT VT = (MVT::SimpleValueType)i;
1270 // Extract subvector is special because the value type
1271 // (result) is 128-bit but the source is 256-bit wide.
1272 if (VT.is128BitVector())
1273 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1275 // Do not attempt to custom lower other non-256-bit vectors
1276 if (!VT.is256BitVector())
1279 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1280 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1281 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1282 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1283 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1284 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1285 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1288 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1289 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1290 MVT VT = (MVT::SimpleValueType)i;
1292 // Do not attempt to promote non-256-bit vectors
1293 if (!VT.is256BitVector())
1296 setOperationAction(ISD::AND, VT, Promote);
1297 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1298 setOperationAction(ISD::OR, VT, Promote);
1299 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1300 setOperationAction(ISD::XOR, VT, Promote);
1301 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1302 setOperationAction(ISD::LOAD, VT, Promote);
1303 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1304 setOperationAction(ISD::SELECT, VT, Promote);
1305 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1309 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1310 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1311 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1312 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1313 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1315 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1316 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1317 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1319 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1320 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1321 setOperationAction(ISD::XOR, MVT::i1, Legal);
1322 setOperationAction(ISD::OR, MVT::i1, Legal);
1323 setOperationAction(ISD::AND, MVT::i1, Legal);
1324 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1325 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1326 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1327 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1328 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1329 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1331 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1332 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1333 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1334 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1335 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1336 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1338 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1340 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1341 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1342 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1343 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1344 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1345 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1346 setOperationAction(ISD::SDIV, MVT::v16i32, Custom);
1348 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1349 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1350 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1351 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1352 if (Subtarget->is64Bit()) {
1353 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1354 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1355 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1356 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1358 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1359 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1360 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1361 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1362 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1363 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1364 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1365 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1367 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1368 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1369 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1372 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1373 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1374 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1375 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1376 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1377 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1378 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1379 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1381 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1383 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1384 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1386 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1388 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1389 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1391 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1393 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1395 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1396 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1397 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1398 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1399 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1401 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1402 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1404 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1405 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1407 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1409 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1410 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1412 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1413 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1415 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1416 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1418 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1419 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1420 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1421 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1422 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1423 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1425 // Custom lower several nodes.
1426 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1427 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1428 MVT VT = (MVT::SimpleValueType)i;
1430 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1431 // Extract subvector is special because the value type
1432 // (result) is 256/128-bit but the source is 512-bit wide.
1433 if (VT.is128BitVector() || VT.is256BitVector())
1434 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1436 if (VT.getVectorElementType() == MVT::i1)
1437 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1439 // Do not attempt to custom lower other non-512-bit vectors
1440 if (!VT.is512BitVector())
1443 if ( EltSize >= 32) {
1444 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1445 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1446 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1447 setOperationAction(ISD::VSELECT, VT, Legal);
1448 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1449 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1450 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1453 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1454 MVT VT = (MVT::SimpleValueType)i;
1456 // Do not attempt to promote non-256-bit vectors
1457 if (!VT.is512BitVector())
1460 setOperationAction(ISD::SELECT, VT, Promote);
1461 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1465 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1466 // of this type with custom code.
1467 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1468 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1469 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1473 // We want to custom lower some of our intrinsics.
1474 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1475 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1476 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1478 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1479 // handle type legalization for these operations here.
1481 // FIXME: We really should do custom legalization for addition and
1482 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1483 // than generic legalization for 64-bit multiplication-with-overflow, though.
1484 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1485 // Add/Sub/Mul with overflow operations are custom lowered.
1487 setOperationAction(ISD::SADDO, VT, Custom);
1488 setOperationAction(ISD::UADDO, VT, Custom);
1489 setOperationAction(ISD::SSUBO, VT, Custom);
1490 setOperationAction(ISD::USUBO, VT, Custom);
1491 setOperationAction(ISD::SMULO, VT, Custom);
1492 setOperationAction(ISD::UMULO, VT, Custom);
1495 // There are no 8-bit 3-address imul/mul instructions
1496 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1497 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1499 if (!Subtarget->is64Bit()) {
1500 // These libcalls are not available in 32-bit.
1501 setLibcallName(RTLIB::SHL_I128, 0);
1502 setLibcallName(RTLIB::SRL_I128, 0);
1503 setLibcallName(RTLIB::SRA_I128, 0);
1506 // Combine sin / cos into one node or libcall if possible.
1507 if (Subtarget->hasSinCos()) {
1508 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1509 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1510 if (Subtarget->isTargetDarwin()) {
1511 // For MacOSX, we don't want to the normal expansion of a libcall to
1512 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1514 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1515 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1519 // We have target-specific dag combine patterns for the following nodes:
1520 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1521 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1522 setTargetDAGCombine(ISD::VSELECT);
1523 setTargetDAGCombine(ISD::SELECT);
1524 setTargetDAGCombine(ISD::SHL);
1525 setTargetDAGCombine(ISD::SRA);
1526 setTargetDAGCombine(ISD::SRL);
1527 setTargetDAGCombine(ISD::OR);
1528 setTargetDAGCombine(ISD::AND);
1529 setTargetDAGCombine(ISD::ADD);
1530 setTargetDAGCombine(ISD::FADD);
1531 setTargetDAGCombine(ISD::FSUB);
1532 setTargetDAGCombine(ISD::FMA);
1533 setTargetDAGCombine(ISD::SUB);
1534 setTargetDAGCombine(ISD::LOAD);
1535 setTargetDAGCombine(ISD::STORE);
1536 setTargetDAGCombine(ISD::ZERO_EXTEND);
1537 setTargetDAGCombine(ISD::ANY_EXTEND);
1538 setTargetDAGCombine(ISD::SIGN_EXTEND);
1539 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1540 setTargetDAGCombine(ISD::TRUNCATE);
1541 setTargetDAGCombine(ISD::SINT_TO_FP);
1542 setTargetDAGCombine(ISD::SETCC);
1543 if (Subtarget->is64Bit())
1544 setTargetDAGCombine(ISD::MUL);
1545 setTargetDAGCombine(ISD::XOR);
1547 computeRegisterProperties();
1549 // On Darwin, -Os means optimize for size without hurting performance,
1550 // do not reduce the limit.
1551 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1552 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1553 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1554 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1555 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1556 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1557 setPrefLoopAlignment(4); // 2^4 bytes.
1559 // Predictable cmov don't hurt on atom because it's in-order.
1560 PredictableSelectIsExpensive = !Subtarget->isAtom();
1562 setPrefFunctionAlignment(4); // 2^4 bytes.
1565 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1567 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1569 if (Subtarget->hasAVX512())
1570 switch(VT.getVectorNumElements()) {
1571 case 8: return MVT::v8i1;
1572 case 16: return MVT::v16i1;
1575 return VT.changeVectorElementTypeToInteger();
1578 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1579 /// the desired ByVal argument alignment.
1580 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1583 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1584 if (VTy->getBitWidth() == 128)
1586 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1587 unsigned EltAlign = 0;
1588 getMaxByValAlign(ATy->getElementType(), EltAlign);
1589 if (EltAlign > MaxAlign)
1590 MaxAlign = EltAlign;
1591 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1592 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1593 unsigned EltAlign = 0;
1594 getMaxByValAlign(STy->getElementType(i), EltAlign);
1595 if (EltAlign > MaxAlign)
1596 MaxAlign = EltAlign;
1603 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1604 /// function arguments in the caller parameter area. For X86, aggregates
1605 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1606 /// are at 4-byte boundaries.
1607 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1608 if (Subtarget->is64Bit()) {
1609 // Max of 8 and alignment of type.
1610 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1617 if (Subtarget->hasSSE1())
1618 getMaxByValAlign(Ty, Align);
1622 /// getOptimalMemOpType - Returns the target specific optimal type for load
1623 /// and store operations as a result of memset, memcpy, and memmove
1624 /// lowering. If DstAlign is zero that means it's safe to destination
1625 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1626 /// means there isn't a need to check it against alignment requirement,
1627 /// probably because the source does not need to be loaded. If 'IsMemset' is
1628 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1629 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1630 /// source is constant so it does not need to be loaded.
1631 /// It returns EVT::Other if the type should be determined using generic
1632 /// target-independent logic.
1634 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1635 unsigned DstAlign, unsigned SrcAlign,
1636 bool IsMemset, bool ZeroMemset,
1638 MachineFunction &MF) const {
1639 const Function *F = MF.getFunction();
1640 if ((!IsMemset || ZeroMemset) &&
1641 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1642 Attribute::NoImplicitFloat)) {
1644 (Subtarget->isUnalignedMemAccessFast() ||
1645 ((DstAlign == 0 || DstAlign >= 16) &&
1646 (SrcAlign == 0 || SrcAlign >= 16)))) {
1648 if (Subtarget->hasInt256())
1650 if (Subtarget->hasFp256())
1653 if (Subtarget->hasSSE2())
1655 if (Subtarget->hasSSE1())
1657 } else if (!MemcpyStrSrc && Size >= 8 &&
1658 !Subtarget->is64Bit() &&
1659 Subtarget->hasSSE2()) {
1660 // Do not use f64 to lower memcpy if source is string constant. It's
1661 // better to use i32 to avoid the loads.
1665 if (Subtarget->is64Bit() && Size >= 8)
1670 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1672 return X86ScalarSSEf32;
1673 else if (VT == MVT::f64)
1674 return X86ScalarSSEf64;
1679 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1683 *Fast = Subtarget->isUnalignedMemAccessFast();
1687 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1688 /// current function. The returned value is a member of the
1689 /// MachineJumpTableInfo::JTEntryKind enum.
1690 unsigned X86TargetLowering::getJumpTableEncoding() const {
1691 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1693 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1694 Subtarget->isPICStyleGOT())
1695 return MachineJumpTableInfo::EK_Custom32;
1697 // Otherwise, use the normal jump table encoding heuristics.
1698 return TargetLowering::getJumpTableEncoding();
1702 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1703 const MachineBasicBlock *MBB,
1704 unsigned uid,MCContext &Ctx) const{
1705 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1706 Subtarget->isPICStyleGOT());
1707 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1709 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1710 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1713 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1715 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1716 SelectionDAG &DAG) const {
1717 if (!Subtarget->is64Bit())
1718 // This doesn't have SDLoc associated with it, but is not really the
1719 // same as a Register.
1720 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1724 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1725 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1727 const MCExpr *X86TargetLowering::
1728 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1729 MCContext &Ctx) const {
1730 // X86-64 uses RIP relative addressing based on the jump table label.
1731 if (Subtarget->isPICStyleRIPRel())
1732 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1734 // Otherwise, the reference is relative to the PIC base.
1735 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1738 // FIXME: Why this routine is here? Move to RegInfo!
1739 std::pair<const TargetRegisterClass*, uint8_t>
1740 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1741 const TargetRegisterClass *RRC = 0;
1743 switch (VT.SimpleTy) {
1745 return TargetLowering::findRepresentativeClass(VT);
1746 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1747 RRC = Subtarget->is64Bit() ?
1748 (const TargetRegisterClass*)&X86::GR64RegClass :
1749 (const TargetRegisterClass*)&X86::GR32RegClass;
1752 RRC = &X86::VR64RegClass;
1754 case MVT::f32: case MVT::f64:
1755 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1756 case MVT::v4f32: case MVT::v2f64:
1757 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1759 RRC = &X86::VR128RegClass;
1762 return std::make_pair(RRC, Cost);
1765 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1766 unsigned &Offset) const {
1767 if (!Subtarget->isTargetLinux())
1770 if (Subtarget->is64Bit()) {
1771 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1773 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1785 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1786 unsigned DestAS) const {
1787 assert(SrcAS != DestAS && "Expected different address spaces!");
1789 return SrcAS < 256 && DestAS < 256;
1792 //===----------------------------------------------------------------------===//
1793 // Return Value Calling Convention Implementation
1794 //===----------------------------------------------------------------------===//
1796 #include "X86GenCallingConv.inc"
1799 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1800 MachineFunction &MF, bool isVarArg,
1801 const SmallVectorImpl<ISD::OutputArg> &Outs,
1802 LLVMContext &Context) const {
1803 SmallVector<CCValAssign, 16> RVLocs;
1804 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1806 return CCInfo.CheckReturn(Outs, RetCC_X86);
1809 const uint16_t *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1810 static const uint16_t ScratchRegs[] = { X86::R11, 0 };
1815 X86TargetLowering::LowerReturn(SDValue Chain,
1816 CallingConv::ID CallConv, bool isVarArg,
1817 const SmallVectorImpl<ISD::OutputArg> &Outs,
1818 const SmallVectorImpl<SDValue> &OutVals,
1819 SDLoc dl, SelectionDAG &DAG) const {
1820 MachineFunction &MF = DAG.getMachineFunction();
1821 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1823 SmallVector<CCValAssign, 16> RVLocs;
1824 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1825 RVLocs, *DAG.getContext());
1826 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1829 SmallVector<SDValue, 6> RetOps;
1830 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1831 // Operand #1 = Bytes To Pop
1832 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1835 // Copy the result values into the output registers.
1836 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1837 CCValAssign &VA = RVLocs[i];
1838 assert(VA.isRegLoc() && "Can only return in registers!");
1839 SDValue ValToCopy = OutVals[i];
1840 EVT ValVT = ValToCopy.getValueType();
1842 // Promote values to the appropriate types
1843 if (VA.getLocInfo() == CCValAssign::SExt)
1844 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1845 else if (VA.getLocInfo() == CCValAssign::ZExt)
1846 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1847 else if (VA.getLocInfo() == CCValAssign::AExt)
1848 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1849 else if (VA.getLocInfo() == CCValAssign::BCvt)
1850 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1852 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1853 "Unexpected FP-extend for return value.");
1855 // If this is x86-64, and we disabled SSE, we can't return FP values,
1856 // or SSE or MMX vectors.
1857 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1858 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1859 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1860 report_fatal_error("SSE register return with SSE disabled");
1862 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1863 // llvm-gcc has never done it right and no one has noticed, so this
1864 // should be OK for now.
1865 if (ValVT == MVT::f64 &&
1866 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1867 report_fatal_error("SSE2 register return with SSE2 disabled");
1869 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1870 // the RET instruction and handled by the FP Stackifier.
1871 if (VA.getLocReg() == X86::ST0 ||
1872 VA.getLocReg() == X86::ST1) {
1873 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1874 // change the value to the FP stack register class.
1875 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1876 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1877 RetOps.push_back(ValToCopy);
1878 // Don't emit a copytoreg.
1882 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1883 // which is returned in RAX / RDX.
1884 if (Subtarget->is64Bit()) {
1885 if (ValVT == MVT::x86mmx) {
1886 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1887 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1888 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1890 // If we don't have SSE2 available, convert to v4f32 so the generated
1891 // register is legal.
1892 if (!Subtarget->hasSSE2())
1893 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1898 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1899 Flag = Chain.getValue(1);
1900 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1903 // The x86-64 ABIs require that for returning structs by value we copy
1904 // the sret argument into %rax/%eax (depending on ABI) for the return.
1905 // Win32 requires us to put the sret argument to %eax as well.
1906 // We saved the argument into a virtual register in the entry block,
1907 // so now we copy the value out and into %rax/%eax.
1908 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1909 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1910 MachineFunction &MF = DAG.getMachineFunction();
1911 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1912 unsigned Reg = FuncInfo->getSRetReturnReg();
1914 "SRetReturnReg should have been set in LowerFormalArguments().");
1915 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1918 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1919 X86::RAX : X86::EAX;
1920 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1921 Flag = Chain.getValue(1);
1923 // RAX/EAX now acts like a return value.
1924 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1927 RetOps[0] = Chain; // Update chain.
1929 // Add the flag if we have it.
1931 RetOps.push_back(Flag);
1933 return DAG.getNode(X86ISD::RET_FLAG, dl,
1934 MVT::Other, &RetOps[0], RetOps.size());
1937 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1938 if (N->getNumValues() != 1)
1940 if (!N->hasNUsesOfValue(1, 0))
1943 SDValue TCChain = Chain;
1944 SDNode *Copy = *N->use_begin();
1945 if (Copy->getOpcode() == ISD::CopyToReg) {
1946 // If the copy has a glue operand, we conservatively assume it isn't safe to
1947 // perform a tail call.
1948 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1950 TCChain = Copy->getOperand(0);
1951 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1954 bool HasRet = false;
1955 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1957 if (UI->getOpcode() != X86ISD::RET_FLAG)
1970 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1971 ISD::NodeType ExtendKind) const {
1973 // TODO: Is this also valid on 32-bit?
1974 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1975 ReturnMVT = MVT::i8;
1977 ReturnMVT = MVT::i32;
1979 MVT MinVT = getRegisterType(ReturnMVT);
1980 return VT.bitsLT(MinVT) ? MinVT : VT;
1983 /// LowerCallResult - Lower the result values of a call into the
1984 /// appropriate copies out of appropriate physical registers.
1987 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1988 CallingConv::ID CallConv, bool isVarArg,
1989 const SmallVectorImpl<ISD::InputArg> &Ins,
1990 SDLoc dl, SelectionDAG &DAG,
1991 SmallVectorImpl<SDValue> &InVals) const {
1993 // Assign locations to each value returned by this call.
1994 SmallVector<CCValAssign, 16> RVLocs;
1995 bool Is64Bit = Subtarget->is64Bit();
1996 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1997 getTargetMachine(), RVLocs, *DAG.getContext());
1998 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2000 // Copy all of the result registers out of their specified physreg.
2001 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2002 CCValAssign &VA = RVLocs[i];
2003 EVT CopyVT = VA.getValVT();
2005 // If this is x86-64, and we disabled SSE, we can't return FP values
2006 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2007 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2008 report_fatal_error("SSE register return with SSE disabled");
2013 // If this is a call to a function that returns an fp value on the floating
2014 // point stack, we must guarantee the value is popped from the stack, so
2015 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2016 // if the return value is not used. We use the FpPOP_RETVAL instruction
2018 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2019 // If we prefer to use the value in xmm registers, copy it out as f80 and
2020 // use a truncate to move it from fp stack reg to xmm reg.
2021 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2022 SDValue Ops[] = { Chain, InFlag };
2023 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2024 MVT::Other, MVT::Glue, Ops), 1);
2025 Val = Chain.getValue(0);
2027 // Round the f80 to the right size, which also moves it to the appropriate
2029 if (CopyVT != VA.getValVT())
2030 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2031 // This truncation won't change the value.
2032 DAG.getIntPtrConstant(1));
2034 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2035 CopyVT, InFlag).getValue(1);
2036 Val = Chain.getValue(0);
2038 InFlag = Chain.getValue(2);
2039 InVals.push_back(Val);
2045 //===----------------------------------------------------------------------===//
2046 // C & StdCall & Fast Calling Convention implementation
2047 //===----------------------------------------------------------------------===//
2048 // StdCall calling convention seems to be standard for many Windows' API
2049 // routines and around. It differs from C calling convention just a little:
2050 // callee should clean up the stack, not caller. Symbols should be also
2051 // decorated in some fancy way :) It doesn't support any vector arguments.
2052 // For info on fast calling convention see Fast Calling Convention (tail call)
2053 // implementation LowerX86_32FastCCCallTo.
2055 /// CallIsStructReturn - Determines whether a call uses struct return
2057 enum StructReturnType {
2062 static StructReturnType
2063 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2065 return NotStructReturn;
2067 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2068 if (!Flags.isSRet())
2069 return NotStructReturn;
2070 if (Flags.isInReg())
2071 return RegStructReturn;
2072 return StackStructReturn;
2075 /// ArgsAreStructReturn - Determines whether a function uses struct
2076 /// return semantics.
2077 static StructReturnType
2078 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2080 return NotStructReturn;
2082 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2083 if (!Flags.isSRet())
2084 return NotStructReturn;
2085 if (Flags.isInReg())
2086 return RegStructReturn;
2087 return StackStructReturn;
2090 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2091 /// by "Src" to address "Dst" with size and alignment information specified by
2092 /// the specific parameter attribute. The copy will be passed as a byval
2093 /// function parameter.
2095 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2096 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2098 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2100 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2101 /*isVolatile*/false, /*AlwaysInline=*/true,
2102 MachinePointerInfo(), MachinePointerInfo());
2105 /// IsTailCallConvention - Return true if the calling convention is one that
2106 /// supports tail call optimization.
2107 static bool IsTailCallConvention(CallingConv::ID CC) {
2108 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2109 CC == CallingConv::HiPE);
2112 /// \brief Return true if the calling convention is a C calling convention.
2113 static bool IsCCallConvention(CallingConv::ID CC) {
2114 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2115 CC == CallingConv::X86_64_SysV);
2118 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2119 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2123 CallingConv::ID CalleeCC = CS.getCallingConv();
2124 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2130 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2131 /// a tailcall target by changing its ABI.
2132 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2133 bool GuaranteedTailCallOpt) {
2134 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2138 X86TargetLowering::LowerMemArgument(SDValue Chain,
2139 CallingConv::ID CallConv,
2140 const SmallVectorImpl<ISD::InputArg> &Ins,
2141 SDLoc dl, SelectionDAG &DAG,
2142 const CCValAssign &VA,
2143 MachineFrameInfo *MFI,
2145 // Create the nodes corresponding to a load from this parameter slot.
2146 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2147 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2148 getTargetMachine().Options.GuaranteedTailCallOpt);
2149 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2152 // If value is passed by pointer we have address passed instead of the value
2154 if (VA.getLocInfo() == CCValAssign::Indirect)
2155 ValVT = VA.getLocVT();
2157 ValVT = VA.getValVT();
2159 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2160 // changed with more analysis.
2161 // In case of tail call optimization mark all arguments mutable. Since they
2162 // could be overwritten by lowering of arguments in case of a tail call.
2163 if (Flags.isByVal()) {
2164 unsigned Bytes = Flags.getByValSize();
2165 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2166 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2167 return DAG.getFrameIndex(FI, getPointerTy());
2169 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2170 VA.getLocMemOffset(), isImmutable);
2171 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2172 return DAG.getLoad(ValVT, dl, Chain, FIN,
2173 MachinePointerInfo::getFixedStack(FI),
2174 false, false, false, 0);
2179 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2180 CallingConv::ID CallConv,
2182 const SmallVectorImpl<ISD::InputArg> &Ins,
2185 SmallVectorImpl<SDValue> &InVals)
2187 MachineFunction &MF = DAG.getMachineFunction();
2188 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2190 const Function* Fn = MF.getFunction();
2191 if (Fn->hasExternalLinkage() &&
2192 Subtarget->isTargetCygMing() &&
2193 Fn->getName() == "main")
2194 FuncInfo->setForceFramePointer(true);
2196 MachineFrameInfo *MFI = MF.getFrameInfo();
2197 bool Is64Bit = Subtarget->is64Bit();
2198 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2200 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2201 "Var args not supported with calling convention fastcc, ghc or hipe");
2203 // Assign locations to all of the incoming arguments.
2204 SmallVector<CCValAssign, 16> ArgLocs;
2205 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2206 ArgLocs, *DAG.getContext());
2208 // Allocate shadow area for Win64
2210 CCInfo.AllocateStack(32, 8);
2212 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2214 unsigned LastVal = ~0U;
2216 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2217 CCValAssign &VA = ArgLocs[i];
2218 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2220 assert(VA.getValNo() != LastVal &&
2221 "Don't support value assigned to multiple locs yet");
2223 LastVal = VA.getValNo();
2225 if (VA.isRegLoc()) {
2226 EVT RegVT = VA.getLocVT();
2227 const TargetRegisterClass *RC;
2228 if (RegVT == MVT::i32)
2229 RC = &X86::GR32RegClass;
2230 else if (Is64Bit && RegVT == MVT::i64)
2231 RC = &X86::GR64RegClass;
2232 else if (RegVT == MVT::f32)
2233 RC = &X86::FR32RegClass;
2234 else if (RegVT == MVT::f64)
2235 RC = &X86::FR64RegClass;
2236 else if (RegVT.is512BitVector())
2237 RC = &X86::VR512RegClass;
2238 else if (RegVT.is256BitVector())
2239 RC = &X86::VR256RegClass;
2240 else if (RegVT.is128BitVector())
2241 RC = &X86::VR128RegClass;
2242 else if (RegVT == MVT::x86mmx)
2243 RC = &X86::VR64RegClass;
2244 else if (RegVT == MVT::i1)
2245 RC = &X86::VK1RegClass;
2246 else if (RegVT == MVT::v8i1)
2247 RC = &X86::VK8RegClass;
2248 else if (RegVT == MVT::v16i1)
2249 RC = &X86::VK16RegClass;
2251 llvm_unreachable("Unknown argument type!");
2253 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2254 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2256 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2257 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2259 if (VA.getLocInfo() == CCValAssign::SExt)
2260 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2261 DAG.getValueType(VA.getValVT()));
2262 else if (VA.getLocInfo() == CCValAssign::ZExt)
2263 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2264 DAG.getValueType(VA.getValVT()));
2265 else if (VA.getLocInfo() == CCValAssign::BCvt)
2266 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2268 if (VA.isExtInLoc()) {
2269 // Handle MMX values passed in XMM regs.
2270 if (RegVT.isVector())
2271 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2273 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2276 assert(VA.isMemLoc());
2277 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2280 // If value is passed via pointer - do a load.
2281 if (VA.getLocInfo() == CCValAssign::Indirect)
2282 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2283 MachinePointerInfo(), false, false, false, 0);
2285 InVals.push_back(ArgValue);
2288 // The x86-64 ABIs require that for returning structs by value we copy
2289 // the sret argument into %rax/%eax (depending on ABI) for the return.
2290 // Win32 requires us to put the sret argument to %eax as well.
2291 // Save the argument into a virtual register so that we can access it
2292 // from the return points.
2293 if (MF.getFunction()->hasStructRetAttr() &&
2294 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2295 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2296 unsigned Reg = FuncInfo->getSRetReturnReg();
2298 MVT PtrTy = getPointerTy();
2299 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2300 FuncInfo->setSRetReturnReg(Reg);
2302 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2303 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2306 unsigned StackSize = CCInfo.getNextStackOffset();
2307 // Align stack specially for tail calls.
2308 if (FuncIsMadeTailCallSafe(CallConv,
2309 MF.getTarget().Options.GuaranteedTailCallOpt))
2310 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2312 // If the function takes variable number of arguments, make a frame index for
2313 // the start of the first vararg value... for expansion of llvm.va_start.
2315 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2316 CallConv != CallingConv::X86_ThisCall)) {
2317 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2320 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2322 // FIXME: We should really autogenerate these arrays
2323 static const uint16_t GPR64ArgRegsWin64[] = {
2324 X86::RCX, X86::RDX, X86::R8, X86::R9
2326 static const uint16_t GPR64ArgRegs64Bit[] = {
2327 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2329 static const uint16_t XMMArgRegs64Bit[] = {
2330 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2331 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2333 const uint16_t *GPR64ArgRegs;
2334 unsigned NumXMMRegs = 0;
2337 // The XMM registers which might contain var arg parameters are shadowed
2338 // in their paired GPR. So we only need to save the GPR to their home
2340 TotalNumIntRegs = 4;
2341 GPR64ArgRegs = GPR64ArgRegsWin64;
2343 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2344 GPR64ArgRegs = GPR64ArgRegs64Bit;
2346 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2349 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2352 bool NoImplicitFloatOps = Fn->getAttributes().
2353 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2354 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2355 "SSE register cannot be used when SSE is disabled!");
2356 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2357 NoImplicitFloatOps) &&
2358 "SSE register cannot be used when SSE is disabled!");
2359 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2360 !Subtarget->hasSSE1())
2361 // Kernel mode asks for SSE to be disabled, so don't push them
2363 TotalNumXMMRegs = 0;
2366 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2367 // Get to the caller-allocated home save location. Add 8 to account
2368 // for the return address.
2369 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2370 FuncInfo->setRegSaveFrameIndex(
2371 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2372 // Fixup to set vararg frame on shadow area (4 x i64).
2374 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2376 // For X86-64, if there are vararg parameters that are passed via
2377 // registers, then we must store them to their spots on the stack so
2378 // they may be loaded by deferencing the result of va_next.
2379 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2380 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2381 FuncInfo->setRegSaveFrameIndex(
2382 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2386 // Store the integer parameter registers.
2387 SmallVector<SDValue, 8> MemOps;
2388 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2390 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2391 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2392 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2393 DAG.getIntPtrConstant(Offset));
2394 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2395 &X86::GR64RegClass);
2396 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2398 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2399 MachinePointerInfo::getFixedStack(
2400 FuncInfo->getRegSaveFrameIndex(), Offset),
2402 MemOps.push_back(Store);
2406 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2407 // Now store the XMM (fp + vector) parameter registers.
2408 SmallVector<SDValue, 11> SaveXMMOps;
2409 SaveXMMOps.push_back(Chain);
2411 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2412 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2413 SaveXMMOps.push_back(ALVal);
2415 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2416 FuncInfo->getRegSaveFrameIndex()));
2417 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2418 FuncInfo->getVarArgsFPOffset()));
2420 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2421 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2422 &X86::VR128RegClass);
2423 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2424 SaveXMMOps.push_back(Val);
2426 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2428 &SaveXMMOps[0], SaveXMMOps.size()));
2431 if (!MemOps.empty())
2432 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2433 &MemOps[0], MemOps.size());
2437 // Some CCs need callee pop.
2438 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2439 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2440 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2442 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2443 // If this is an sret function, the return should pop the hidden pointer.
2444 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2445 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2446 argsAreStructReturn(Ins) == StackStructReturn)
2447 FuncInfo->setBytesToPopOnReturn(4);
2451 // RegSaveFrameIndex is X86-64 only.
2452 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2453 if (CallConv == CallingConv::X86_FastCall ||
2454 CallConv == CallingConv::X86_ThisCall)
2455 // fastcc functions can't have varargs.
2456 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2459 FuncInfo->setArgumentStackSize(StackSize);
2465 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2466 SDValue StackPtr, SDValue Arg,
2467 SDLoc dl, SelectionDAG &DAG,
2468 const CCValAssign &VA,
2469 ISD::ArgFlagsTy Flags) const {
2470 unsigned LocMemOffset = VA.getLocMemOffset();
2471 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2472 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2473 if (Flags.isByVal())
2474 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2476 return DAG.getStore(Chain, dl, Arg, PtrOff,
2477 MachinePointerInfo::getStack(LocMemOffset),
2481 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2482 /// optimization is performed and it is required.
2484 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2485 SDValue &OutRetAddr, SDValue Chain,
2486 bool IsTailCall, bool Is64Bit,
2487 int FPDiff, SDLoc dl) const {
2488 // Adjust the Return address stack slot.
2489 EVT VT = getPointerTy();
2490 OutRetAddr = getReturnAddressFrameIndex(DAG);
2492 // Load the "old" Return address.
2493 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2494 false, false, false, 0);
2495 return SDValue(OutRetAddr.getNode(), 1);
2498 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2499 /// optimization is performed and it is required (FPDiff!=0).
2501 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2502 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2503 unsigned SlotSize, int FPDiff, SDLoc dl) {
2504 // Store the return address to the appropriate stack slot.
2505 if (!FPDiff) return Chain;
2506 // Calculate the new stack slot for the return address.
2507 int NewReturnAddrFI =
2508 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2510 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2511 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2512 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2518 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2519 SmallVectorImpl<SDValue> &InVals) const {
2520 SelectionDAG &DAG = CLI.DAG;
2522 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2523 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2524 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2525 SDValue Chain = CLI.Chain;
2526 SDValue Callee = CLI.Callee;
2527 CallingConv::ID CallConv = CLI.CallConv;
2528 bool &isTailCall = CLI.IsTailCall;
2529 bool isVarArg = CLI.IsVarArg;
2531 MachineFunction &MF = DAG.getMachineFunction();
2532 bool Is64Bit = Subtarget->is64Bit();
2533 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2534 StructReturnType SR = callIsStructReturn(Outs);
2535 bool IsSibcall = false;
2537 if (MF.getTarget().Options.DisableTailCalls)
2541 // Check if it's really possible to do a tail call.
2542 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2543 isVarArg, SR != NotStructReturn,
2544 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2545 Outs, OutVals, Ins, DAG);
2547 // Sibcalls are automatically detected tailcalls which do not require
2549 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2556 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2557 "Var args not supported with calling convention fastcc, ghc or hipe");
2559 // Analyze operands of the call, assigning locations to each operand.
2560 SmallVector<CCValAssign, 16> ArgLocs;
2561 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2562 ArgLocs, *DAG.getContext());
2564 // Allocate shadow area for Win64
2566 CCInfo.AllocateStack(32, 8);
2568 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2570 // Get a count of how many bytes are to be pushed on the stack.
2571 unsigned NumBytes = CCInfo.getNextStackOffset();
2573 // This is a sibcall. The memory operands are available in caller's
2574 // own caller's stack.
2576 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2577 IsTailCallConvention(CallConv))
2578 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2581 if (isTailCall && !IsSibcall) {
2582 // Lower arguments at fp - stackoffset + fpdiff.
2583 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2584 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2586 FPDiff = NumBytesCallerPushed - NumBytes;
2588 // Set the delta of movement of the returnaddr stackslot.
2589 // But only set if delta is greater than previous delta.
2590 if (FPDiff < X86Info->getTCReturnAddrDelta())
2591 X86Info->setTCReturnAddrDelta(FPDiff);
2594 unsigned NumBytesToPush = NumBytes;
2595 unsigned NumBytesToPop = NumBytes;
2597 // If we have an inalloca argument, all stack space has already been allocated
2598 // for us and be right at the top of the stack. We don't support multiple
2599 // arguments passed in memory when using inalloca.
2600 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2602 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2603 "an inalloca argument must be the only memory argument");
2607 Chain = DAG.getCALLSEQ_START(
2608 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2610 SDValue RetAddrFrIdx;
2611 // Load return address for tail calls.
2612 if (isTailCall && FPDiff)
2613 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2614 Is64Bit, FPDiff, dl);
2616 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2617 SmallVector<SDValue, 8> MemOpChains;
2620 // Walk the register/memloc assignments, inserting copies/loads. In the case
2621 // of tail call optimization arguments are handle later.
2622 const X86RegisterInfo *RegInfo =
2623 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2624 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2625 // Skip inalloca arguments, they have already been written.
2626 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2627 if (Flags.isInAlloca())
2630 CCValAssign &VA = ArgLocs[i];
2631 EVT RegVT = VA.getLocVT();
2632 SDValue Arg = OutVals[i];
2633 bool isByVal = Flags.isByVal();
2635 // Promote the value if needed.
2636 switch (VA.getLocInfo()) {
2637 default: llvm_unreachable("Unknown loc info!");
2638 case CCValAssign::Full: break;
2639 case CCValAssign::SExt:
2640 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2642 case CCValAssign::ZExt:
2643 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2645 case CCValAssign::AExt:
2646 if (RegVT.is128BitVector()) {
2647 // Special case: passing MMX values in XMM registers.
2648 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2649 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2650 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2652 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2654 case CCValAssign::BCvt:
2655 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2657 case CCValAssign::Indirect: {
2658 // Store the argument.
2659 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2660 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2661 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2662 MachinePointerInfo::getFixedStack(FI),
2669 if (VA.isRegLoc()) {
2670 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2671 if (isVarArg && IsWin64) {
2672 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2673 // shadow reg if callee is a varargs function.
2674 unsigned ShadowReg = 0;
2675 switch (VA.getLocReg()) {
2676 case X86::XMM0: ShadowReg = X86::RCX; break;
2677 case X86::XMM1: ShadowReg = X86::RDX; break;
2678 case X86::XMM2: ShadowReg = X86::R8; break;
2679 case X86::XMM3: ShadowReg = X86::R9; break;
2682 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2684 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2685 assert(VA.isMemLoc());
2686 if (StackPtr.getNode() == 0)
2687 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2689 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2690 dl, DAG, VA, Flags));
2694 if (!MemOpChains.empty())
2695 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2696 &MemOpChains[0], MemOpChains.size());
2698 if (Subtarget->isPICStyleGOT()) {
2699 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2702 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2703 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2705 // If we are tail calling and generating PIC/GOT style code load the
2706 // address of the callee into ECX. The value in ecx is used as target of
2707 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2708 // for tail calls on PIC/GOT architectures. Normally we would just put the
2709 // address of GOT into ebx and then call target@PLT. But for tail calls
2710 // ebx would be restored (since ebx is callee saved) before jumping to the
2713 // Note: The actual moving to ECX is done further down.
2714 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2715 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2716 !G->getGlobal()->hasProtectedVisibility())
2717 Callee = LowerGlobalAddress(Callee, DAG);
2718 else if (isa<ExternalSymbolSDNode>(Callee))
2719 Callee = LowerExternalSymbol(Callee, DAG);
2723 if (Is64Bit && isVarArg && !IsWin64) {
2724 // From AMD64 ABI document:
2725 // For calls that may call functions that use varargs or stdargs
2726 // (prototype-less calls or calls to functions containing ellipsis (...) in
2727 // the declaration) %al is used as hidden argument to specify the number
2728 // of SSE registers used. The contents of %al do not need to match exactly
2729 // the number of registers, but must be an ubound on the number of SSE
2730 // registers used and is in the range 0 - 8 inclusive.
2732 // Count the number of XMM registers allocated.
2733 static const uint16_t XMMArgRegs[] = {
2734 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2735 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2737 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2738 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2739 && "SSE registers cannot be used when SSE is disabled");
2741 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2742 DAG.getConstant(NumXMMRegs, MVT::i8)));
2745 // For tail calls lower the arguments to the 'real' stack slot.
2747 // Force all the incoming stack arguments to be loaded from the stack
2748 // before any new outgoing arguments are stored to the stack, because the
2749 // outgoing stack slots may alias the incoming argument stack slots, and
2750 // the alias isn't otherwise explicit. This is slightly more conservative
2751 // than necessary, because it means that each store effectively depends
2752 // on every argument instead of just those arguments it would clobber.
2753 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2755 SmallVector<SDValue, 8> MemOpChains2;
2758 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2759 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2760 CCValAssign &VA = ArgLocs[i];
2763 assert(VA.isMemLoc());
2764 SDValue Arg = OutVals[i];
2765 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2766 // Create frame index.
2767 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2768 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2769 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2770 FIN = DAG.getFrameIndex(FI, getPointerTy());
2772 if (Flags.isByVal()) {
2773 // Copy relative to framepointer.
2774 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2775 if (StackPtr.getNode() == 0)
2776 StackPtr = DAG.getCopyFromReg(Chain, dl,
2777 RegInfo->getStackRegister(),
2779 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2781 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2785 // Store relative to framepointer.
2786 MemOpChains2.push_back(
2787 DAG.getStore(ArgChain, dl, Arg, FIN,
2788 MachinePointerInfo::getFixedStack(FI),
2794 if (!MemOpChains2.empty())
2795 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2796 &MemOpChains2[0], MemOpChains2.size());
2798 // Store the return address to the appropriate stack slot.
2799 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2800 getPointerTy(), RegInfo->getSlotSize(),
2804 // Build a sequence of copy-to-reg nodes chained together with token chain
2805 // and flag operands which copy the outgoing args into registers.
2807 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2808 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2809 RegsToPass[i].second, InFlag);
2810 InFlag = Chain.getValue(1);
2813 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2814 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2815 // In the 64-bit large code model, we have to make all calls
2816 // through a register, since the call instruction's 32-bit
2817 // pc-relative offset may not be large enough to hold the whole
2819 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2820 // If the callee is a GlobalAddress node (quite common, every direct call
2821 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2824 // We should use extra load for direct calls to dllimported functions in
2826 const GlobalValue *GV = G->getGlobal();
2827 if (!GV->hasDLLImportStorageClass()) {
2828 unsigned char OpFlags = 0;
2829 bool ExtraLoad = false;
2830 unsigned WrapperKind = ISD::DELETED_NODE;
2832 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2833 // external symbols most go through the PLT in PIC mode. If the symbol
2834 // has hidden or protected visibility, or if it is static or local, then
2835 // we don't need to use the PLT - we can directly call it.
2836 if (Subtarget->isTargetELF() &&
2837 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2838 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2839 OpFlags = X86II::MO_PLT;
2840 } else if (Subtarget->isPICStyleStubAny() &&
2841 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2842 (!Subtarget->getTargetTriple().isMacOSX() ||
2843 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2844 // PC-relative references to external symbols should go through $stub,
2845 // unless we're building with the leopard linker or later, which
2846 // automatically synthesizes these stubs.
2847 OpFlags = X86II::MO_DARWIN_STUB;
2848 } else if (Subtarget->isPICStyleRIPRel() &&
2849 isa<Function>(GV) &&
2850 cast<Function>(GV)->getAttributes().
2851 hasAttribute(AttributeSet::FunctionIndex,
2852 Attribute::NonLazyBind)) {
2853 // If the function is marked as non-lazy, generate an indirect call
2854 // which loads from the GOT directly. This avoids runtime overhead
2855 // at the cost of eager binding (and one extra byte of encoding).
2856 OpFlags = X86II::MO_GOTPCREL;
2857 WrapperKind = X86ISD::WrapperRIP;
2861 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2862 G->getOffset(), OpFlags);
2864 // Add a wrapper if needed.
2865 if (WrapperKind != ISD::DELETED_NODE)
2866 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2867 // Add extra indirection if needed.
2869 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2870 MachinePointerInfo::getGOT(),
2871 false, false, false, 0);
2873 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2874 unsigned char OpFlags = 0;
2876 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2877 // external symbols should go through the PLT.
2878 if (Subtarget->isTargetELF() &&
2879 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2880 OpFlags = X86II::MO_PLT;
2881 } else if (Subtarget->isPICStyleStubAny() &&
2882 (!Subtarget->getTargetTriple().isMacOSX() ||
2883 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2884 // PC-relative references to external symbols should go through $stub,
2885 // unless we're building with the leopard linker or later, which
2886 // automatically synthesizes these stubs.
2887 OpFlags = X86II::MO_DARWIN_STUB;
2890 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2894 // Returns a chain & a flag for retval copy to use.
2895 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2896 SmallVector<SDValue, 8> Ops;
2898 if (!IsSibcall && isTailCall) {
2899 Chain = DAG.getCALLSEQ_END(Chain,
2900 DAG.getIntPtrConstant(NumBytesToPop, true),
2901 DAG.getIntPtrConstant(0, true), InFlag, dl);
2902 InFlag = Chain.getValue(1);
2905 Ops.push_back(Chain);
2906 Ops.push_back(Callee);
2909 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2911 // Add argument registers to the end of the list so that they are known live
2913 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2914 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2915 RegsToPass[i].second.getValueType()));
2917 // Add a register mask operand representing the call-preserved registers.
2918 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2919 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2920 assert(Mask && "Missing call preserved mask for calling convention");
2921 Ops.push_back(DAG.getRegisterMask(Mask));
2923 if (InFlag.getNode())
2924 Ops.push_back(InFlag);
2928 //// If this is the first return lowered for this function, add the regs
2929 //// to the liveout set for the function.
2930 // This isn't right, although it's probably harmless on x86; liveouts
2931 // should be computed from returns not tail calls. Consider a void
2932 // function making a tail call to a function returning int.
2933 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2936 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2937 InFlag = Chain.getValue(1);
2939 // Create the CALLSEQ_END node.
2940 unsigned NumBytesForCalleeToPop;
2941 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2942 getTargetMachine().Options.GuaranteedTailCallOpt))
2943 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2944 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2945 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2946 SR == StackStructReturn)
2947 // If this is a call to a struct-return function, the callee
2948 // pops the hidden struct pointer, so we have to push it back.
2949 // This is common for Darwin/X86, Linux & Mingw32 targets.
2950 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2951 NumBytesForCalleeToPop = 4;
2953 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2955 // Returns a flag for retval copy to use.
2957 Chain = DAG.getCALLSEQ_END(Chain,
2958 DAG.getIntPtrConstant(NumBytesToPop, true),
2959 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2962 InFlag = Chain.getValue(1);
2965 // Handle result values, copying them out of physregs into vregs that we
2967 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2968 Ins, dl, DAG, InVals);
2971 //===----------------------------------------------------------------------===//
2972 // Fast Calling Convention (tail call) implementation
2973 //===----------------------------------------------------------------------===//
2975 // Like std call, callee cleans arguments, convention except that ECX is
2976 // reserved for storing the tail called function address. Only 2 registers are
2977 // free for argument passing (inreg). Tail call optimization is performed
2979 // * tailcallopt is enabled
2980 // * caller/callee are fastcc
2981 // On X86_64 architecture with GOT-style position independent code only local
2982 // (within module) calls are supported at the moment.
2983 // To keep the stack aligned according to platform abi the function
2984 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2985 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2986 // If a tail called function callee has more arguments than the caller the
2987 // caller needs to make sure that there is room to move the RETADDR to. This is
2988 // achieved by reserving an area the size of the argument delta right after the
2989 // original REtADDR, but before the saved framepointer or the spilled registers
2990 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3002 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3003 /// for a 16 byte align requirement.
3005 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3006 SelectionDAG& DAG) const {
3007 MachineFunction &MF = DAG.getMachineFunction();
3008 const TargetMachine &TM = MF.getTarget();
3009 const X86RegisterInfo *RegInfo =
3010 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3011 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3012 unsigned StackAlignment = TFI.getStackAlignment();
3013 uint64_t AlignMask = StackAlignment - 1;
3014 int64_t Offset = StackSize;
3015 unsigned SlotSize = RegInfo->getSlotSize();
3016 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3017 // Number smaller than 12 so just add the difference.
3018 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3020 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3021 Offset = ((~AlignMask) & Offset) + StackAlignment +
3022 (StackAlignment-SlotSize);
3027 /// MatchingStackOffset - Return true if the given stack call argument is
3028 /// already available in the same position (relatively) of the caller's
3029 /// incoming argument stack.
3031 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3032 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3033 const X86InstrInfo *TII) {
3034 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3036 if (Arg.getOpcode() == ISD::CopyFromReg) {
3037 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3038 if (!TargetRegisterInfo::isVirtualRegister(VR))
3040 MachineInstr *Def = MRI->getVRegDef(VR);
3043 if (!Flags.isByVal()) {
3044 if (!TII->isLoadFromStackSlot(Def, FI))
3047 unsigned Opcode = Def->getOpcode();
3048 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3049 Def->getOperand(1).isFI()) {
3050 FI = Def->getOperand(1).getIndex();
3051 Bytes = Flags.getByValSize();
3055 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3056 if (Flags.isByVal())
3057 // ByVal argument is passed in as a pointer but it's now being
3058 // dereferenced. e.g.
3059 // define @foo(%struct.X* %A) {
3060 // tail call @bar(%struct.X* byval %A)
3063 SDValue Ptr = Ld->getBasePtr();
3064 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3067 FI = FINode->getIndex();
3068 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3069 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3070 FI = FINode->getIndex();
3071 Bytes = Flags.getByValSize();
3075 assert(FI != INT_MAX);
3076 if (!MFI->isFixedObjectIndex(FI))
3078 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3081 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3082 /// for tail call optimization. Targets which want to do tail call
3083 /// optimization should implement this function.
3085 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3086 CallingConv::ID CalleeCC,
3088 bool isCalleeStructRet,
3089 bool isCallerStructRet,
3091 const SmallVectorImpl<ISD::OutputArg> &Outs,
3092 const SmallVectorImpl<SDValue> &OutVals,
3093 const SmallVectorImpl<ISD::InputArg> &Ins,
3094 SelectionDAG &DAG) const {
3095 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3098 // If -tailcallopt is specified, make fastcc functions tail-callable.
3099 const MachineFunction &MF = DAG.getMachineFunction();
3100 const Function *CallerF = MF.getFunction();
3102 // If the function return type is x86_fp80 and the callee return type is not,
3103 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3104 // perform a tailcall optimization here.
3105 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3108 CallingConv::ID CallerCC = CallerF->getCallingConv();
3109 bool CCMatch = CallerCC == CalleeCC;
3110 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3111 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3113 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3114 if (IsTailCallConvention(CalleeCC) && CCMatch)
3119 // Look for obvious safe cases to perform tail call optimization that do not
3120 // require ABI changes. This is what gcc calls sibcall.
3122 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3123 // emit a special epilogue.
3124 const X86RegisterInfo *RegInfo =
3125 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3126 if (RegInfo->needsStackRealignment(MF))
3129 // Also avoid sibcall optimization if either caller or callee uses struct
3130 // return semantics.
3131 if (isCalleeStructRet || isCallerStructRet)
3134 // An stdcall/thiscall caller is expected to clean up its arguments; the
3135 // callee isn't going to do that.
3136 // FIXME: this is more restrictive than needed. We could produce a tailcall
3137 // when the stack adjustment matches. For example, with a thiscall that takes
3138 // only one argument.
3139 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3140 CallerCC == CallingConv::X86_ThisCall))
3143 // Do not sibcall optimize vararg calls unless all arguments are passed via
3145 if (isVarArg && !Outs.empty()) {
3147 // Optimizing for varargs on Win64 is unlikely to be safe without
3148 // additional testing.
3149 if (IsCalleeWin64 || IsCallerWin64)
3152 SmallVector<CCValAssign, 16> ArgLocs;
3153 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3154 getTargetMachine(), ArgLocs, *DAG.getContext());
3156 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3157 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3158 if (!ArgLocs[i].isRegLoc())
3162 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3163 // stack. Therefore, if it's not used by the call it is not safe to optimize
3164 // this into a sibcall.
3165 bool Unused = false;
3166 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3173 SmallVector<CCValAssign, 16> RVLocs;
3174 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3175 getTargetMachine(), RVLocs, *DAG.getContext());
3176 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3177 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3178 CCValAssign &VA = RVLocs[i];
3179 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3184 // If the calling conventions do not match, then we'd better make sure the
3185 // results are returned in the same way as what the caller expects.
3187 SmallVector<CCValAssign, 16> RVLocs1;
3188 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3189 getTargetMachine(), RVLocs1, *DAG.getContext());
3190 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3192 SmallVector<CCValAssign, 16> RVLocs2;
3193 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3194 getTargetMachine(), RVLocs2, *DAG.getContext());
3195 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3197 if (RVLocs1.size() != RVLocs2.size())
3199 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3200 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3202 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3204 if (RVLocs1[i].isRegLoc()) {
3205 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3208 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3214 // If the callee takes no arguments then go on to check the results of the
3216 if (!Outs.empty()) {
3217 // Check if stack adjustment is needed. For now, do not do this if any
3218 // argument is passed on the stack.
3219 SmallVector<CCValAssign, 16> ArgLocs;
3220 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3221 getTargetMachine(), ArgLocs, *DAG.getContext());
3223 // Allocate shadow area for Win64
3225 CCInfo.AllocateStack(32, 8);
3227 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3228 if (CCInfo.getNextStackOffset()) {
3229 MachineFunction &MF = DAG.getMachineFunction();
3230 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3233 // Check if the arguments are already laid out in the right way as
3234 // the caller's fixed stack objects.
3235 MachineFrameInfo *MFI = MF.getFrameInfo();
3236 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3237 const X86InstrInfo *TII =
3238 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3239 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3240 CCValAssign &VA = ArgLocs[i];
3241 SDValue Arg = OutVals[i];
3242 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3243 if (VA.getLocInfo() == CCValAssign::Indirect)
3245 if (!VA.isRegLoc()) {
3246 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3253 // If the tailcall address may be in a register, then make sure it's
3254 // possible to register allocate for it. In 32-bit, the call address can
3255 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3256 // callee-saved registers are restored. These happen to be the same
3257 // registers used to pass 'inreg' arguments so watch out for those.
3258 if (!Subtarget->is64Bit() &&
3259 ((!isa<GlobalAddressSDNode>(Callee) &&
3260 !isa<ExternalSymbolSDNode>(Callee)) ||
3261 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3262 unsigned NumInRegs = 0;
3263 // In PIC we need an extra register to formulate the address computation
3265 unsigned MaxInRegs =
3266 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3268 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3269 CCValAssign &VA = ArgLocs[i];
3272 unsigned Reg = VA.getLocReg();
3275 case X86::EAX: case X86::EDX: case X86::ECX:
3276 if (++NumInRegs == MaxInRegs)
3288 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3289 const TargetLibraryInfo *libInfo) const {
3290 return X86::createFastISel(funcInfo, libInfo);
3293 //===----------------------------------------------------------------------===//
3294 // Other Lowering Hooks
3295 //===----------------------------------------------------------------------===//
3297 static bool MayFoldLoad(SDValue Op) {
3298 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3301 static bool MayFoldIntoStore(SDValue Op) {
3302 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3305 static bool isTargetShuffle(unsigned Opcode) {
3307 default: return false;
3308 case X86ISD::PSHUFD:
3309 case X86ISD::PSHUFHW:
3310 case X86ISD::PSHUFLW:
3312 case X86ISD::PALIGNR:
3313 case X86ISD::MOVLHPS:
3314 case X86ISD::MOVLHPD:
3315 case X86ISD::MOVHLPS:
3316 case X86ISD::MOVLPS:
3317 case X86ISD::MOVLPD:
3318 case X86ISD::MOVSHDUP:
3319 case X86ISD::MOVSLDUP:
3320 case X86ISD::MOVDDUP:
3323 case X86ISD::UNPCKL:
3324 case X86ISD::UNPCKH:
3325 case X86ISD::VPERMILP:
3326 case X86ISD::VPERM2X128:
3327 case X86ISD::VPERMI:
3332 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3333 SDValue V1, SelectionDAG &DAG) {
3335 default: llvm_unreachable("Unknown x86 shuffle node");
3336 case X86ISD::MOVSHDUP:
3337 case X86ISD::MOVSLDUP:
3338 case X86ISD::MOVDDUP:
3339 return DAG.getNode(Opc, dl, VT, V1);
3343 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3344 SDValue V1, unsigned TargetMask,
3345 SelectionDAG &DAG) {
3347 default: llvm_unreachable("Unknown x86 shuffle node");
3348 case X86ISD::PSHUFD:
3349 case X86ISD::PSHUFHW:
3350 case X86ISD::PSHUFLW:
3351 case X86ISD::VPERMILP:
3352 case X86ISD::VPERMI:
3353 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3357 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3358 SDValue V1, SDValue V2, unsigned TargetMask,
3359 SelectionDAG &DAG) {
3361 default: llvm_unreachable("Unknown x86 shuffle node");
3362 case X86ISD::PALIGNR:
3364 case X86ISD::VPERM2X128:
3365 return DAG.getNode(Opc, dl, VT, V1, V2,
3366 DAG.getConstant(TargetMask, MVT::i8));
3370 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3371 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3373 default: llvm_unreachable("Unknown x86 shuffle node");
3374 case X86ISD::MOVLHPS:
3375 case X86ISD::MOVLHPD:
3376 case X86ISD::MOVHLPS:
3377 case X86ISD::MOVLPS:
3378 case X86ISD::MOVLPD:
3381 case X86ISD::UNPCKL:
3382 case X86ISD::UNPCKH:
3383 return DAG.getNode(Opc, dl, VT, V1, V2);
3387 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3388 MachineFunction &MF = DAG.getMachineFunction();
3389 const X86RegisterInfo *RegInfo =
3390 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3391 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3392 int ReturnAddrIndex = FuncInfo->getRAIndex();
3394 if (ReturnAddrIndex == 0) {
3395 // Set up a frame object for the return address.
3396 unsigned SlotSize = RegInfo->getSlotSize();
3397 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3400 FuncInfo->setRAIndex(ReturnAddrIndex);
3403 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3406 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3407 bool hasSymbolicDisplacement) {
3408 // Offset should fit into 32 bit immediate field.
3409 if (!isInt<32>(Offset))
3412 // If we don't have a symbolic displacement - we don't have any extra
3414 if (!hasSymbolicDisplacement)
3417 // FIXME: Some tweaks might be needed for medium code model.
3418 if (M != CodeModel::Small && M != CodeModel::Kernel)
3421 // For small code model we assume that latest object is 16MB before end of 31
3422 // bits boundary. We may also accept pretty large negative constants knowing
3423 // that all objects are in the positive half of address space.
3424 if (M == CodeModel::Small && Offset < 16*1024*1024)
3427 // For kernel code model we know that all object resist in the negative half
3428 // of 32bits address space. We may not accept negative offsets, since they may
3429 // be just off and we may accept pretty large positive ones.
3430 if (M == CodeModel::Kernel && Offset > 0)
3436 /// isCalleePop - Determines whether the callee is required to pop its
3437 /// own arguments. Callee pop is necessary to support tail calls.
3438 bool X86::isCalleePop(CallingConv::ID CallingConv,
3439 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3443 switch (CallingConv) {
3446 case CallingConv::X86_StdCall:
3448 case CallingConv::X86_FastCall:
3450 case CallingConv::X86_ThisCall:
3452 case CallingConv::Fast:
3454 case CallingConv::GHC:
3456 case CallingConv::HiPE:
3461 /// \brief Return true if the condition is an unsigned comparison operation.
3462 static bool isX86CCUnsigned(unsigned X86CC) {
3464 default: llvm_unreachable("Invalid integer condition!");
3465 case X86::COND_E: return true;
3466 case X86::COND_G: return false;
3467 case X86::COND_GE: return false;
3468 case X86::COND_L: return false;
3469 case X86::COND_LE: return false;
3470 case X86::COND_NE: return true;
3471 case X86::COND_B: return true;
3472 case X86::COND_A: return true;
3473 case X86::COND_BE: return true;
3474 case X86::COND_AE: return true;
3476 llvm_unreachable("covered switch fell through?!");
3479 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3480 /// specific condition code, returning the condition code and the LHS/RHS of the
3481 /// comparison to make.
3482 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3483 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3485 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3486 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3487 // X > -1 -> X == 0, jump !sign.
3488 RHS = DAG.getConstant(0, RHS.getValueType());
3489 return X86::COND_NS;
3491 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3492 // X < 0 -> X == 0, jump on sign.
3495 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3497 RHS = DAG.getConstant(0, RHS.getValueType());
3498 return X86::COND_LE;
3502 switch (SetCCOpcode) {
3503 default: llvm_unreachable("Invalid integer condition!");
3504 case ISD::SETEQ: return X86::COND_E;
3505 case ISD::SETGT: return X86::COND_G;
3506 case ISD::SETGE: return X86::COND_GE;
3507 case ISD::SETLT: return X86::COND_L;
3508 case ISD::SETLE: return X86::COND_LE;
3509 case ISD::SETNE: return X86::COND_NE;
3510 case ISD::SETULT: return X86::COND_B;
3511 case ISD::SETUGT: return X86::COND_A;
3512 case ISD::SETULE: return X86::COND_BE;
3513 case ISD::SETUGE: return X86::COND_AE;
3517 // First determine if it is required or is profitable to flip the operands.
3519 // If LHS is a foldable load, but RHS is not, flip the condition.
3520 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3521 !ISD::isNON_EXTLoad(RHS.getNode())) {
3522 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3523 std::swap(LHS, RHS);
3526 switch (SetCCOpcode) {
3532 std::swap(LHS, RHS);
3536 // On a floating point condition, the flags are set as follows:
3538 // 0 | 0 | 0 | X > Y
3539 // 0 | 0 | 1 | X < Y
3540 // 1 | 0 | 0 | X == Y
3541 // 1 | 1 | 1 | unordered
3542 switch (SetCCOpcode) {
3543 default: llvm_unreachable("Condcode should be pre-legalized away");
3545 case ISD::SETEQ: return X86::COND_E;
3546 case ISD::SETOLT: // flipped
3548 case ISD::SETGT: return X86::COND_A;
3549 case ISD::SETOLE: // flipped
3551 case ISD::SETGE: return X86::COND_AE;
3552 case ISD::SETUGT: // flipped
3554 case ISD::SETLT: return X86::COND_B;
3555 case ISD::SETUGE: // flipped
3557 case ISD::SETLE: return X86::COND_BE;
3559 case ISD::SETNE: return X86::COND_NE;
3560 case ISD::SETUO: return X86::COND_P;
3561 case ISD::SETO: return X86::COND_NP;
3563 case ISD::SETUNE: return X86::COND_INVALID;
3567 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3568 /// code. Current x86 isa includes the following FP cmov instructions:
3569 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3570 static bool hasFPCMov(unsigned X86CC) {
3586 /// isFPImmLegal - Returns true if the target can instruction select the
3587 /// specified FP immediate natively. If false, the legalizer will
3588 /// materialize the FP immediate as a load from a constant pool.
3589 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3590 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3591 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3597 /// \brief Returns true if it is beneficial to convert a load of a constant
3598 /// to just the constant itself.
3599 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3601 assert(Ty->isIntegerTy());
3603 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3604 if (BitSize == 0 || BitSize > 64)
3609 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3610 /// the specified range (L, H].
3611 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3612 return (Val < 0) || (Val >= Low && Val < Hi);
3615 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3616 /// specified value.
3617 static bool isUndefOrEqual(int Val, int CmpVal) {
3618 return (Val < 0 || Val == CmpVal);
3621 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3622 /// from position Pos and ending in Pos+Size, falls within the specified
3623 /// sequential range (L, L+Pos]. or is undef.
3624 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3625 unsigned Pos, unsigned Size, int Low) {
3626 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3627 if (!isUndefOrEqual(Mask[i], Low))
3632 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3633 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3634 /// the second operand.
3635 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3636 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3637 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3638 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3639 return (Mask[0] < 2 && Mask[1] < 2);
3643 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3644 /// is suitable for input to PSHUFHW.
3645 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3646 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3649 // Lower quadword copied in order or undef.
3650 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3653 // Upper quadword shuffled.
3654 for (unsigned i = 4; i != 8; ++i)
3655 if (!isUndefOrInRange(Mask[i], 4, 8))
3658 if (VT == MVT::v16i16) {
3659 // Lower quadword copied in order or undef.
3660 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3663 // Upper quadword shuffled.
3664 for (unsigned i = 12; i != 16; ++i)
3665 if (!isUndefOrInRange(Mask[i], 12, 16))
3672 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3673 /// is suitable for input to PSHUFLW.
3674 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3675 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3678 // Upper quadword copied in order.
3679 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3682 // Lower quadword shuffled.
3683 for (unsigned i = 0; i != 4; ++i)
3684 if (!isUndefOrInRange(Mask[i], 0, 4))
3687 if (VT == MVT::v16i16) {
3688 // Upper quadword copied in order.
3689 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3692 // Lower quadword shuffled.
3693 for (unsigned i = 8; i != 12; ++i)
3694 if (!isUndefOrInRange(Mask[i], 8, 12))
3701 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3702 /// is suitable for input to PALIGNR.
3703 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3704 const X86Subtarget *Subtarget) {
3705 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3706 (VT.is256BitVector() && !Subtarget->hasInt256()))
3709 unsigned NumElts = VT.getVectorNumElements();
3710 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3711 unsigned NumLaneElts = NumElts/NumLanes;
3713 // Do not handle 64-bit element shuffles with palignr.
3714 if (NumLaneElts == 2)
3717 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3719 for (i = 0; i != NumLaneElts; ++i) {
3724 // Lane is all undef, go to next lane
3725 if (i == NumLaneElts)
3728 int Start = Mask[i+l];
3730 // Make sure its in this lane in one of the sources
3731 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3732 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3735 // If not lane 0, then we must match lane 0
3736 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3739 // Correct second source to be contiguous with first source
3740 if (Start >= (int)NumElts)
3741 Start -= NumElts - NumLaneElts;
3743 // Make sure we're shifting in the right direction.
3744 if (Start <= (int)(i+l))
3749 // Check the rest of the elements to see if they are consecutive.
3750 for (++i; i != NumLaneElts; ++i) {
3751 int Idx = Mask[i+l];
3753 // Make sure its in this lane
3754 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3755 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3758 // If not lane 0, then we must match lane 0
3759 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3762 if (Idx >= (int)NumElts)
3763 Idx -= NumElts - NumLaneElts;
3765 if (!isUndefOrEqual(Idx, Start+i))
3774 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3775 /// the two vector operands have swapped position.
3776 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3777 unsigned NumElems) {
3778 for (unsigned i = 0; i != NumElems; ++i) {
3782 else if (idx < (int)NumElems)
3783 Mask[i] = idx + NumElems;
3785 Mask[i] = idx - NumElems;
3789 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3790 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3791 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3792 /// reverse of what x86 shuffles want.
3793 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3795 unsigned NumElems = VT.getVectorNumElements();
3796 unsigned NumLanes = VT.getSizeInBits()/128;
3797 unsigned NumLaneElems = NumElems/NumLanes;
3799 if (NumLaneElems != 2 && NumLaneElems != 4)
3802 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3803 bool symetricMaskRequired =
3804 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3806 // VSHUFPSY divides the resulting vector into 4 chunks.
3807 // The sources are also splitted into 4 chunks, and each destination
3808 // chunk must come from a different source chunk.
3810 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3811 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3813 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3814 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3816 // VSHUFPDY divides the resulting vector into 4 chunks.
3817 // The sources are also splitted into 4 chunks, and each destination
3818 // chunk must come from a different source chunk.
3820 // SRC1 => X3 X2 X1 X0
3821 // SRC2 => Y3 Y2 Y1 Y0
3823 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3825 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3826 unsigned HalfLaneElems = NumLaneElems/2;
3827 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3828 for (unsigned i = 0; i != NumLaneElems; ++i) {
3829 int Idx = Mask[i+l];
3830 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3831 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3833 // For VSHUFPSY, the mask of the second half must be the same as the
3834 // first but with the appropriate offsets. This works in the same way as
3835 // VPERMILPS works with masks.
3836 if (!symetricMaskRequired || Idx < 0)
3838 if (MaskVal[i] < 0) {
3839 MaskVal[i] = Idx - l;
3842 if ((signed)(Idx - l) != MaskVal[i])
3850 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3851 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3852 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3853 if (!VT.is128BitVector())
3856 unsigned NumElems = VT.getVectorNumElements();
3861 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3862 return isUndefOrEqual(Mask[0], 6) &&
3863 isUndefOrEqual(Mask[1], 7) &&
3864 isUndefOrEqual(Mask[2], 2) &&
3865 isUndefOrEqual(Mask[3], 3);
3868 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3869 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3871 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3872 if (!VT.is128BitVector())
3875 unsigned NumElems = VT.getVectorNumElements();
3880 return isUndefOrEqual(Mask[0], 2) &&
3881 isUndefOrEqual(Mask[1], 3) &&
3882 isUndefOrEqual(Mask[2], 2) &&
3883 isUndefOrEqual(Mask[3], 3);
3886 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3887 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3888 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3889 if (!VT.is128BitVector())
3892 unsigned NumElems = VT.getVectorNumElements();
3894 if (NumElems != 2 && NumElems != 4)
3897 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3898 if (!isUndefOrEqual(Mask[i], i + NumElems))
3901 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3902 if (!isUndefOrEqual(Mask[i], i))
3908 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3909 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3910 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3911 if (!VT.is128BitVector())
3914 unsigned NumElems = VT.getVectorNumElements();
3916 if (NumElems != 2 && NumElems != 4)
3919 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3920 if (!isUndefOrEqual(Mask[i], i))
3923 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3924 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3931 // Some special combinations that can be optimized.
3934 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3935 SelectionDAG &DAG) {
3936 MVT VT = SVOp->getSimpleValueType(0);
3939 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3942 ArrayRef<int> Mask = SVOp->getMask();
3944 // These are the special masks that may be optimized.
3945 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3946 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3947 bool MatchEvenMask = true;
3948 bool MatchOddMask = true;
3949 for (int i=0; i<8; ++i) {
3950 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3951 MatchEvenMask = false;
3952 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3953 MatchOddMask = false;
3956 if (!MatchEvenMask && !MatchOddMask)
3959 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3961 SDValue Op0 = SVOp->getOperand(0);
3962 SDValue Op1 = SVOp->getOperand(1);
3964 if (MatchEvenMask) {
3965 // Shift the second operand right to 32 bits.
3966 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3967 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3969 // Shift the first operand left to 32 bits.
3970 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3971 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3973 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3974 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3977 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3978 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3979 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3980 bool HasInt256, bool V2IsSplat = false) {
3982 assert(VT.getSizeInBits() >= 128 &&
3983 "Unsupported vector type for unpckl");
3985 // AVX defines UNPCK* to operate independently on 128-bit lanes.
3987 unsigned NumOf256BitLanes;
3988 unsigned NumElts = VT.getVectorNumElements();
3989 if (VT.is256BitVector()) {
3990 if (NumElts != 4 && NumElts != 8 &&
3991 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3994 NumOf256BitLanes = 1;
3995 } else if (VT.is512BitVector()) {
3996 assert(VT.getScalarType().getSizeInBits() >= 32 &&
3997 "Unsupported vector type for unpckh");
3999 NumOf256BitLanes = 2;
4002 NumOf256BitLanes = 1;
4005 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4006 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4008 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4009 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4010 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4011 int BitI = Mask[l256*NumEltsInStride+l+i];
4012 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4013 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4015 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4017 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4025 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4026 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4027 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4028 bool HasInt256, bool V2IsSplat = false) {
4029 assert(VT.getSizeInBits() >= 128 &&
4030 "Unsupported vector type for unpckh");
4032 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4034 unsigned NumOf256BitLanes;
4035 unsigned NumElts = VT.getVectorNumElements();
4036 if (VT.is256BitVector()) {
4037 if (NumElts != 4 && NumElts != 8 &&
4038 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4041 NumOf256BitLanes = 1;
4042 } else if (VT.is512BitVector()) {
4043 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4044 "Unsupported vector type for unpckh");
4046 NumOf256BitLanes = 2;
4049 NumOf256BitLanes = 1;
4052 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4053 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4055 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4056 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4057 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4058 int BitI = Mask[l256*NumEltsInStride+l+i];
4059 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4060 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4062 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4064 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4072 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4073 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4075 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4076 unsigned NumElts = VT.getVectorNumElements();
4077 bool Is256BitVec = VT.is256BitVector();
4079 if (VT.is512BitVector())
4081 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4082 "Unsupported vector type for unpckh");
4084 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4085 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4088 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4089 // FIXME: Need a better way to get rid of this, there's no latency difference
4090 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4091 // the former later. We should also remove the "_undef" special mask.
4092 if (NumElts == 4 && Is256BitVec)
4095 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4096 // independently on 128-bit lanes.
4097 unsigned NumLanes = VT.getSizeInBits()/128;
4098 unsigned NumLaneElts = NumElts/NumLanes;
4100 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4101 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4102 int BitI = Mask[l+i];
4103 int BitI1 = Mask[l+i+1];
4105 if (!isUndefOrEqual(BitI, j))
4107 if (!isUndefOrEqual(BitI1, j))
4115 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4116 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4118 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4119 unsigned NumElts = VT.getVectorNumElements();
4121 if (VT.is512BitVector())
4124 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4125 "Unsupported vector type for unpckh");
4127 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4128 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4131 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4132 // independently on 128-bit lanes.
4133 unsigned NumLanes = VT.getSizeInBits()/128;
4134 unsigned NumLaneElts = NumElts/NumLanes;
4136 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4137 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4138 int BitI = Mask[l+i];
4139 int BitI1 = Mask[l+i+1];
4140 if (!isUndefOrEqual(BitI, j))
4142 if (!isUndefOrEqual(BitI1, j))
4149 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4150 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4151 /// MOVSD, and MOVD, i.e. setting the lowest element.
4152 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4153 if (VT.getVectorElementType().getSizeInBits() < 32)
4155 if (!VT.is128BitVector())
4158 unsigned NumElts = VT.getVectorNumElements();
4160 if (!isUndefOrEqual(Mask[0], NumElts))
4163 for (unsigned i = 1; i != NumElts; ++i)
4164 if (!isUndefOrEqual(Mask[i], i))
4170 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4171 /// as permutations between 128-bit chunks or halves. As an example: this
4173 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4174 /// The first half comes from the second half of V1 and the second half from the
4175 /// the second half of V2.
4176 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4177 if (!HasFp256 || !VT.is256BitVector())
4180 // The shuffle result is divided into half A and half B. In total the two
4181 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4182 // B must come from C, D, E or F.
4183 unsigned HalfSize = VT.getVectorNumElements()/2;
4184 bool MatchA = false, MatchB = false;
4186 // Check if A comes from one of C, D, E, F.
4187 for (unsigned Half = 0; Half != 4; ++Half) {
4188 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4194 // Check if B comes from one of C, D, E, F.
4195 for (unsigned Half = 0; Half != 4; ++Half) {
4196 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4202 return MatchA && MatchB;
4205 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4206 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4207 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4208 MVT VT = SVOp->getSimpleValueType(0);
4210 unsigned HalfSize = VT.getVectorNumElements()/2;
4212 unsigned FstHalf = 0, SndHalf = 0;
4213 for (unsigned i = 0; i < HalfSize; ++i) {
4214 if (SVOp->getMaskElt(i) > 0) {
4215 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4219 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4220 if (SVOp->getMaskElt(i) > 0) {
4221 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4226 return (FstHalf | (SndHalf << 4));
4229 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4230 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4231 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4235 unsigned NumElts = VT.getVectorNumElements();
4237 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4238 for (unsigned i = 0; i != NumElts; ++i) {
4241 Imm8 |= Mask[i] << (i*2);
4246 unsigned LaneSize = 4;
4247 SmallVector<int, 4> MaskVal(LaneSize, -1);
4249 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4250 for (unsigned i = 0; i != LaneSize; ++i) {
4251 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4255 if (MaskVal[i] < 0) {
4256 MaskVal[i] = Mask[i+l] - l;
4257 Imm8 |= MaskVal[i] << (i*2);
4260 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4267 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4268 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4269 /// Note that VPERMIL mask matching is different depending whether theunderlying
4270 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4271 /// to the same elements of the low, but to the higher half of the source.
4272 /// In VPERMILPD the two lanes could be shuffled independently of each other
4273 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4274 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4275 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4276 if (VT.getSizeInBits() < 256 || EltSize < 32)
4278 bool symetricMaskRequired = (EltSize == 32);
4279 unsigned NumElts = VT.getVectorNumElements();
4281 unsigned NumLanes = VT.getSizeInBits()/128;
4282 unsigned LaneSize = NumElts/NumLanes;
4283 // 2 or 4 elements in one lane
4285 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4286 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4287 for (unsigned i = 0; i != LaneSize; ++i) {
4288 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4290 if (symetricMaskRequired) {
4291 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4292 ExpectedMaskVal[i] = Mask[i+l] - l;
4295 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4303 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4304 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4305 /// element of vector 2 and the other elements to come from vector 1 in order.
4306 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4307 bool V2IsSplat = false, bool V2IsUndef = false) {
4308 if (!VT.is128BitVector())
4311 unsigned NumOps = VT.getVectorNumElements();
4312 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4315 if (!isUndefOrEqual(Mask[0], 0))
4318 for (unsigned i = 1; i != NumOps; ++i)
4319 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4320 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4321 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4327 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4328 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4329 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4330 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4331 const X86Subtarget *Subtarget) {
4332 if (!Subtarget->hasSSE3())
4335 unsigned NumElems = VT.getVectorNumElements();
4337 if ((VT.is128BitVector() && NumElems != 4) ||
4338 (VT.is256BitVector() && NumElems != 8) ||
4339 (VT.is512BitVector() && NumElems != 16))
4342 // "i+1" is the value the indexed mask element must have
4343 for (unsigned i = 0; i != NumElems; i += 2)
4344 if (!isUndefOrEqual(Mask[i], i+1) ||
4345 !isUndefOrEqual(Mask[i+1], i+1))
4351 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4352 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4353 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4354 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4355 const X86Subtarget *Subtarget) {
4356 if (!Subtarget->hasSSE3())
4359 unsigned NumElems = VT.getVectorNumElements();
4361 if ((VT.is128BitVector() && NumElems != 4) ||
4362 (VT.is256BitVector() && NumElems != 8) ||
4363 (VT.is512BitVector() && NumElems != 16))
4366 // "i" is the value the indexed mask element must have
4367 for (unsigned i = 0; i != NumElems; i += 2)
4368 if (!isUndefOrEqual(Mask[i], i) ||
4369 !isUndefOrEqual(Mask[i+1], i))
4375 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4376 /// specifies a shuffle of elements that is suitable for input to 256-bit
4377 /// version of MOVDDUP.
4378 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4379 if (!HasFp256 || !VT.is256BitVector())
4382 unsigned NumElts = VT.getVectorNumElements();
4386 for (unsigned i = 0; i != NumElts/2; ++i)
4387 if (!isUndefOrEqual(Mask[i], 0))
4389 for (unsigned i = NumElts/2; i != NumElts; ++i)
4390 if (!isUndefOrEqual(Mask[i], NumElts/2))
4395 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4396 /// specifies a shuffle of elements that is suitable for input to 128-bit
4397 /// version of MOVDDUP.
4398 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4399 if (!VT.is128BitVector())
4402 unsigned e = VT.getVectorNumElements() / 2;
4403 for (unsigned i = 0; i != e; ++i)
4404 if (!isUndefOrEqual(Mask[i], i))
4406 for (unsigned i = 0; i != e; ++i)
4407 if (!isUndefOrEqual(Mask[e+i], i))
4412 /// isVEXTRACTIndex - Return true if the specified
4413 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4414 /// suitable for instruction that extract 128 or 256 bit vectors
4415 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4416 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4417 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4420 // The index should be aligned on a vecWidth-bit boundary.
4422 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4424 MVT VT = N->getSimpleValueType(0);
4425 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4426 bool Result = (Index * ElSize) % vecWidth == 0;
4431 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4432 /// operand specifies a subvector insert that is suitable for input to
4433 /// insertion of 128 or 256-bit subvectors
4434 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4435 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4436 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4438 // The index should be aligned on a vecWidth-bit boundary.
4440 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4442 MVT VT = N->getSimpleValueType(0);
4443 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4444 bool Result = (Index * ElSize) % vecWidth == 0;
4449 bool X86::isVINSERT128Index(SDNode *N) {
4450 return isVINSERTIndex(N, 128);
4453 bool X86::isVINSERT256Index(SDNode *N) {
4454 return isVINSERTIndex(N, 256);
4457 bool X86::isVEXTRACT128Index(SDNode *N) {
4458 return isVEXTRACTIndex(N, 128);
4461 bool X86::isVEXTRACT256Index(SDNode *N) {
4462 return isVEXTRACTIndex(N, 256);
4465 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4466 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4467 /// Handles 128-bit and 256-bit.
4468 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4469 MVT VT = N->getSimpleValueType(0);
4471 assert((VT.getSizeInBits() >= 128) &&
4472 "Unsupported vector type for PSHUF/SHUFP");
4474 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4475 // independently on 128-bit lanes.
4476 unsigned NumElts = VT.getVectorNumElements();
4477 unsigned NumLanes = VT.getSizeInBits()/128;
4478 unsigned NumLaneElts = NumElts/NumLanes;
4480 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4481 "Only supports 2, 4 or 8 elements per lane");
4483 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4485 for (unsigned i = 0; i != NumElts; ++i) {
4486 int Elt = N->getMaskElt(i);
4487 if (Elt < 0) continue;
4488 Elt &= NumLaneElts - 1;
4489 unsigned ShAmt = (i << Shift) % 8;
4490 Mask |= Elt << ShAmt;
4496 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4497 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4498 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4499 MVT VT = N->getSimpleValueType(0);
4501 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4502 "Unsupported vector type for PSHUFHW");
4504 unsigned NumElts = VT.getVectorNumElements();
4507 for (unsigned l = 0; l != NumElts; l += 8) {
4508 // 8 nodes per lane, but we only care about the last 4.
4509 for (unsigned i = 0; i < 4; ++i) {
4510 int Elt = N->getMaskElt(l+i+4);
4511 if (Elt < 0) continue;
4512 Elt &= 0x3; // only 2-bits.
4513 Mask |= Elt << (i * 2);
4520 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4521 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4522 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4523 MVT VT = N->getSimpleValueType(0);
4525 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4526 "Unsupported vector type for PSHUFHW");
4528 unsigned NumElts = VT.getVectorNumElements();
4531 for (unsigned l = 0; l != NumElts; l += 8) {
4532 // 8 nodes per lane, but we only care about the first 4.
4533 for (unsigned i = 0; i < 4; ++i) {
4534 int Elt = N->getMaskElt(l+i);
4535 if (Elt < 0) continue;
4536 Elt &= 0x3; // only 2-bits
4537 Mask |= Elt << (i * 2);
4544 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4545 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4546 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4547 MVT VT = SVOp->getSimpleValueType(0);
4548 unsigned EltSize = VT.is512BitVector() ? 1 :
4549 VT.getVectorElementType().getSizeInBits() >> 3;
4551 unsigned NumElts = VT.getVectorNumElements();
4552 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4553 unsigned NumLaneElts = NumElts/NumLanes;
4557 for (i = 0; i != NumElts; ++i) {
4558 Val = SVOp->getMaskElt(i);
4562 if (Val >= (int)NumElts)
4563 Val -= NumElts - NumLaneElts;
4565 assert(Val - i > 0 && "PALIGNR imm should be positive");
4566 return (Val - i) * EltSize;
4569 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4570 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4571 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4572 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4575 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4577 MVT VecVT = N->getOperand(0).getSimpleValueType();
4578 MVT ElVT = VecVT.getVectorElementType();
4580 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4581 return Index / NumElemsPerChunk;
4584 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4585 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4586 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4587 llvm_unreachable("Illegal insert subvector for VINSERT");
4590 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4592 MVT VecVT = N->getSimpleValueType(0);
4593 MVT ElVT = VecVT.getVectorElementType();
4595 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4596 return Index / NumElemsPerChunk;
4599 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4600 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4601 /// and VINSERTI128 instructions.
4602 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4603 return getExtractVEXTRACTImmediate(N, 128);
4606 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4607 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4608 /// and VINSERTI64x4 instructions.
4609 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4610 return getExtractVEXTRACTImmediate(N, 256);
4613 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4614 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4615 /// and VINSERTI128 instructions.
4616 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4617 return getInsertVINSERTImmediate(N, 128);
4620 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4621 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4622 /// and VINSERTI64x4 instructions.
4623 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4624 return getInsertVINSERTImmediate(N, 256);
4627 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4629 bool X86::isZeroNode(SDValue Elt) {
4630 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4631 return CN->isNullValue();
4632 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4633 return CFP->getValueAPF().isPosZero();
4637 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4638 /// their permute mask.
4639 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4640 SelectionDAG &DAG) {
4641 MVT VT = SVOp->getSimpleValueType(0);
4642 unsigned NumElems = VT.getVectorNumElements();
4643 SmallVector<int, 8> MaskVec;
4645 for (unsigned i = 0; i != NumElems; ++i) {
4646 int Idx = SVOp->getMaskElt(i);
4648 if (Idx < (int)NumElems)
4653 MaskVec.push_back(Idx);
4655 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4656 SVOp->getOperand(0), &MaskVec[0]);
4659 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4660 /// match movhlps. The lower half elements should come from upper half of
4661 /// V1 (and in order), and the upper half elements should come from the upper
4662 /// half of V2 (and in order).
4663 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4664 if (!VT.is128BitVector())
4666 if (VT.getVectorNumElements() != 4)
4668 for (unsigned i = 0, e = 2; i != e; ++i)
4669 if (!isUndefOrEqual(Mask[i], i+2))
4671 for (unsigned i = 2; i != 4; ++i)
4672 if (!isUndefOrEqual(Mask[i], i+4))
4677 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4678 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4680 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4681 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4683 N = N->getOperand(0).getNode();
4684 if (!ISD::isNON_EXTLoad(N))
4687 *LD = cast<LoadSDNode>(N);
4691 // Test whether the given value is a vector value which will be legalized
4693 static bool WillBeConstantPoolLoad(SDNode *N) {
4694 if (N->getOpcode() != ISD::BUILD_VECTOR)
4697 // Check for any non-constant elements.
4698 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4699 switch (N->getOperand(i).getNode()->getOpcode()) {
4701 case ISD::ConstantFP:
4708 // Vectors of all-zeros and all-ones are materialized with special
4709 // instructions rather than being loaded.
4710 return !ISD::isBuildVectorAllZeros(N) &&
4711 !ISD::isBuildVectorAllOnes(N);
4714 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4715 /// match movlp{s|d}. The lower half elements should come from lower half of
4716 /// V1 (and in order), and the upper half elements should come from the upper
4717 /// half of V2 (and in order). And since V1 will become the source of the
4718 /// MOVLP, it must be either a vector load or a scalar load to vector.
4719 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4720 ArrayRef<int> Mask, MVT VT) {
4721 if (!VT.is128BitVector())
4724 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4726 // Is V2 is a vector load, don't do this transformation. We will try to use
4727 // load folding shufps op.
4728 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4731 unsigned NumElems = VT.getVectorNumElements();
4733 if (NumElems != 2 && NumElems != 4)
4735 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4736 if (!isUndefOrEqual(Mask[i], i))
4738 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4739 if (!isUndefOrEqual(Mask[i], i+NumElems))
4744 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4746 static bool isSplatVector(SDNode *N) {
4747 if (N->getOpcode() != ISD::BUILD_VECTOR)
4750 SDValue SplatValue = N->getOperand(0);
4751 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4752 if (N->getOperand(i) != SplatValue)
4757 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4758 /// to an zero vector.
4759 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4760 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4761 SDValue V1 = N->getOperand(0);
4762 SDValue V2 = N->getOperand(1);
4763 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4764 for (unsigned i = 0; i != NumElems; ++i) {
4765 int Idx = N->getMaskElt(i);
4766 if (Idx >= (int)NumElems) {
4767 unsigned Opc = V2.getOpcode();
4768 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4770 if (Opc != ISD::BUILD_VECTOR ||
4771 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4773 } else if (Idx >= 0) {
4774 unsigned Opc = V1.getOpcode();
4775 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4777 if (Opc != ISD::BUILD_VECTOR ||
4778 !X86::isZeroNode(V1.getOperand(Idx)))
4785 /// getZeroVector - Returns a vector of specified type with all zero elements.
4787 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4788 SelectionDAG &DAG, SDLoc dl) {
4789 assert(VT.isVector() && "Expected a vector type");
4791 // Always build SSE zero vectors as <4 x i32> bitcasted
4792 // to their dest type. This ensures they get CSE'd.
4794 if (VT.is128BitVector()) { // SSE
4795 if (Subtarget->hasSSE2()) { // SSE2
4796 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4797 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4799 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4800 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4802 } else if (VT.is256BitVector()) { // AVX
4803 if (Subtarget->hasInt256()) { // AVX2
4804 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4805 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4806 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4807 array_lengthof(Ops));
4809 // 256-bit logic and arithmetic instructions in AVX are all
4810 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4811 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4812 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4813 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4814 array_lengthof(Ops));
4816 } else if (VT.is512BitVector()) { // AVX-512
4817 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4818 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4819 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4820 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4821 } else if (VT.getScalarType() == MVT::i1) {
4822 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4823 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4824 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4825 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4826 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4827 Ops, VT.getVectorNumElements());
4829 llvm_unreachable("Unexpected vector type");
4831 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4834 /// getOnesVector - Returns a vector of specified type with all bits set.
4835 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4836 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4837 /// Then bitcast to their original type, ensuring they get CSE'd.
4838 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4840 assert(VT.isVector() && "Expected a vector type");
4842 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4844 if (VT.is256BitVector()) {
4845 if (HasInt256) { // AVX2
4846 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4847 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4848 array_lengthof(Ops));
4850 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4851 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4853 } else if (VT.is128BitVector()) {
4854 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4856 llvm_unreachable("Unexpected vector type");
4858 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4861 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4862 /// that point to V2 points to its first element.
4863 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4864 for (unsigned i = 0; i != NumElems; ++i) {
4865 if (Mask[i] > (int)NumElems) {
4871 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4872 /// operation of specified width.
4873 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4875 unsigned NumElems = VT.getVectorNumElements();
4876 SmallVector<int, 8> Mask;
4877 Mask.push_back(NumElems);
4878 for (unsigned i = 1; i != NumElems; ++i)
4880 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4883 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4884 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4886 unsigned NumElems = VT.getVectorNumElements();
4887 SmallVector<int, 8> Mask;
4888 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4890 Mask.push_back(i + NumElems);
4892 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4895 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4896 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4898 unsigned NumElems = VT.getVectorNumElements();
4899 SmallVector<int, 8> Mask;
4900 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4901 Mask.push_back(i + Half);
4902 Mask.push_back(i + NumElems + Half);
4904 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4907 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4908 // a generic shuffle instruction because the target has no such instructions.
4909 // Generate shuffles which repeat i16 and i8 several times until they can be
4910 // represented by v4f32 and then be manipulated by target suported shuffles.
4911 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4912 MVT VT = V.getSimpleValueType();
4913 int NumElems = VT.getVectorNumElements();
4916 while (NumElems > 4) {
4917 if (EltNo < NumElems/2) {
4918 V = getUnpackl(DAG, dl, VT, V, V);
4920 V = getUnpackh(DAG, dl, VT, V, V);
4921 EltNo -= NumElems/2;
4928 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4929 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4930 MVT VT = V.getSimpleValueType();
4933 if (VT.is128BitVector()) {
4934 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4935 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4936 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4938 } else if (VT.is256BitVector()) {
4939 // To use VPERMILPS to splat scalars, the second half of indicies must
4940 // refer to the higher part, which is a duplication of the lower one,
4941 // because VPERMILPS can only handle in-lane permutations.
4942 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4943 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4945 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4946 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4949 llvm_unreachable("Vector size not supported");
4951 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4954 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4955 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4956 MVT SrcVT = SV->getSimpleValueType(0);
4957 SDValue V1 = SV->getOperand(0);
4960 int EltNo = SV->getSplatIndex();
4961 int NumElems = SrcVT.getVectorNumElements();
4962 bool Is256BitVec = SrcVT.is256BitVector();
4964 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4965 "Unknown how to promote splat for type");
4967 // Extract the 128-bit part containing the splat element and update
4968 // the splat element index when it refers to the higher register.
4970 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4971 if (EltNo >= NumElems/2)
4972 EltNo -= NumElems/2;
4975 // All i16 and i8 vector types can't be used directly by a generic shuffle
4976 // instruction because the target has no such instruction. Generate shuffles
4977 // which repeat i16 and i8 several times until they fit in i32, and then can
4978 // be manipulated by target suported shuffles.
4979 MVT EltVT = SrcVT.getVectorElementType();
4980 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4981 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4983 // Recreate the 256-bit vector and place the same 128-bit vector
4984 // into the low and high part. This is necessary because we want
4985 // to use VPERM* to shuffle the vectors
4987 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4990 return getLegalSplat(DAG, V1, EltNo);
4993 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4994 /// vector of zero or undef vector. This produces a shuffle where the low
4995 /// element of V2 is swizzled into the zero/undef vector, landing at element
4996 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4997 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4999 const X86Subtarget *Subtarget,
5000 SelectionDAG &DAG) {
5001 MVT VT = V2.getSimpleValueType();
5003 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5004 unsigned NumElems = VT.getVectorNumElements();
5005 SmallVector<int, 16> MaskVec;
5006 for (unsigned i = 0; i != NumElems; ++i)
5007 // If this is the insertion idx, put the low elt of V2 here.
5008 MaskVec.push_back(i == Idx ? NumElems : i);
5009 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5012 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5013 /// target specific opcode. Returns true if the Mask could be calculated.
5014 /// Sets IsUnary to true if only uses one source.
5015 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5016 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5017 unsigned NumElems = VT.getVectorNumElements();
5021 switch(N->getOpcode()) {
5023 ImmN = N->getOperand(N->getNumOperands()-1);
5024 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5026 case X86ISD::UNPCKH:
5027 DecodeUNPCKHMask(VT, Mask);
5029 case X86ISD::UNPCKL:
5030 DecodeUNPCKLMask(VT, Mask);
5032 case X86ISD::MOVHLPS:
5033 DecodeMOVHLPSMask(NumElems, Mask);
5035 case X86ISD::MOVLHPS:
5036 DecodeMOVLHPSMask(NumElems, Mask);
5038 case X86ISD::PALIGNR:
5039 ImmN = N->getOperand(N->getNumOperands()-1);
5040 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5042 case X86ISD::PSHUFD:
5043 case X86ISD::VPERMILP:
5044 ImmN = N->getOperand(N->getNumOperands()-1);
5045 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5048 case X86ISD::PSHUFHW:
5049 ImmN = N->getOperand(N->getNumOperands()-1);
5050 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5053 case X86ISD::PSHUFLW:
5054 ImmN = N->getOperand(N->getNumOperands()-1);
5055 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5058 case X86ISD::VPERMI:
5059 ImmN = N->getOperand(N->getNumOperands()-1);
5060 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5064 case X86ISD::MOVSD: {
5065 // The index 0 always comes from the first element of the second source,
5066 // this is why MOVSS and MOVSD are used in the first place. The other
5067 // elements come from the other positions of the first source vector
5068 Mask.push_back(NumElems);
5069 for (unsigned i = 1; i != NumElems; ++i) {
5074 case X86ISD::VPERM2X128:
5075 ImmN = N->getOperand(N->getNumOperands()-1);
5076 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5077 if (Mask.empty()) return false;
5079 case X86ISD::MOVDDUP:
5080 case X86ISD::MOVLHPD:
5081 case X86ISD::MOVLPD:
5082 case X86ISD::MOVLPS:
5083 case X86ISD::MOVSHDUP:
5084 case X86ISD::MOVSLDUP:
5085 // Not yet implemented
5087 default: llvm_unreachable("unknown target shuffle node");
5093 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5094 /// element of the result of the vector shuffle.
5095 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5098 return SDValue(); // Limit search depth.
5100 SDValue V = SDValue(N, 0);
5101 EVT VT = V.getValueType();
5102 unsigned Opcode = V.getOpcode();
5104 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5105 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5106 int Elt = SV->getMaskElt(Index);
5109 return DAG.getUNDEF(VT.getVectorElementType());
5111 unsigned NumElems = VT.getVectorNumElements();
5112 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5113 : SV->getOperand(1);
5114 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5117 // Recurse into target specific vector shuffles to find scalars.
5118 if (isTargetShuffle(Opcode)) {
5119 MVT ShufVT = V.getSimpleValueType();
5120 unsigned NumElems = ShufVT.getVectorNumElements();
5121 SmallVector<int, 16> ShuffleMask;
5124 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5127 int Elt = ShuffleMask[Index];
5129 return DAG.getUNDEF(ShufVT.getVectorElementType());
5131 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5133 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5137 // Actual nodes that may contain scalar elements
5138 if (Opcode == ISD::BITCAST) {
5139 V = V.getOperand(0);
5140 EVT SrcVT = V.getValueType();
5141 unsigned NumElems = VT.getVectorNumElements();
5143 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5147 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5148 return (Index == 0) ? V.getOperand(0)
5149 : DAG.getUNDEF(VT.getVectorElementType());
5151 if (V.getOpcode() == ISD::BUILD_VECTOR)
5152 return V.getOperand(Index);
5157 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5158 /// shuffle operation which come from a consecutively from a zero. The
5159 /// search can start in two different directions, from left or right.
5160 /// We count undefs as zeros until PreferredNum is reached.
5161 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5162 unsigned NumElems, bool ZerosFromLeft,
5164 unsigned PreferredNum = -1U) {
5165 unsigned NumZeros = 0;
5166 for (unsigned i = 0; i != NumElems; ++i) {
5167 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5168 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5172 if (X86::isZeroNode(Elt))
5174 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5175 NumZeros = std::min(NumZeros + 1, PreferredNum);
5183 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5184 /// correspond consecutively to elements from one of the vector operands,
5185 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5187 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5188 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5189 unsigned NumElems, unsigned &OpNum) {
5190 bool SeenV1 = false;
5191 bool SeenV2 = false;
5193 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5194 int Idx = SVOp->getMaskElt(i);
5195 // Ignore undef indicies
5199 if (Idx < (int)NumElems)
5204 // Only accept consecutive elements from the same vector
5205 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5209 OpNum = SeenV1 ? 0 : 1;
5213 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5214 /// logical left shift of a vector.
5215 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5216 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5218 SVOp->getSimpleValueType(0).getVectorNumElements();
5219 unsigned NumZeros = getNumOfConsecutiveZeros(
5220 SVOp, NumElems, false /* check zeros from right */, DAG,
5221 SVOp->getMaskElt(0));
5227 // Considering the elements in the mask that are not consecutive zeros,
5228 // check if they consecutively come from only one of the source vectors.
5230 // V1 = {X, A, B, C} 0
5232 // vector_shuffle V1, V2 <1, 2, 3, X>
5234 if (!isShuffleMaskConsecutive(SVOp,
5235 0, // Mask Start Index
5236 NumElems-NumZeros, // Mask End Index(exclusive)
5237 NumZeros, // Where to start looking in the src vector
5238 NumElems, // Number of elements in vector
5239 OpSrc)) // Which source operand ?
5244 ShVal = SVOp->getOperand(OpSrc);
5248 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5249 /// logical left shift of a vector.
5250 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5251 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5253 SVOp->getSimpleValueType(0).getVectorNumElements();
5254 unsigned NumZeros = getNumOfConsecutiveZeros(
5255 SVOp, NumElems, true /* check zeros from left */, DAG,
5256 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5262 // Considering the elements in the mask that are not consecutive zeros,
5263 // check if they consecutively come from only one of the source vectors.
5265 // 0 { A, B, X, X } = V2
5267 // vector_shuffle V1, V2 <X, X, 4, 5>
5269 if (!isShuffleMaskConsecutive(SVOp,
5270 NumZeros, // Mask Start Index
5271 NumElems, // Mask End Index(exclusive)
5272 0, // Where to start looking in the src vector
5273 NumElems, // Number of elements in vector
5274 OpSrc)) // Which source operand ?
5279 ShVal = SVOp->getOperand(OpSrc);
5283 /// isVectorShift - Returns true if the shuffle can be implemented as a
5284 /// logical left or right shift of a vector.
5285 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5286 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5287 // Although the logic below support any bitwidth size, there are no
5288 // shift instructions which handle more than 128-bit vectors.
5289 if (!SVOp->getSimpleValueType(0).is128BitVector())
5292 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5293 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5299 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5301 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5302 unsigned NumNonZero, unsigned NumZero,
5304 const X86Subtarget* Subtarget,
5305 const TargetLowering &TLI) {
5312 for (unsigned i = 0; i < 16; ++i) {
5313 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5314 if (ThisIsNonZero && First) {
5316 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5318 V = DAG.getUNDEF(MVT::v8i16);
5323 SDValue ThisElt(0, 0), LastElt(0, 0);
5324 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5325 if (LastIsNonZero) {
5326 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5327 MVT::i16, Op.getOperand(i-1));
5329 if (ThisIsNonZero) {
5330 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5331 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5332 ThisElt, DAG.getConstant(8, MVT::i8));
5334 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5338 if (ThisElt.getNode())
5339 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5340 DAG.getIntPtrConstant(i/2));
5344 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5347 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5349 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5350 unsigned NumNonZero, unsigned NumZero,
5352 const X86Subtarget* Subtarget,
5353 const TargetLowering &TLI) {
5360 for (unsigned i = 0; i < 8; ++i) {
5361 bool isNonZero = (NonZeros & (1 << i)) != 0;
5365 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5367 V = DAG.getUNDEF(MVT::v8i16);
5370 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5371 MVT::v8i16, V, Op.getOperand(i),
5372 DAG.getIntPtrConstant(i));
5379 /// getVShift - Return a vector logical shift node.
5381 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5382 unsigned NumBits, SelectionDAG &DAG,
5383 const TargetLowering &TLI, SDLoc dl) {
5384 assert(VT.is128BitVector() && "Unknown type for VShift");
5385 EVT ShVT = MVT::v2i64;
5386 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5387 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5388 return DAG.getNode(ISD::BITCAST, dl, VT,
5389 DAG.getNode(Opc, dl, ShVT, SrcOp,
5390 DAG.getConstant(NumBits,
5391 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5395 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5397 // Check if the scalar load can be widened into a vector load. And if
5398 // the address is "base + cst" see if the cst can be "absorbed" into
5399 // the shuffle mask.
5400 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5401 SDValue Ptr = LD->getBasePtr();
5402 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5404 EVT PVT = LD->getValueType(0);
5405 if (PVT != MVT::i32 && PVT != MVT::f32)
5410 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5411 FI = FINode->getIndex();
5413 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5414 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5415 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5416 Offset = Ptr.getConstantOperandVal(1);
5417 Ptr = Ptr.getOperand(0);
5422 // FIXME: 256-bit vector instructions don't require a strict alignment,
5423 // improve this code to support it better.
5424 unsigned RequiredAlign = VT.getSizeInBits()/8;
5425 SDValue Chain = LD->getChain();
5426 // Make sure the stack object alignment is at least 16 or 32.
5427 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5428 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5429 if (MFI->isFixedObjectIndex(FI)) {
5430 // Can't change the alignment. FIXME: It's possible to compute
5431 // the exact stack offset and reference FI + adjust offset instead.
5432 // If someone *really* cares about this. That's the way to implement it.
5435 MFI->setObjectAlignment(FI, RequiredAlign);
5439 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5440 // Ptr + (Offset & ~15).
5443 if ((Offset % RequiredAlign) & 3)
5445 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5447 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5448 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5450 int EltNo = (Offset - StartOffset) >> 2;
5451 unsigned NumElems = VT.getVectorNumElements();
5453 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5454 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5455 LD->getPointerInfo().getWithOffset(StartOffset),
5456 false, false, false, 0);
5458 SmallVector<int, 8> Mask;
5459 for (unsigned i = 0; i != NumElems; ++i)
5460 Mask.push_back(EltNo);
5462 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5468 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5469 /// vector of type 'VT', see if the elements can be replaced by a single large
5470 /// load which has the same value as a build_vector whose operands are 'elts'.
5472 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5474 /// FIXME: we'd also like to handle the case where the last elements are zero
5475 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5476 /// There's even a handy isZeroNode for that purpose.
5477 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5478 SDLoc &DL, SelectionDAG &DAG,
5479 bool isAfterLegalize) {
5480 EVT EltVT = VT.getVectorElementType();
5481 unsigned NumElems = Elts.size();
5483 LoadSDNode *LDBase = NULL;
5484 unsigned LastLoadedElt = -1U;
5486 // For each element in the initializer, see if we've found a load or an undef.
5487 // If we don't find an initial load element, or later load elements are
5488 // non-consecutive, bail out.
5489 for (unsigned i = 0; i < NumElems; ++i) {
5490 SDValue Elt = Elts[i];
5492 if (!Elt.getNode() ||
5493 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5496 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5498 LDBase = cast<LoadSDNode>(Elt.getNode());
5502 if (Elt.getOpcode() == ISD::UNDEF)
5505 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5506 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5511 // If we have found an entire vector of loads and undefs, then return a large
5512 // load of the entire vector width starting at the base pointer. If we found
5513 // consecutive loads for the low half, generate a vzext_load node.
5514 if (LastLoadedElt == NumElems - 1) {
5516 if (isAfterLegalize &&
5517 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5520 SDValue NewLd = SDValue();
5522 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5523 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5524 LDBase->getPointerInfo(),
5525 LDBase->isVolatile(), LDBase->isNonTemporal(),
5526 LDBase->isInvariant(), 0);
5527 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5528 LDBase->getPointerInfo(),
5529 LDBase->isVolatile(), LDBase->isNonTemporal(),
5530 LDBase->isInvariant(), LDBase->getAlignment());
5532 if (LDBase->hasAnyUseOfValue(1)) {
5533 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5535 SDValue(NewLd.getNode(), 1));
5536 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5537 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5538 SDValue(NewLd.getNode(), 1));
5543 if (NumElems == 4 && LastLoadedElt == 1 &&
5544 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5545 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5546 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5548 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5549 array_lengthof(Ops), MVT::i64,
5550 LDBase->getPointerInfo(),
5551 LDBase->getAlignment(),
5552 false/*isVolatile*/, true/*ReadMem*/,
5555 // Make sure the newly-created LOAD is in the same position as LDBase in
5556 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5557 // update uses of LDBase's output chain to use the TokenFactor.
5558 if (LDBase->hasAnyUseOfValue(1)) {
5559 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5560 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5561 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5562 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5563 SDValue(ResNode.getNode(), 1));
5566 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5571 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5572 /// to generate a splat value for the following cases:
5573 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5574 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5575 /// a scalar load, or a constant.
5576 /// The VBROADCAST node is returned when a pattern is found,
5577 /// or SDValue() otherwise.
5578 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5579 SelectionDAG &DAG) {
5580 if (!Subtarget->hasFp256())
5583 MVT VT = Op.getSimpleValueType();
5586 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5587 "Unsupported vector type for broadcast.");
5592 switch (Op.getOpcode()) {
5594 // Unknown pattern found.
5597 case ISD::BUILD_VECTOR: {
5598 // The BUILD_VECTOR node must be a splat.
5599 if (!isSplatVector(Op.getNode()))
5602 Ld = Op.getOperand(0);
5603 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5604 Ld.getOpcode() == ISD::ConstantFP);
5606 // The suspected load node has several users. Make sure that all
5607 // of its users are from the BUILD_VECTOR node.
5608 // Constants may have multiple users.
5609 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5614 case ISD::VECTOR_SHUFFLE: {
5615 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5617 // Shuffles must have a splat mask where the first element is
5619 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5622 SDValue Sc = Op.getOperand(0);
5623 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5624 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5626 if (!Subtarget->hasInt256())
5629 // Use the register form of the broadcast instruction available on AVX2.
5630 if (VT.getSizeInBits() >= 256)
5631 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5632 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5635 Ld = Sc.getOperand(0);
5636 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5637 Ld.getOpcode() == ISD::ConstantFP);
5639 // The scalar_to_vector node and the suspected
5640 // load node must have exactly one user.
5641 // Constants may have multiple users.
5643 // AVX-512 has register version of the broadcast
5644 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5645 Ld.getValueType().getSizeInBits() >= 32;
5646 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5653 bool IsGE256 = (VT.getSizeInBits() >= 256);
5655 // Handle the broadcasting a single constant scalar from the constant pool
5656 // into a vector. On Sandybridge it is still better to load a constant vector
5657 // from the constant pool and not to broadcast it from a scalar.
5658 if (ConstSplatVal && Subtarget->hasInt256()) {
5659 EVT CVT = Ld.getValueType();
5660 assert(!CVT.isVector() && "Must not broadcast a vector type");
5661 unsigned ScalarSize = CVT.getSizeInBits();
5663 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5664 const Constant *C = 0;
5665 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5666 C = CI->getConstantIntValue();
5667 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5668 C = CF->getConstantFPValue();
5670 assert(C && "Invalid constant type");
5672 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5673 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5674 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5675 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5676 MachinePointerInfo::getConstantPool(),
5677 false, false, false, Alignment);
5679 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5683 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5684 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5686 // Handle AVX2 in-register broadcasts.
5687 if (!IsLoad && Subtarget->hasInt256() &&
5688 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5689 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5691 // The scalar source must be a normal load.
5695 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5696 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5698 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5699 // double since there is no vbroadcastsd xmm
5700 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5701 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5702 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5705 // Unsupported broadcast.
5709 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5710 MVT VT = Op.getSimpleValueType();
5712 // Skip if insert_vec_elt is not supported.
5713 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5714 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5718 unsigned NumElems = Op.getNumOperands();
5722 SmallVector<unsigned, 4> InsertIndices;
5723 SmallVector<int, 8> Mask(NumElems, -1);
5725 for (unsigned i = 0; i != NumElems; ++i) {
5726 unsigned Opc = Op.getOperand(i).getOpcode();
5728 if (Opc == ISD::UNDEF)
5731 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5732 // Quit if more than 1 elements need inserting.
5733 if (InsertIndices.size() > 1)
5736 InsertIndices.push_back(i);
5740 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5741 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5743 // Quit if extracted from vector of different type.
5744 if (ExtractedFromVec.getValueType() != VT)
5747 // Quit if non-constant index.
5748 if (!isa<ConstantSDNode>(ExtIdx))
5751 if (VecIn1.getNode() == 0)
5752 VecIn1 = ExtractedFromVec;
5753 else if (VecIn1 != ExtractedFromVec) {
5754 if (VecIn2.getNode() == 0)
5755 VecIn2 = ExtractedFromVec;
5756 else if (VecIn2 != ExtractedFromVec)
5757 // Quit if more than 2 vectors to shuffle
5761 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5763 if (ExtractedFromVec == VecIn1)
5765 else if (ExtractedFromVec == VecIn2)
5766 Mask[i] = Idx + NumElems;
5769 if (VecIn1.getNode() == 0)
5772 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5773 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5774 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5775 unsigned Idx = InsertIndices[i];
5776 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5777 DAG.getIntPtrConstant(Idx));
5783 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5785 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5787 MVT VT = Op.getSimpleValueType();
5788 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5789 "Unexpected type in LowerBUILD_VECTORvXi1!");
5792 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5793 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5794 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5795 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5796 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5797 Ops, VT.getVectorNumElements());
5800 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5801 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5802 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5803 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5804 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5805 Ops, VT.getVectorNumElements());
5808 bool AllContants = true;
5809 uint64_t Immediate = 0;
5810 int NonConstIdx = -1;
5811 bool IsSplat = true;
5812 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5813 SDValue In = Op.getOperand(idx);
5814 if (In.getOpcode() == ISD::UNDEF)
5816 if (!isa<ConstantSDNode>(In)) {
5817 AllContants = false;
5820 else if (cast<ConstantSDNode>(In)->getZExtValue())
5821 Immediate |= (1ULL << idx);
5822 if (In != Op.getOperand(0))
5827 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5828 DAG.getConstant(Immediate, MVT::i16));
5829 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5830 DAG.getIntPtrConstant(0));
5833 if (!IsSplat && (NonConstIdx != 0))
5834 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5835 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5838 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5839 DAG.getConstant(-1, SelectVT),
5840 DAG.getConstant(0, SelectVT));
5842 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5843 DAG.getConstant((Immediate | 1), SelectVT),
5844 DAG.getConstant(Immediate, SelectVT));
5845 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5849 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5852 MVT VT = Op.getSimpleValueType();
5853 MVT ExtVT = VT.getVectorElementType();
5854 unsigned NumElems = Op.getNumOperands();
5856 // Generate vectors for predicate vectors.
5857 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5858 return LowerBUILD_VECTORvXi1(Op, DAG);
5860 // Vectors containing all zeros can be matched by pxor and xorps later
5861 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5862 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5863 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5864 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5867 return getZeroVector(VT, Subtarget, DAG, dl);
5870 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5871 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5872 // vpcmpeqd on 256-bit vectors.
5873 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5874 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5877 if (!VT.is512BitVector())
5878 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5881 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5882 if (Broadcast.getNode())
5885 unsigned EVTBits = ExtVT.getSizeInBits();
5887 unsigned NumZero = 0;
5888 unsigned NumNonZero = 0;
5889 unsigned NonZeros = 0;
5890 bool IsAllConstants = true;
5891 SmallSet<SDValue, 8> Values;
5892 for (unsigned i = 0; i < NumElems; ++i) {
5893 SDValue Elt = Op.getOperand(i);
5894 if (Elt.getOpcode() == ISD::UNDEF)
5897 if (Elt.getOpcode() != ISD::Constant &&
5898 Elt.getOpcode() != ISD::ConstantFP)
5899 IsAllConstants = false;
5900 if (X86::isZeroNode(Elt))
5903 NonZeros |= (1 << i);
5908 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5909 if (NumNonZero == 0)
5910 return DAG.getUNDEF(VT);
5912 // Special case for single non-zero, non-undef, element.
5913 if (NumNonZero == 1) {
5914 unsigned Idx = countTrailingZeros(NonZeros);
5915 SDValue Item = Op.getOperand(Idx);
5917 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5918 // the value are obviously zero, truncate the value to i32 and do the
5919 // insertion that way. Only do this if the value is non-constant or if the
5920 // value is a constant being inserted into element 0. It is cheaper to do
5921 // a constant pool load than it is to do a movd + shuffle.
5922 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5923 (!IsAllConstants || Idx == 0)) {
5924 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5926 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5927 EVT VecVT = MVT::v4i32;
5928 unsigned VecElts = 4;
5930 // Truncate the value (which may itself be a constant) to i32, and
5931 // convert it to a vector with movd (S2V+shuffle to zero extend).
5932 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5933 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5934 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5936 // Now we have our 32-bit value zero extended in the low element of
5937 // a vector. If Idx != 0, swizzle it into place.
5939 SmallVector<int, 4> Mask;
5940 Mask.push_back(Idx);
5941 for (unsigned i = 1; i != VecElts; ++i)
5943 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5946 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5950 // If we have a constant or non-constant insertion into the low element of
5951 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5952 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5953 // depending on what the source datatype is.
5956 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5958 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5959 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5960 if (VT.is256BitVector() || VT.is512BitVector()) {
5961 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5962 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5963 Item, DAG.getIntPtrConstant(0));
5965 assert(VT.is128BitVector() && "Expected an SSE value type!");
5966 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5967 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5968 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5971 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5972 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5973 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5974 if (VT.is256BitVector()) {
5975 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5976 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5978 assert(VT.is128BitVector() && "Expected an SSE value type!");
5979 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5981 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5985 // Is it a vector logical left shift?
5986 if (NumElems == 2 && Idx == 1 &&
5987 X86::isZeroNode(Op.getOperand(0)) &&
5988 !X86::isZeroNode(Op.getOperand(1))) {
5989 unsigned NumBits = VT.getSizeInBits();
5990 return getVShift(true, VT,
5991 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5992 VT, Op.getOperand(1)),
5993 NumBits/2, DAG, *this, dl);
5996 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5999 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6000 // is a non-constant being inserted into an element other than the low one,
6001 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6002 // movd/movss) to move this into the low element, then shuffle it into
6004 if (EVTBits == 32) {
6005 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6007 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6008 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6009 SmallVector<int, 8> MaskVec;
6010 for (unsigned i = 0; i != NumElems; ++i)
6011 MaskVec.push_back(i == Idx ? 0 : 1);
6012 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6016 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6017 if (Values.size() == 1) {
6018 if (EVTBits == 32) {
6019 // Instead of a shuffle like this:
6020 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6021 // Check if it's possible to issue this instead.
6022 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6023 unsigned Idx = countTrailingZeros(NonZeros);
6024 SDValue Item = Op.getOperand(Idx);
6025 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6026 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6031 // A vector full of immediates; various special cases are already
6032 // handled, so this is best done with a single constant-pool load.
6036 // For AVX-length vectors, build the individual 128-bit pieces and use
6037 // shuffles to put them in place.
6038 if (VT.is256BitVector() || VT.is512BitVector()) {
6039 SmallVector<SDValue, 64> V;
6040 for (unsigned i = 0; i != NumElems; ++i)
6041 V.push_back(Op.getOperand(i));
6043 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6045 // Build both the lower and upper subvector.
6046 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6047 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6050 // Recreate the wider vector with the lower and upper part.
6051 if (VT.is256BitVector())
6052 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6053 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6056 // Let legalizer expand 2-wide build_vectors.
6057 if (EVTBits == 64) {
6058 if (NumNonZero == 1) {
6059 // One half is zero or undef.
6060 unsigned Idx = countTrailingZeros(NonZeros);
6061 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6062 Op.getOperand(Idx));
6063 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6068 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6069 if (EVTBits == 8 && NumElems == 16) {
6070 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6072 if (V.getNode()) return V;
6075 if (EVTBits == 16 && NumElems == 8) {
6076 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6078 if (V.getNode()) return V;
6081 // If element VT is == 32 bits, turn it into a number of shuffles.
6082 SmallVector<SDValue, 8> V(NumElems);
6083 if (NumElems == 4 && NumZero > 0) {
6084 for (unsigned i = 0; i < 4; ++i) {
6085 bool isZero = !(NonZeros & (1 << i));
6087 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6089 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6092 for (unsigned i = 0; i < 2; ++i) {
6093 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6096 V[i] = V[i*2]; // Must be a zero vector.
6099 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6102 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6105 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6110 bool Reverse1 = (NonZeros & 0x3) == 2;
6111 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6115 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6116 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6118 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6121 if (Values.size() > 1 && VT.is128BitVector()) {
6122 // Check for a build vector of consecutive loads.
6123 for (unsigned i = 0; i < NumElems; ++i)
6124 V[i] = Op.getOperand(i);
6126 // Check for elements which are consecutive loads.
6127 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6131 // Check for a build vector from mostly shuffle plus few inserting.
6132 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6136 // For SSE 4.1, use insertps to put the high elements into the low element.
6137 if (getSubtarget()->hasSSE41()) {
6139 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6140 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6142 Result = DAG.getUNDEF(VT);
6144 for (unsigned i = 1; i < NumElems; ++i) {
6145 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6146 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6147 Op.getOperand(i), DAG.getIntPtrConstant(i));
6152 // Otherwise, expand into a number of unpckl*, start by extending each of
6153 // our (non-undef) elements to the full vector width with the element in the
6154 // bottom slot of the vector (which generates no code for SSE).
6155 for (unsigned i = 0; i < NumElems; ++i) {
6156 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6157 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6159 V[i] = DAG.getUNDEF(VT);
6162 // Next, we iteratively mix elements, e.g. for v4f32:
6163 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6164 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6165 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6166 unsigned EltStride = NumElems >> 1;
6167 while (EltStride != 0) {
6168 for (unsigned i = 0; i < EltStride; ++i) {
6169 // If V[i+EltStride] is undef and this is the first round of mixing,
6170 // then it is safe to just drop this shuffle: V[i] is already in the
6171 // right place, the one element (since it's the first round) being
6172 // inserted as undef can be dropped. This isn't safe for successive
6173 // rounds because they will permute elements within both vectors.
6174 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6175 EltStride == NumElems/2)
6178 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6187 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6188 // to create 256-bit vectors from two other 128-bit ones.
6189 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6191 MVT ResVT = Op.getSimpleValueType();
6193 assert((ResVT.is256BitVector() ||
6194 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6196 SDValue V1 = Op.getOperand(0);
6197 SDValue V2 = Op.getOperand(1);
6198 unsigned NumElems = ResVT.getVectorNumElements();
6199 if(ResVT.is256BitVector())
6200 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6202 if (Op.getNumOperands() == 4) {
6203 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6204 ResVT.getVectorNumElements()/2);
6205 SDValue V3 = Op.getOperand(2);
6206 SDValue V4 = Op.getOperand(3);
6207 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6208 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6210 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6213 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6214 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6215 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6216 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6217 Op.getNumOperands() == 4)));
6219 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6220 // from two other 128-bit ones.
6222 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6223 return LowerAVXCONCAT_VECTORS(Op, DAG);
6226 // Try to lower a shuffle node into a simple blend instruction.
6228 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6229 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6230 SDValue V1 = SVOp->getOperand(0);
6231 SDValue V2 = SVOp->getOperand(1);
6233 MVT VT = SVOp->getSimpleValueType(0);
6234 MVT EltVT = VT.getVectorElementType();
6235 unsigned NumElems = VT.getVectorNumElements();
6237 // There is no blend with immediate in AVX-512.
6238 if (VT.is512BitVector())
6241 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6243 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6246 // Check the mask for BLEND and build the value.
6247 unsigned MaskValue = 0;
6248 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6249 unsigned NumLanes = (NumElems-1)/8 + 1;
6250 unsigned NumElemsInLane = NumElems / NumLanes;
6252 // Blend for v16i16 should be symetric for the both lanes.
6253 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6255 int SndLaneEltIdx = (NumLanes == 2) ?
6256 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6257 int EltIdx = SVOp->getMaskElt(i);
6259 if ((EltIdx < 0 || EltIdx == (int)i) &&
6260 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6263 if (((unsigned)EltIdx == (i + NumElems)) &&
6264 (SndLaneEltIdx < 0 ||
6265 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6266 MaskValue |= (1<<i);
6271 // Convert i32 vectors to floating point if it is not AVX2.
6272 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6274 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6275 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6277 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6278 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6281 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6282 DAG.getConstant(MaskValue, MVT::i32));
6283 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6286 // v8i16 shuffles - Prefer shuffles in the following order:
6287 // 1. [all] pshuflw, pshufhw, optional move
6288 // 2. [ssse3] 1 x pshufb
6289 // 3. [ssse3] 2 x pshufb + 1 x por
6290 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6292 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6293 SelectionDAG &DAG) {
6294 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6295 SDValue V1 = SVOp->getOperand(0);
6296 SDValue V2 = SVOp->getOperand(1);
6298 SmallVector<int, 8> MaskVals;
6300 // Determine if more than 1 of the words in each of the low and high quadwords
6301 // of the result come from the same quadword of one of the two inputs. Undef
6302 // mask values count as coming from any quadword, for better codegen.
6303 unsigned LoQuad[] = { 0, 0, 0, 0 };
6304 unsigned HiQuad[] = { 0, 0, 0, 0 };
6305 std::bitset<4> InputQuads;
6306 for (unsigned i = 0; i < 8; ++i) {
6307 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6308 int EltIdx = SVOp->getMaskElt(i);
6309 MaskVals.push_back(EltIdx);
6318 InputQuads.set(EltIdx / 4);
6321 int BestLoQuad = -1;
6322 unsigned MaxQuad = 1;
6323 for (unsigned i = 0; i < 4; ++i) {
6324 if (LoQuad[i] > MaxQuad) {
6326 MaxQuad = LoQuad[i];
6330 int BestHiQuad = -1;
6332 for (unsigned i = 0; i < 4; ++i) {
6333 if (HiQuad[i] > MaxQuad) {
6335 MaxQuad = HiQuad[i];
6339 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6340 // of the two input vectors, shuffle them into one input vector so only a
6341 // single pshufb instruction is necessary. If There are more than 2 input
6342 // quads, disable the next transformation since it does not help SSSE3.
6343 bool V1Used = InputQuads[0] || InputQuads[1];
6344 bool V2Used = InputQuads[2] || InputQuads[3];
6345 if (Subtarget->hasSSSE3()) {
6346 if (InputQuads.count() == 2 && V1Used && V2Used) {
6347 BestLoQuad = InputQuads[0] ? 0 : 1;
6348 BestHiQuad = InputQuads[2] ? 2 : 3;
6350 if (InputQuads.count() > 2) {
6356 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6357 // the shuffle mask. If a quad is scored as -1, that means that it contains
6358 // words from all 4 input quadwords.
6360 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6362 BestLoQuad < 0 ? 0 : BestLoQuad,
6363 BestHiQuad < 0 ? 1 : BestHiQuad
6365 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6366 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6367 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6368 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6370 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6371 // source words for the shuffle, to aid later transformations.
6372 bool AllWordsInNewV = true;
6373 bool InOrder[2] = { true, true };
6374 for (unsigned i = 0; i != 8; ++i) {
6375 int idx = MaskVals[i];
6377 InOrder[i/4] = false;
6378 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6380 AllWordsInNewV = false;
6384 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6385 if (AllWordsInNewV) {
6386 for (int i = 0; i != 8; ++i) {
6387 int idx = MaskVals[i];
6390 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6391 if ((idx != i) && idx < 4)
6393 if ((idx != i) && idx > 3)
6402 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6403 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6404 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6405 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6406 unsigned TargetMask = 0;
6407 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6408 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6409 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6410 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6411 getShufflePSHUFLWImmediate(SVOp);
6412 V1 = NewV.getOperand(0);
6413 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6417 // Promote splats to a larger type which usually leads to more efficient code.
6418 // FIXME: Is this true if pshufb is available?
6419 if (SVOp->isSplat())
6420 return PromoteSplat(SVOp, DAG);
6422 // If we have SSSE3, and all words of the result are from 1 input vector,
6423 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6424 // is present, fall back to case 4.
6425 if (Subtarget->hasSSSE3()) {
6426 SmallVector<SDValue,16> pshufbMask;
6428 // If we have elements from both input vectors, set the high bit of the
6429 // shuffle mask element to zero out elements that come from V2 in the V1
6430 // mask, and elements that come from V1 in the V2 mask, so that the two
6431 // results can be OR'd together.
6432 bool TwoInputs = V1Used && V2Used;
6433 for (unsigned i = 0; i != 8; ++i) {
6434 int EltIdx = MaskVals[i] * 2;
6435 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6436 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6437 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6438 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6440 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6441 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6442 DAG.getNode(ISD::BUILD_VECTOR, dl,
6443 MVT::v16i8, &pshufbMask[0], 16));
6445 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6447 // Calculate the shuffle mask for the second input, shuffle it, and
6448 // OR it with the first shuffled input.
6450 for (unsigned i = 0; i != 8; ++i) {
6451 int EltIdx = MaskVals[i] * 2;
6452 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6453 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6454 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6455 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6457 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6458 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6459 DAG.getNode(ISD::BUILD_VECTOR, dl,
6460 MVT::v16i8, &pshufbMask[0], 16));
6461 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6462 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6465 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6466 // and update MaskVals with new element order.
6467 std::bitset<8> InOrder;
6468 if (BestLoQuad >= 0) {
6469 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6470 for (int i = 0; i != 4; ++i) {
6471 int idx = MaskVals[i];
6474 } else if ((idx / 4) == BestLoQuad) {
6479 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6482 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6483 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6484 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6486 getShufflePSHUFLWImmediate(SVOp), DAG);
6490 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6491 // and update MaskVals with the new element order.
6492 if (BestHiQuad >= 0) {
6493 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6494 for (unsigned i = 4; i != 8; ++i) {
6495 int idx = MaskVals[i];
6498 } else if ((idx / 4) == BestHiQuad) {
6499 MaskV[i] = (idx & 3) + 4;
6503 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6506 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6507 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6508 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6510 getShufflePSHUFHWImmediate(SVOp), DAG);
6514 // In case BestHi & BestLo were both -1, which means each quadword has a word
6515 // from each of the four input quadwords, calculate the InOrder bitvector now
6516 // before falling through to the insert/extract cleanup.
6517 if (BestLoQuad == -1 && BestHiQuad == -1) {
6519 for (int i = 0; i != 8; ++i)
6520 if (MaskVals[i] < 0 || MaskVals[i] == i)
6524 // The other elements are put in the right place using pextrw and pinsrw.
6525 for (unsigned i = 0; i != 8; ++i) {
6528 int EltIdx = MaskVals[i];
6531 SDValue ExtOp = (EltIdx < 8) ?
6532 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6533 DAG.getIntPtrConstant(EltIdx)) :
6534 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6535 DAG.getIntPtrConstant(EltIdx - 8));
6536 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6537 DAG.getIntPtrConstant(i));
6542 // v16i8 shuffles - Prefer shuffles in the following order:
6543 // 1. [ssse3] 1 x pshufb
6544 // 2. [ssse3] 2 x pshufb + 1 x por
6545 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6546 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6547 const X86Subtarget* Subtarget,
6548 SelectionDAG &DAG) {
6549 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6550 SDValue V1 = SVOp->getOperand(0);
6551 SDValue V2 = SVOp->getOperand(1);
6553 ArrayRef<int> MaskVals = SVOp->getMask();
6555 // Promote splats to a larger type which usually leads to more efficient code.
6556 // FIXME: Is this true if pshufb is available?
6557 if (SVOp->isSplat())
6558 return PromoteSplat(SVOp, DAG);
6560 // If we have SSSE3, case 1 is generated when all result bytes come from
6561 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6562 // present, fall back to case 3.
6564 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6565 if (Subtarget->hasSSSE3()) {
6566 SmallVector<SDValue,16> pshufbMask;
6568 // If all result elements are from one input vector, then only translate
6569 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6571 // Otherwise, we have elements from both input vectors, and must zero out
6572 // elements that come from V2 in the first mask, and V1 in the second mask
6573 // so that we can OR them together.
6574 for (unsigned i = 0; i != 16; ++i) {
6575 int EltIdx = MaskVals[i];
6576 if (EltIdx < 0 || EltIdx >= 16)
6578 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6580 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6581 DAG.getNode(ISD::BUILD_VECTOR, dl,
6582 MVT::v16i8, &pshufbMask[0], 16));
6584 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6585 // the 2nd operand if it's undefined or zero.
6586 if (V2.getOpcode() == ISD::UNDEF ||
6587 ISD::isBuildVectorAllZeros(V2.getNode()))
6590 // Calculate the shuffle mask for the second input, shuffle it, and
6591 // OR it with the first shuffled input.
6593 for (unsigned i = 0; i != 16; ++i) {
6594 int EltIdx = MaskVals[i];
6595 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6596 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6598 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6599 DAG.getNode(ISD::BUILD_VECTOR, dl,
6600 MVT::v16i8, &pshufbMask[0], 16));
6601 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6604 // No SSSE3 - Calculate in place words and then fix all out of place words
6605 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6606 // the 16 different words that comprise the two doublequadword input vectors.
6607 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6608 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6610 for (int i = 0; i != 8; ++i) {
6611 int Elt0 = MaskVals[i*2];
6612 int Elt1 = MaskVals[i*2+1];
6614 // This word of the result is all undef, skip it.
6615 if (Elt0 < 0 && Elt1 < 0)
6618 // This word of the result is already in the correct place, skip it.
6619 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6622 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6623 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6626 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6627 // using a single extract together, load it and store it.
6628 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6629 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6630 DAG.getIntPtrConstant(Elt1 / 2));
6631 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6632 DAG.getIntPtrConstant(i));
6636 // If Elt1 is defined, extract it from the appropriate source. If the
6637 // source byte is not also odd, shift the extracted word left 8 bits
6638 // otherwise clear the bottom 8 bits if we need to do an or.
6640 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6641 DAG.getIntPtrConstant(Elt1 / 2));
6642 if ((Elt1 & 1) == 0)
6643 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6645 TLI.getShiftAmountTy(InsElt.getValueType())));
6647 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6648 DAG.getConstant(0xFF00, MVT::i16));
6650 // If Elt0 is defined, extract it from the appropriate source. If the
6651 // source byte is not also even, shift the extracted word right 8 bits. If
6652 // Elt1 was also defined, OR the extracted values together before
6653 // inserting them in the result.
6655 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6656 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6657 if ((Elt0 & 1) != 0)
6658 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6660 TLI.getShiftAmountTy(InsElt0.getValueType())));
6662 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6663 DAG.getConstant(0x00FF, MVT::i16));
6664 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6667 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6668 DAG.getIntPtrConstant(i));
6670 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6673 // v32i8 shuffles - Translate to VPSHUFB if possible.
6675 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6676 const X86Subtarget *Subtarget,
6677 SelectionDAG &DAG) {
6678 MVT VT = SVOp->getSimpleValueType(0);
6679 SDValue V1 = SVOp->getOperand(0);
6680 SDValue V2 = SVOp->getOperand(1);
6682 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6684 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6685 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6686 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6688 // VPSHUFB may be generated if
6689 // (1) one of input vector is undefined or zeroinitializer.
6690 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6691 // And (2) the mask indexes don't cross the 128-bit lane.
6692 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6693 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6696 if (V1IsAllZero && !V2IsAllZero) {
6697 CommuteVectorShuffleMask(MaskVals, 32);
6700 SmallVector<SDValue, 32> pshufbMask;
6701 for (unsigned i = 0; i != 32; i++) {
6702 int EltIdx = MaskVals[i];
6703 if (EltIdx < 0 || EltIdx >= 32)
6706 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6707 // Cross lane is not allowed.
6711 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6713 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6714 DAG.getNode(ISD::BUILD_VECTOR, dl,
6715 MVT::v32i8, &pshufbMask[0], 32));
6718 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6719 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6720 /// done when every pair / quad of shuffle mask elements point to elements in
6721 /// the right sequence. e.g.
6722 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6724 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6725 SelectionDAG &DAG) {
6726 MVT VT = SVOp->getSimpleValueType(0);
6728 unsigned NumElems = VT.getVectorNumElements();
6731 switch (VT.SimpleTy) {
6732 default: llvm_unreachable("Unexpected!");
6733 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6734 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6735 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6736 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6737 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6738 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6741 SmallVector<int, 8> MaskVec;
6742 for (unsigned i = 0; i != NumElems; i += Scale) {
6744 for (unsigned j = 0; j != Scale; ++j) {
6745 int EltIdx = SVOp->getMaskElt(i+j);
6749 StartIdx = (EltIdx / Scale);
6750 if (EltIdx != (int)(StartIdx*Scale + j))
6753 MaskVec.push_back(StartIdx);
6756 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6757 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6758 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6761 /// getVZextMovL - Return a zero-extending vector move low node.
6763 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6764 SDValue SrcOp, SelectionDAG &DAG,
6765 const X86Subtarget *Subtarget, SDLoc dl) {
6766 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6767 LoadSDNode *LD = NULL;
6768 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6769 LD = dyn_cast<LoadSDNode>(SrcOp);
6771 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6773 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6774 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6775 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6776 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6777 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6779 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6780 return DAG.getNode(ISD::BITCAST, dl, VT,
6781 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6782 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6790 return DAG.getNode(ISD::BITCAST, dl, VT,
6791 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6792 DAG.getNode(ISD::BITCAST, dl,
6796 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6797 /// which could not be matched by any known target speficic shuffle
6799 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6801 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6802 if (NewOp.getNode())
6805 MVT VT = SVOp->getSimpleValueType(0);
6807 unsigned NumElems = VT.getVectorNumElements();
6808 unsigned NumLaneElems = NumElems / 2;
6811 MVT EltVT = VT.getVectorElementType();
6812 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6815 SmallVector<int, 16> Mask;
6816 for (unsigned l = 0; l < 2; ++l) {
6817 // Build a shuffle mask for the output, discovering on the fly which
6818 // input vectors to use as shuffle operands (recorded in InputUsed).
6819 // If building a suitable shuffle vector proves too hard, then bail
6820 // out with UseBuildVector set.
6821 bool UseBuildVector = false;
6822 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6823 unsigned LaneStart = l * NumLaneElems;
6824 for (unsigned i = 0; i != NumLaneElems; ++i) {
6825 // The mask element. This indexes into the input.
6826 int Idx = SVOp->getMaskElt(i+LaneStart);
6828 // the mask element does not index into any input vector.
6833 // The input vector this mask element indexes into.
6834 int Input = Idx / NumLaneElems;
6836 // Turn the index into an offset from the start of the input vector.
6837 Idx -= Input * NumLaneElems;
6839 // Find or create a shuffle vector operand to hold this input.
6841 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6842 if (InputUsed[OpNo] == Input)
6843 // This input vector is already an operand.
6845 if (InputUsed[OpNo] < 0) {
6846 // Create a new operand for this input vector.
6847 InputUsed[OpNo] = Input;
6852 if (OpNo >= array_lengthof(InputUsed)) {
6853 // More than two input vectors used! Give up on trying to create a
6854 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6855 UseBuildVector = true;
6859 // Add the mask index for the new shuffle vector.
6860 Mask.push_back(Idx + OpNo * NumLaneElems);
6863 if (UseBuildVector) {
6864 SmallVector<SDValue, 16> SVOps;
6865 for (unsigned i = 0; i != NumLaneElems; ++i) {
6866 // The mask element. This indexes into the input.
6867 int Idx = SVOp->getMaskElt(i+LaneStart);
6869 SVOps.push_back(DAG.getUNDEF(EltVT));
6873 // The input vector this mask element indexes into.
6874 int Input = Idx / NumElems;
6876 // Turn the index into an offset from the start of the input vector.
6877 Idx -= Input * NumElems;
6879 // Extract the vector element by hand.
6880 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6881 SVOp->getOperand(Input),
6882 DAG.getIntPtrConstant(Idx)));
6885 // Construct the output using a BUILD_VECTOR.
6886 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6888 } else if (InputUsed[0] < 0) {
6889 // No input vectors were used! The result is undefined.
6890 Output[l] = DAG.getUNDEF(NVT);
6892 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6893 (InputUsed[0] % 2) * NumLaneElems,
6895 // If only one input was used, use an undefined vector for the other.
6896 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6897 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6898 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6899 // At least one input vector was used. Create a new shuffle vector.
6900 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6906 // Concatenate the result back
6907 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6910 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6911 /// 4 elements, and match them with several different shuffle types.
6913 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6914 SDValue V1 = SVOp->getOperand(0);
6915 SDValue V2 = SVOp->getOperand(1);
6917 MVT VT = SVOp->getSimpleValueType(0);
6919 assert(VT.is128BitVector() && "Unsupported vector size");
6921 std::pair<int, int> Locs[4];
6922 int Mask1[] = { -1, -1, -1, -1 };
6923 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6927 for (unsigned i = 0; i != 4; ++i) {
6928 int Idx = PermMask[i];
6930 Locs[i] = std::make_pair(-1, -1);
6932 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6934 Locs[i] = std::make_pair(0, NumLo);
6938 Locs[i] = std::make_pair(1, NumHi);
6940 Mask1[2+NumHi] = Idx;
6946 if (NumLo <= 2 && NumHi <= 2) {
6947 // If no more than two elements come from either vector. This can be
6948 // implemented with two shuffles. First shuffle gather the elements.
6949 // The second shuffle, which takes the first shuffle as both of its
6950 // vector operands, put the elements into the right order.
6951 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6953 int Mask2[] = { -1, -1, -1, -1 };
6955 for (unsigned i = 0; i != 4; ++i)
6956 if (Locs[i].first != -1) {
6957 unsigned Idx = (i < 2) ? 0 : 4;
6958 Idx += Locs[i].first * 2 + Locs[i].second;
6962 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6965 if (NumLo == 3 || NumHi == 3) {
6966 // Otherwise, we must have three elements from one vector, call it X, and
6967 // one element from the other, call it Y. First, use a shufps to build an
6968 // intermediate vector with the one element from Y and the element from X
6969 // that will be in the same half in the final destination (the indexes don't
6970 // matter). Then, use a shufps to build the final vector, taking the half
6971 // containing the element from Y from the intermediate, and the other half
6974 // Normalize it so the 3 elements come from V1.
6975 CommuteVectorShuffleMask(PermMask, 4);
6979 // Find the element from V2.
6981 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6982 int Val = PermMask[HiIndex];
6989 Mask1[0] = PermMask[HiIndex];
6991 Mask1[2] = PermMask[HiIndex^1];
6993 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6996 Mask1[0] = PermMask[0];
6997 Mask1[1] = PermMask[1];
6998 Mask1[2] = HiIndex & 1 ? 6 : 4;
6999 Mask1[3] = HiIndex & 1 ? 4 : 6;
7000 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7003 Mask1[0] = HiIndex & 1 ? 2 : 0;
7004 Mask1[1] = HiIndex & 1 ? 0 : 2;
7005 Mask1[2] = PermMask[2];
7006 Mask1[3] = PermMask[3];
7011 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7014 // Break it into (shuffle shuffle_hi, shuffle_lo).
7015 int LoMask[] = { -1, -1, -1, -1 };
7016 int HiMask[] = { -1, -1, -1, -1 };
7018 int *MaskPtr = LoMask;
7019 unsigned MaskIdx = 0;
7022 for (unsigned i = 0; i != 4; ++i) {
7029 int Idx = PermMask[i];
7031 Locs[i] = std::make_pair(-1, -1);
7032 } else if (Idx < 4) {
7033 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7034 MaskPtr[LoIdx] = Idx;
7037 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7038 MaskPtr[HiIdx] = Idx;
7043 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7044 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7045 int MaskOps[] = { -1, -1, -1, -1 };
7046 for (unsigned i = 0; i != 4; ++i)
7047 if (Locs[i].first != -1)
7048 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7049 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7052 static bool MayFoldVectorLoad(SDValue V) {
7053 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7054 V = V.getOperand(0);
7056 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7057 V = V.getOperand(0);
7058 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7059 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7060 // BUILD_VECTOR (load), undef
7061 V = V.getOperand(0);
7063 return MayFoldLoad(V);
7067 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7068 MVT VT = Op.getSimpleValueType();
7070 // Canonizalize to v2f64.
7071 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7072 return DAG.getNode(ISD::BITCAST, dl, VT,
7073 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7078 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7080 SDValue V1 = Op.getOperand(0);
7081 SDValue V2 = Op.getOperand(1);
7082 MVT VT = Op.getSimpleValueType();
7084 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7086 if (HasSSE2 && VT == MVT::v2f64)
7087 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7089 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7090 return DAG.getNode(ISD::BITCAST, dl, VT,
7091 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7092 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7093 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7097 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7098 SDValue V1 = Op.getOperand(0);
7099 SDValue V2 = Op.getOperand(1);
7100 MVT VT = Op.getSimpleValueType();
7102 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7103 "unsupported shuffle type");
7105 if (V2.getOpcode() == ISD::UNDEF)
7109 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7113 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7114 SDValue V1 = Op.getOperand(0);
7115 SDValue V2 = Op.getOperand(1);
7116 MVT VT = Op.getSimpleValueType();
7117 unsigned NumElems = VT.getVectorNumElements();
7119 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7120 // operand of these instructions is only memory, so check if there's a
7121 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7123 bool CanFoldLoad = false;
7125 // Trivial case, when V2 comes from a load.
7126 if (MayFoldVectorLoad(V2))
7129 // When V1 is a load, it can be folded later into a store in isel, example:
7130 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7132 // (MOVLPSmr addr:$src1, VR128:$src2)
7133 // So, recognize this potential and also use MOVLPS or MOVLPD
7134 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7137 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7139 if (HasSSE2 && NumElems == 2)
7140 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7143 // If we don't care about the second element, proceed to use movss.
7144 if (SVOp->getMaskElt(1) != -1)
7145 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7148 // movl and movlp will both match v2i64, but v2i64 is never matched by
7149 // movl earlier because we make it strict to avoid messing with the movlp load
7150 // folding logic (see the code above getMOVLP call). Match it here then,
7151 // this is horrible, but will stay like this until we move all shuffle
7152 // matching to x86 specific nodes. Note that for the 1st condition all
7153 // types are matched with movsd.
7155 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7156 // as to remove this logic from here, as much as possible
7157 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7158 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7159 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7162 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7164 // Invert the operand order and use SHUFPS to match it.
7165 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7166 getShuffleSHUFImmediate(SVOp), DAG);
7169 // Reduce a vector shuffle to zext.
7170 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7171 SelectionDAG &DAG) {
7172 // PMOVZX is only available from SSE41.
7173 if (!Subtarget->hasSSE41())
7176 MVT VT = Op.getSimpleValueType();
7178 // Only AVX2 support 256-bit vector integer extending.
7179 if (!Subtarget->hasInt256() && VT.is256BitVector())
7182 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7184 SDValue V1 = Op.getOperand(0);
7185 SDValue V2 = Op.getOperand(1);
7186 unsigned NumElems = VT.getVectorNumElements();
7188 // Extending is an unary operation and the element type of the source vector
7189 // won't be equal to or larger than i64.
7190 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7191 VT.getVectorElementType() == MVT::i64)
7194 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7195 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7196 while ((1U << Shift) < NumElems) {
7197 if (SVOp->getMaskElt(1U << Shift) == 1)
7200 // The maximal ratio is 8, i.e. from i8 to i64.
7205 // Check the shuffle mask.
7206 unsigned Mask = (1U << Shift) - 1;
7207 for (unsigned i = 0; i != NumElems; ++i) {
7208 int EltIdx = SVOp->getMaskElt(i);
7209 if ((i & Mask) != 0 && EltIdx != -1)
7211 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7215 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7216 MVT NeVT = MVT::getIntegerVT(NBits);
7217 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7219 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7222 // Simplify the operand as it's prepared to be fed into shuffle.
7223 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7224 if (V1.getOpcode() == ISD::BITCAST &&
7225 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7226 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7227 V1.getOperand(0).getOperand(0)
7228 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7229 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7230 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7231 ConstantSDNode *CIdx =
7232 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7233 // If it's foldable, i.e. normal load with single use, we will let code
7234 // selection to fold it. Otherwise, we will short the conversion sequence.
7235 if (CIdx && CIdx->getZExtValue() == 0 &&
7236 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7237 MVT FullVT = V.getSimpleValueType();
7238 MVT V1VT = V1.getSimpleValueType();
7239 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7240 // The "ext_vec_elt" node is wider than the result node.
7241 // In this case we should extract subvector from V.
7242 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7243 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7244 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7245 FullVT.getVectorNumElements()/Ratio);
7246 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7247 DAG.getIntPtrConstant(0));
7249 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7253 return DAG.getNode(ISD::BITCAST, DL, VT,
7254 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7258 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7259 SelectionDAG &DAG) {
7260 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7261 MVT VT = Op.getSimpleValueType();
7263 SDValue V1 = Op.getOperand(0);
7264 SDValue V2 = Op.getOperand(1);
7266 if (isZeroShuffle(SVOp))
7267 return getZeroVector(VT, Subtarget, DAG, dl);
7269 // Handle splat operations
7270 if (SVOp->isSplat()) {
7271 // Use vbroadcast whenever the splat comes from a foldable load
7272 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7273 if (Broadcast.getNode())
7277 // Check integer expanding shuffles.
7278 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7279 if (NewOp.getNode())
7282 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7284 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7285 VT == MVT::v16i16 || VT == MVT::v32i8) {
7286 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7287 if (NewOp.getNode())
7288 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7289 } else if ((VT == MVT::v4i32 ||
7290 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7291 // FIXME: Figure out a cleaner way to do this.
7292 // Try to make use of movq to zero out the top part.
7293 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7294 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7295 if (NewOp.getNode()) {
7296 MVT NewVT = NewOp.getSimpleValueType();
7297 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7298 NewVT, true, false))
7299 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7300 DAG, Subtarget, dl);
7302 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7303 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7304 if (NewOp.getNode()) {
7305 MVT NewVT = NewOp.getSimpleValueType();
7306 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7307 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7308 DAG, Subtarget, dl);
7316 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7317 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7318 SDValue V1 = Op.getOperand(0);
7319 SDValue V2 = Op.getOperand(1);
7320 MVT VT = Op.getSimpleValueType();
7322 unsigned NumElems = VT.getVectorNumElements();
7323 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7324 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7325 bool V1IsSplat = false;
7326 bool V2IsSplat = false;
7327 bool HasSSE2 = Subtarget->hasSSE2();
7328 bool HasFp256 = Subtarget->hasFp256();
7329 bool HasInt256 = Subtarget->hasInt256();
7330 MachineFunction &MF = DAG.getMachineFunction();
7331 bool OptForSize = MF.getFunction()->getAttributes().
7332 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7334 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7336 if (V1IsUndef && V2IsUndef)
7337 return DAG.getUNDEF(VT);
7339 // When we create a shuffle node we put the UNDEF node to second operand,
7340 // but in some cases the first operand may be transformed to UNDEF.
7341 // In this case we should just commute the node.
7343 return CommuteVectorShuffle(SVOp, DAG);
7345 // Vector shuffle lowering takes 3 steps:
7347 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7348 // narrowing and commutation of operands should be handled.
7349 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7351 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7352 // so the shuffle can be broken into other shuffles and the legalizer can
7353 // try the lowering again.
7355 // The general idea is that no vector_shuffle operation should be left to
7356 // be matched during isel, all of them must be converted to a target specific
7359 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7360 // narrowing and commutation of operands should be handled. The actual code
7361 // doesn't include all of those, work in progress...
7362 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7363 if (NewOp.getNode())
7366 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7368 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7369 // unpckh_undef). Only use pshufd if speed is more important than size.
7370 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7371 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7372 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7373 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7375 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7376 V2IsUndef && MayFoldVectorLoad(V1))
7377 return getMOVDDup(Op, dl, V1, DAG);
7379 if (isMOVHLPS_v_undef_Mask(M, VT))
7380 return getMOVHighToLow(Op, dl, DAG);
7382 // Use to match splats
7383 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7384 (VT == MVT::v2f64 || VT == MVT::v2i64))
7385 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7387 if (isPSHUFDMask(M, VT)) {
7388 // The actual implementation will match the mask in the if above and then
7389 // during isel it can match several different instructions, not only pshufd
7390 // as its name says, sad but true, emulate the behavior for now...
7391 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7392 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7394 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7396 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7397 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7399 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7400 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7403 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7407 if (isPALIGNRMask(M, VT, Subtarget))
7408 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7409 getShufflePALIGNRImmediate(SVOp),
7412 // Check if this can be converted into a logical shift.
7413 bool isLeft = false;
7416 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7417 if (isShift && ShVal.hasOneUse()) {
7418 // If the shifted value has multiple uses, it may be cheaper to use
7419 // v_set0 + movlhps or movhlps, etc.
7420 MVT EltVT = VT.getVectorElementType();
7421 ShAmt *= EltVT.getSizeInBits();
7422 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7425 if (isMOVLMask(M, VT)) {
7426 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7427 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7428 if (!isMOVLPMask(M, VT)) {
7429 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7430 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7432 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7433 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7437 // FIXME: fold these into legal mask.
7438 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7439 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7441 if (isMOVHLPSMask(M, VT))
7442 return getMOVHighToLow(Op, dl, DAG);
7444 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7445 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7447 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7448 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7450 if (isMOVLPMask(M, VT))
7451 return getMOVLP(Op, dl, DAG, HasSSE2);
7453 if (ShouldXformToMOVHLPS(M, VT) ||
7454 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7455 return CommuteVectorShuffle(SVOp, DAG);
7458 // No better options. Use a vshldq / vsrldq.
7459 MVT EltVT = VT.getVectorElementType();
7460 ShAmt *= EltVT.getSizeInBits();
7461 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7464 bool Commuted = false;
7465 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7466 // 1,1,1,1 -> v8i16 though.
7467 V1IsSplat = isSplatVector(V1.getNode());
7468 V2IsSplat = isSplatVector(V2.getNode());
7470 // Canonicalize the splat or undef, if present, to be on the RHS.
7471 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7472 CommuteVectorShuffleMask(M, NumElems);
7474 std::swap(V1IsSplat, V2IsSplat);
7478 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7479 // Shuffling low element of v1 into undef, just return v1.
7482 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7483 // the instruction selector will not match, so get a canonical MOVL with
7484 // swapped operands to undo the commute.
7485 return getMOVL(DAG, dl, VT, V2, V1);
7488 if (isUNPCKLMask(M, VT, HasInt256))
7489 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7491 if (isUNPCKHMask(M, VT, HasInt256))
7492 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7495 // Normalize mask so all entries that point to V2 points to its first
7496 // element then try to match unpck{h|l} again. If match, return a
7497 // new vector_shuffle with the corrected mask.p
7498 SmallVector<int, 8> NewMask(M.begin(), M.end());
7499 NormalizeMask(NewMask, NumElems);
7500 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7501 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7502 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7503 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7507 // Commute is back and try unpck* again.
7508 // FIXME: this seems wrong.
7509 CommuteVectorShuffleMask(M, NumElems);
7511 std::swap(V1IsSplat, V2IsSplat);
7513 if (isUNPCKLMask(M, VT, HasInt256))
7514 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7516 if (isUNPCKHMask(M, VT, HasInt256))
7517 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7520 // Normalize the node to match x86 shuffle ops if needed
7521 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7522 return CommuteVectorShuffle(SVOp, DAG);
7524 // The checks below are all present in isShuffleMaskLegal, but they are
7525 // inlined here right now to enable us to directly emit target specific
7526 // nodes, and remove one by one until they don't return Op anymore.
7528 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7529 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7530 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7531 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7534 if (isPSHUFHWMask(M, VT, HasInt256))
7535 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7536 getShufflePSHUFHWImmediate(SVOp),
7539 if (isPSHUFLWMask(M, VT, HasInt256))
7540 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7541 getShufflePSHUFLWImmediate(SVOp),
7544 if (isSHUFPMask(M, VT))
7545 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7546 getShuffleSHUFImmediate(SVOp), DAG);
7548 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7549 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7550 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7551 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7553 //===--------------------------------------------------------------------===//
7554 // Generate target specific nodes for 128 or 256-bit shuffles only
7555 // supported in the AVX instruction set.
7558 // Handle VMOVDDUPY permutations
7559 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7560 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7562 // Handle VPERMILPS/D* permutations
7563 if (isVPERMILPMask(M, VT)) {
7564 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7565 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7566 getShuffleSHUFImmediate(SVOp), DAG);
7567 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7568 getShuffleSHUFImmediate(SVOp), DAG);
7571 // Handle VPERM2F128/VPERM2I128 permutations
7572 if (isVPERM2X128Mask(M, VT, HasFp256))
7573 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7574 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7576 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7577 if (BlendOp.getNode())
7581 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7582 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7584 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7585 VT.is512BitVector()) {
7586 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7587 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7588 SmallVector<SDValue, 16> permclMask;
7589 for (unsigned i = 0; i != NumElems; ++i) {
7590 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7593 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7594 &permclMask[0], NumElems);
7596 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7597 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7598 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7599 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7600 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7603 //===--------------------------------------------------------------------===//
7604 // Since no target specific shuffle was selected for this generic one,
7605 // lower it into other known shuffles. FIXME: this isn't true yet, but
7606 // this is the plan.
7609 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7610 if (VT == MVT::v8i16) {
7611 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7612 if (NewOp.getNode())
7616 if (VT == MVT::v16i8) {
7617 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7618 if (NewOp.getNode())
7622 if (VT == MVT::v32i8) {
7623 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7624 if (NewOp.getNode())
7628 // Handle all 128-bit wide vectors with 4 elements, and match them with
7629 // several different shuffle types.
7630 if (NumElems == 4 && VT.is128BitVector())
7631 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7633 // Handle general 256-bit shuffles
7634 if (VT.is256BitVector())
7635 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7640 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7641 MVT VT = Op.getSimpleValueType();
7644 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7647 if (VT.getSizeInBits() == 8) {
7648 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7649 Op.getOperand(0), Op.getOperand(1));
7650 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7651 DAG.getValueType(VT));
7652 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7655 if (VT.getSizeInBits() == 16) {
7656 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7657 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7659 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7660 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7661 DAG.getNode(ISD::BITCAST, dl,
7665 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7666 Op.getOperand(0), Op.getOperand(1));
7667 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7668 DAG.getValueType(VT));
7669 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7672 if (VT == MVT::f32) {
7673 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7674 // the result back to FR32 register. It's only worth matching if the
7675 // result has a single use which is a store or a bitcast to i32. And in
7676 // the case of a store, it's not worth it if the index is a constant 0,
7677 // because a MOVSSmr can be used instead, which is smaller and faster.
7678 if (!Op.hasOneUse())
7680 SDNode *User = *Op.getNode()->use_begin();
7681 if ((User->getOpcode() != ISD::STORE ||
7682 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7683 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7684 (User->getOpcode() != ISD::BITCAST ||
7685 User->getValueType(0) != MVT::i32))
7687 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7688 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7691 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7694 if (VT == MVT::i32 || VT == MVT::i64) {
7695 // ExtractPS/pextrq works with constant index.
7696 if (isa<ConstantSDNode>(Op.getOperand(1)))
7702 /// Extract one bit from mask vector, like v16i1 or v8i1.
7703 /// AVX-512 feature.
7705 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7706 SDValue Vec = Op.getOperand(0);
7708 MVT VecVT = Vec.getSimpleValueType();
7709 SDValue Idx = Op.getOperand(1);
7710 MVT EltVT = Op.getSimpleValueType();
7712 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7714 // variable index can't be handled in mask registers,
7715 // extend vector to VR512
7716 if (!isa<ConstantSDNode>(Idx)) {
7717 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7718 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7719 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7720 ExtVT.getVectorElementType(), Ext, Idx);
7721 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7724 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7725 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7726 unsigned MaxSift = rc->getSize()*8 - 1;
7727 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7728 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7729 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7730 DAG.getConstant(MaxSift, MVT::i8));
7731 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7732 DAG.getIntPtrConstant(0));
7736 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7737 SelectionDAG &DAG) const {
7739 SDValue Vec = Op.getOperand(0);
7740 MVT VecVT = Vec.getSimpleValueType();
7741 SDValue Idx = Op.getOperand(1);
7743 if (Op.getSimpleValueType() == MVT::i1)
7744 return ExtractBitFromMaskVector(Op, DAG);
7746 if (!isa<ConstantSDNode>(Idx)) {
7747 if (VecVT.is512BitVector() ||
7748 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7749 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7752 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7753 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7754 MaskEltVT.getSizeInBits());
7756 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7757 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7758 getZeroVector(MaskVT, Subtarget, DAG, dl),
7759 Idx, DAG.getConstant(0, getPointerTy()));
7760 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7761 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7762 Perm, DAG.getConstant(0, getPointerTy()));
7767 // If this is a 256-bit vector result, first extract the 128-bit vector and
7768 // then extract the element from the 128-bit vector.
7769 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7771 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7772 // Get the 128-bit vector.
7773 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7774 MVT EltVT = VecVT.getVectorElementType();
7776 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7778 //if (IdxVal >= NumElems/2)
7779 // IdxVal -= NumElems/2;
7780 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7781 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7782 DAG.getConstant(IdxVal, MVT::i32));
7785 assert(VecVT.is128BitVector() && "Unexpected vector length");
7787 if (Subtarget->hasSSE41()) {
7788 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7793 MVT VT = Op.getSimpleValueType();
7794 // TODO: handle v16i8.
7795 if (VT.getSizeInBits() == 16) {
7796 SDValue Vec = Op.getOperand(0);
7797 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7799 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7800 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7801 DAG.getNode(ISD::BITCAST, dl,
7804 // Transform it so it match pextrw which produces a 32-bit result.
7805 MVT EltVT = MVT::i32;
7806 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7807 Op.getOperand(0), Op.getOperand(1));
7808 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7809 DAG.getValueType(VT));
7810 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7813 if (VT.getSizeInBits() == 32) {
7814 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7818 // SHUFPS the element to the lowest double word, then movss.
7819 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7820 MVT VVT = Op.getOperand(0).getSimpleValueType();
7821 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7822 DAG.getUNDEF(VVT), Mask);
7823 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7824 DAG.getIntPtrConstant(0));
7827 if (VT.getSizeInBits() == 64) {
7828 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7829 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7830 // to match extract_elt for f64.
7831 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7835 // UNPCKHPD the element to the lowest double word, then movsd.
7836 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7837 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7838 int Mask[2] = { 1, -1 };
7839 MVT VVT = Op.getOperand(0).getSimpleValueType();
7840 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7841 DAG.getUNDEF(VVT), Mask);
7842 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7843 DAG.getIntPtrConstant(0));
7849 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7850 MVT VT = Op.getSimpleValueType();
7851 MVT EltVT = VT.getVectorElementType();
7854 SDValue N0 = Op.getOperand(0);
7855 SDValue N1 = Op.getOperand(1);
7856 SDValue N2 = Op.getOperand(2);
7858 if (!VT.is128BitVector())
7861 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7862 isa<ConstantSDNode>(N2)) {
7864 if (VT == MVT::v8i16)
7865 Opc = X86ISD::PINSRW;
7866 else if (VT == MVT::v16i8)
7867 Opc = X86ISD::PINSRB;
7869 Opc = X86ISD::PINSRB;
7871 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7873 if (N1.getValueType() != MVT::i32)
7874 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7875 if (N2.getValueType() != MVT::i32)
7876 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7877 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7880 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7881 // Bits [7:6] of the constant are the source select. This will always be
7882 // zero here. The DAG Combiner may combine an extract_elt index into these
7883 // bits. For example (insert (extract, 3), 2) could be matched by putting
7884 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7885 // Bits [5:4] of the constant are the destination select. This is the
7886 // value of the incoming immediate.
7887 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7888 // combine either bitwise AND or insert of float 0.0 to set these bits.
7889 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7890 // Create this as a scalar to vector..
7891 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7892 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7895 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7896 // PINSR* works with constant index.
7903 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7904 MVT VT = Op.getSimpleValueType();
7905 MVT EltVT = VT.getVectorElementType();
7908 SDValue N0 = Op.getOperand(0);
7909 SDValue N1 = Op.getOperand(1);
7910 SDValue N2 = Op.getOperand(2);
7912 // If this is a 256-bit vector result, first extract the 128-bit vector,
7913 // insert the element into the extracted half and then place it back.
7914 if (VT.is256BitVector() || VT.is512BitVector()) {
7915 if (!isa<ConstantSDNode>(N2))
7918 // Get the desired 128-bit vector half.
7919 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7920 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7922 // Insert the element into the desired half.
7923 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7924 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7926 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7927 DAG.getConstant(IdxIn128, MVT::i32));
7929 // Insert the changed part back to the 256-bit vector
7930 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7933 if (Subtarget->hasSSE41())
7934 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7936 if (EltVT == MVT::i8)
7939 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7940 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7941 // as its second argument.
7942 if (N1.getValueType() != MVT::i32)
7943 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7944 if (N2.getValueType() != MVT::i32)
7945 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7946 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7951 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7953 MVT OpVT = Op.getSimpleValueType();
7955 // If this is a 256-bit vector result, first insert into a 128-bit
7956 // vector and then insert into the 256-bit vector.
7957 if (!OpVT.is128BitVector()) {
7958 // Insert into a 128-bit vector.
7959 unsigned SizeFactor = OpVT.getSizeInBits()/128;
7960 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
7961 OpVT.getVectorNumElements() / SizeFactor);
7963 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7965 // Insert the 128-bit vector.
7966 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7969 if (OpVT == MVT::v1i64 &&
7970 Op.getOperand(0).getValueType() == MVT::i64)
7971 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7973 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7974 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7975 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7976 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7979 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7980 // a simple subregister reference or explicit instructions to grab
7981 // upper bits of a vector.
7982 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7983 SelectionDAG &DAG) {
7985 SDValue In = Op.getOperand(0);
7986 SDValue Idx = Op.getOperand(1);
7987 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7988 MVT ResVT = Op.getSimpleValueType();
7989 MVT InVT = In.getSimpleValueType();
7991 if (Subtarget->hasFp256()) {
7992 if (ResVT.is128BitVector() &&
7993 (InVT.is256BitVector() || InVT.is512BitVector()) &&
7994 isa<ConstantSDNode>(Idx)) {
7995 return Extract128BitVector(In, IdxVal, DAG, dl);
7997 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7998 isa<ConstantSDNode>(Idx)) {
7999 return Extract256BitVector(In, IdxVal, DAG, dl);
8005 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8006 // simple superregister reference or explicit instructions to insert
8007 // the upper bits of a vector.
8008 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8009 SelectionDAG &DAG) {
8010 if (Subtarget->hasFp256()) {
8011 SDLoc dl(Op.getNode());
8012 SDValue Vec = Op.getNode()->getOperand(0);
8013 SDValue SubVec = Op.getNode()->getOperand(1);
8014 SDValue Idx = Op.getNode()->getOperand(2);
8016 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8017 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8018 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8019 isa<ConstantSDNode>(Idx)) {
8020 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8021 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8024 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8025 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8026 isa<ConstantSDNode>(Idx)) {
8027 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8028 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8034 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8035 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8036 // one of the above mentioned nodes. It has to be wrapped because otherwise
8037 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8038 // be used to form addressing mode. These wrapped nodes will be selected
8041 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8042 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8044 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8046 unsigned char OpFlag = 0;
8047 unsigned WrapperKind = X86ISD::Wrapper;
8048 CodeModel::Model M = getTargetMachine().getCodeModel();
8050 if (Subtarget->isPICStyleRIPRel() &&
8051 (M == CodeModel::Small || M == CodeModel::Kernel))
8052 WrapperKind = X86ISD::WrapperRIP;
8053 else if (Subtarget->isPICStyleGOT())
8054 OpFlag = X86II::MO_GOTOFF;
8055 else if (Subtarget->isPICStyleStubPIC())
8056 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8058 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8060 CP->getOffset(), OpFlag);
8062 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8063 // With PIC, the address is actually $g + Offset.
8065 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8066 DAG.getNode(X86ISD::GlobalBaseReg,
8067 SDLoc(), getPointerTy()),
8074 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8075 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8077 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8079 unsigned char OpFlag = 0;
8080 unsigned WrapperKind = X86ISD::Wrapper;
8081 CodeModel::Model M = getTargetMachine().getCodeModel();
8083 if (Subtarget->isPICStyleRIPRel() &&
8084 (M == CodeModel::Small || M == CodeModel::Kernel))
8085 WrapperKind = X86ISD::WrapperRIP;
8086 else if (Subtarget->isPICStyleGOT())
8087 OpFlag = X86II::MO_GOTOFF;
8088 else if (Subtarget->isPICStyleStubPIC())
8089 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8091 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8094 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8096 // With PIC, the address is actually $g + Offset.
8098 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8099 DAG.getNode(X86ISD::GlobalBaseReg,
8100 SDLoc(), getPointerTy()),
8107 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8108 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8110 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8112 unsigned char OpFlag = 0;
8113 unsigned WrapperKind = X86ISD::Wrapper;
8114 CodeModel::Model M = getTargetMachine().getCodeModel();
8116 if (Subtarget->isPICStyleRIPRel() &&
8117 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8118 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8119 OpFlag = X86II::MO_GOTPCREL;
8120 WrapperKind = X86ISD::WrapperRIP;
8121 } else if (Subtarget->isPICStyleGOT()) {
8122 OpFlag = X86II::MO_GOT;
8123 } else if (Subtarget->isPICStyleStubPIC()) {
8124 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8125 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8126 OpFlag = X86II::MO_DARWIN_NONLAZY;
8129 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8132 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8134 // With PIC, the address is actually $g + Offset.
8135 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8136 !Subtarget->is64Bit()) {
8137 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8138 DAG.getNode(X86ISD::GlobalBaseReg,
8139 SDLoc(), getPointerTy()),
8143 // For symbols that require a load from a stub to get the address, emit the
8145 if (isGlobalStubReference(OpFlag))
8146 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8147 MachinePointerInfo::getGOT(), false, false, false, 0);
8153 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8154 // Create the TargetBlockAddressAddress node.
8155 unsigned char OpFlags =
8156 Subtarget->ClassifyBlockAddressReference();
8157 CodeModel::Model M = getTargetMachine().getCodeModel();
8158 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8159 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8161 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8164 if (Subtarget->isPICStyleRIPRel() &&
8165 (M == CodeModel::Small || M == CodeModel::Kernel))
8166 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8168 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8170 // With PIC, the address is actually $g + Offset.
8171 if (isGlobalRelativeToPICBase(OpFlags)) {
8172 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8173 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8181 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8182 int64_t Offset, SelectionDAG &DAG) const {
8183 // Create the TargetGlobalAddress node, folding in the constant
8184 // offset if it is legal.
8185 unsigned char OpFlags =
8186 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8187 CodeModel::Model M = getTargetMachine().getCodeModel();
8189 if (OpFlags == X86II::MO_NO_FLAG &&
8190 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8191 // A direct static reference to a global.
8192 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8195 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8198 if (Subtarget->isPICStyleRIPRel() &&
8199 (M == CodeModel::Small || M == CodeModel::Kernel))
8200 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8202 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8204 // With PIC, the address is actually $g + Offset.
8205 if (isGlobalRelativeToPICBase(OpFlags)) {
8206 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8207 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8211 // For globals that require a load from a stub to get the address, emit the
8213 if (isGlobalStubReference(OpFlags))
8214 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8215 MachinePointerInfo::getGOT(), false, false, false, 0);
8217 // If there was a non-zero offset that we didn't fold, create an explicit
8220 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8221 DAG.getConstant(Offset, getPointerTy()));
8227 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8228 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8229 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8230 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8234 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8235 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8236 unsigned char OperandFlags, bool LocalDynamic = false) {
8237 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8238 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8240 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8241 GA->getValueType(0),
8245 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8249 SDValue Ops[] = { Chain, TGA, *InFlag };
8250 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8252 SDValue Ops[] = { Chain, TGA };
8253 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8256 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8257 MFI->setAdjustsStack(true);
8259 SDValue Flag = Chain.getValue(1);
8260 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8263 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8265 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8268 SDLoc dl(GA); // ? function entry point might be better
8269 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8270 DAG.getNode(X86ISD::GlobalBaseReg,
8271 SDLoc(), PtrVT), InFlag);
8272 InFlag = Chain.getValue(1);
8274 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8277 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8279 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8281 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8282 X86::RAX, X86II::MO_TLSGD);
8285 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8291 // Get the start address of the TLS block for this module.
8292 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8293 .getInfo<X86MachineFunctionInfo>();
8294 MFI->incNumLocalDynamicTLSAccesses();
8298 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8299 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8302 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8303 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8304 InFlag = Chain.getValue(1);
8305 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8306 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8309 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8313 unsigned char OperandFlags = X86II::MO_DTPOFF;
8314 unsigned WrapperKind = X86ISD::Wrapper;
8315 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8316 GA->getValueType(0),
8317 GA->getOffset(), OperandFlags);
8318 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8320 // Add x@dtpoff with the base.
8321 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8324 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8325 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8326 const EVT PtrVT, TLSModel::Model model,
8327 bool is64Bit, bool isPIC) {
8330 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8331 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8332 is64Bit ? 257 : 256));
8334 SDValue ThreadPointer =
8335 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8336 MachinePointerInfo(Ptr), false, false, false, 0);
8338 unsigned char OperandFlags = 0;
8339 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8341 unsigned WrapperKind = X86ISD::Wrapper;
8342 if (model == TLSModel::LocalExec) {
8343 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8344 } else if (model == TLSModel::InitialExec) {
8346 OperandFlags = X86II::MO_GOTTPOFF;
8347 WrapperKind = X86ISD::WrapperRIP;
8349 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8352 llvm_unreachable("Unexpected model");
8355 // emit "addl x@ntpoff,%eax" (local exec)
8356 // or "addl x@indntpoff,%eax" (initial exec)
8357 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8359 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8360 GA->getOffset(), OperandFlags);
8361 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8363 if (model == TLSModel::InitialExec) {
8364 if (isPIC && !is64Bit) {
8365 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8366 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8370 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8371 MachinePointerInfo::getGOT(), false, false, false, 0);
8374 // The address of the thread local variable is the add of the thread
8375 // pointer with the offset of the variable.
8376 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8380 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8382 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8383 const GlobalValue *GV = GA->getGlobal();
8385 if (Subtarget->isTargetELF()) {
8386 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8389 case TLSModel::GeneralDynamic:
8390 if (Subtarget->is64Bit())
8391 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8392 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8393 case TLSModel::LocalDynamic:
8394 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8395 Subtarget->is64Bit());
8396 case TLSModel::InitialExec:
8397 case TLSModel::LocalExec:
8398 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8399 Subtarget->is64Bit(),
8400 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8402 llvm_unreachable("Unknown TLS model.");
8405 if (Subtarget->isTargetDarwin()) {
8406 // Darwin only has one model of TLS. Lower to that.
8407 unsigned char OpFlag = 0;
8408 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8409 X86ISD::WrapperRIP : X86ISD::Wrapper;
8411 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8413 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8414 !Subtarget->is64Bit();
8416 OpFlag = X86II::MO_TLVP_PIC_BASE;
8418 OpFlag = X86II::MO_TLVP;
8420 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8421 GA->getValueType(0),
8422 GA->getOffset(), OpFlag);
8423 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8425 // With PIC32, the address is actually $g + Offset.
8427 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8428 DAG.getNode(X86ISD::GlobalBaseReg,
8429 SDLoc(), getPointerTy()),
8432 // Lowering the machine isd will make sure everything is in the right
8434 SDValue Chain = DAG.getEntryNode();
8435 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8436 SDValue Args[] = { Chain, Offset };
8437 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8439 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8440 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8441 MFI->setAdjustsStack(true);
8443 // And our return value (tls address) is in the standard call return value
8445 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8446 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8450 if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8451 // Just use the implicit TLS architecture
8452 // Need to generate someting similar to:
8453 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8455 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8456 // mov rcx, qword [rdx+rcx*8]
8457 // mov eax, .tls$:tlsvar
8458 // [rax+rcx] contains the address
8459 // Windows 64bit: gs:0x58
8460 // Windows 32bit: fs:__tls_array
8462 // If GV is an alias then use the aliasee for determining
8463 // thread-localness.
8464 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8465 GV = GA->resolveAliasedGlobal(false);
8467 SDValue Chain = DAG.getEntryNode();
8469 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8470 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8471 // use its literal value of 0x2C.
8472 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8473 ? Type::getInt8PtrTy(*DAG.getContext(),
8475 : Type::getInt32PtrTy(*DAG.getContext(),
8478 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8479 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8480 DAG.getExternalSymbol("_tls_array", getPointerTy()));
8482 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8483 MachinePointerInfo(Ptr),
8484 false, false, false, 0);
8486 // Load the _tls_index variable
8487 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8488 if (Subtarget->is64Bit())
8489 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8490 IDX, MachinePointerInfo(), MVT::i32,
8493 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8494 false, false, false, 0);
8496 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8498 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8500 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8501 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8502 false, false, false, 0);
8504 // Get the offset of start of .tls section
8505 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8506 GA->getValueType(0),
8507 GA->getOffset(), X86II::MO_SECREL);
8508 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8510 // The address of the thread local variable is the add of the thread
8511 // pointer with the offset of the variable.
8512 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8515 llvm_unreachable("TLS not implemented for this target.");
8518 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8519 /// and take a 2 x i32 value to shift plus a shift amount.
8520 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8521 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8522 MVT VT = Op.getSimpleValueType();
8523 unsigned VTBits = VT.getSizeInBits();
8525 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8526 SDValue ShOpLo = Op.getOperand(0);
8527 SDValue ShOpHi = Op.getOperand(1);
8528 SDValue ShAmt = Op.getOperand(2);
8529 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8530 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8532 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8533 DAG.getConstant(VTBits - 1, MVT::i8));
8534 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8535 DAG.getConstant(VTBits - 1, MVT::i8))
8536 : DAG.getConstant(0, VT);
8539 if (Op.getOpcode() == ISD::SHL_PARTS) {
8540 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8541 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8543 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8544 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8547 // If the shift amount is larger or equal than the width of a part we can't
8548 // rely on the results of shld/shrd. Insert a test and select the appropriate
8549 // values for large shift amounts.
8550 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8551 DAG.getConstant(VTBits, MVT::i8));
8552 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8553 AndNode, DAG.getConstant(0, MVT::i8));
8556 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8557 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8558 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8560 if (Op.getOpcode() == ISD::SHL_PARTS) {
8561 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8562 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8564 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8565 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8568 SDValue Ops[2] = { Lo, Hi };
8569 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8572 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8573 SelectionDAG &DAG) const {
8574 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8576 if (SrcVT.isVector())
8579 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8580 "Unknown SINT_TO_FP to lower!");
8582 // These are really Legal; return the operand so the caller accepts it as
8584 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8586 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8587 Subtarget->is64Bit()) {
8592 unsigned Size = SrcVT.getSizeInBits()/8;
8593 MachineFunction &MF = DAG.getMachineFunction();
8594 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8595 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8596 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8598 MachinePointerInfo::getFixedStack(SSFI),
8600 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8603 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8605 SelectionDAG &DAG) const {
8609 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8611 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8613 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8615 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8617 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8618 MachineMemOperand *MMO;
8620 int SSFI = FI->getIndex();
8622 DAG.getMachineFunction()
8623 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8624 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8626 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8627 StackSlot = StackSlot.getOperand(1);
8629 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8630 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8632 Tys, Ops, array_lengthof(Ops),
8636 Chain = Result.getValue(1);
8637 SDValue InFlag = Result.getValue(2);
8639 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8640 // shouldn't be necessary except that RFP cannot be live across
8641 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8642 MachineFunction &MF = DAG.getMachineFunction();
8643 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8644 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8645 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8646 Tys = DAG.getVTList(MVT::Other);
8648 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8650 MachineMemOperand *MMO =
8651 DAG.getMachineFunction()
8652 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8653 MachineMemOperand::MOStore, SSFISize, SSFISize);
8655 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8656 Ops, array_lengthof(Ops),
8657 Op.getValueType(), MMO);
8658 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8659 MachinePointerInfo::getFixedStack(SSFI),
8660 false, false, false, 0);
8666 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8667 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8668 SelectionDAG &DAG) const {
8669 // This algorithm is not obvious. Here it is what we're trying to output:
8672 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8673 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8677 pshufd $0x4e, %xmm0, %xmm1
8683 LLVMContext *Context = DAG.getContext();
8685 // Build some magic constants.
8686 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8687 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8688 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8690 SmallVector<Constant*,2> CV1;
8692 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8693 APInt(64, 0x4330000000000000ULL))));
8695 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8696 APInt(64, 0x4530000000000000ULL))));
8697 Constant *C1 = ConstantVector::get(CV1);
8698 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8700 // Load the 64-bit value into an XMM register.
8701 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8703 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8704 MachinePointerInfo::getConstantPool(),
8705 false, false, false, 16);
8706 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8707 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8710 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8711 MachinePointerInfo::getConstantPool(),
8712 false, false, false, 16);
8713 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8714 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8717 if (Subtarget->hasSSE3()) {
8718 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8719 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8721 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8722 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8724 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8725 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8729 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8730 DAG.getIntPtrConstant(0));
8733 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8734 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8735 SelectionDAG &DAG) const {
8737 // FP constant to bias correct the final result.
8738 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8741 // Load the 32-bit value into an XMM register.
8742 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8745 // Zero out the upper parts of the register.
8746 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8748 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8749 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8750 DAG.getIntPtrConstant(0));
8752 // Or the load with the bias.
8753 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8754 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8755 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8757 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8758 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8759 MVT::v2f64, Bias)));
8760 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8761 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8762 DAG.getIntPtrConstant(0));
8764 // Subtract the bias.
8765 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8767 // Handle final rounding.
8768 EVT DestVT = Op.getValueType();
8770 if (DestVT.bitsLT(MVT::f64))
8771 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8772 DAG.getIntPtrConstant(0));
8773 if (DestVT.bitsGT(MVT::f64))
8774 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8776 // Handle final rounding.
8780 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8781 SelectionDAG &DAG) const {
8782 SDValue N0 = Op.getOperand(0);
8783 MVT SVT = N0.getSimpleValueType();
8786 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8787 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8788 "Custom UINT_TO_FP is not supported!");
8790 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8791 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8792 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8795 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8796 SelectionDAG &DAG) const {
8797 SDValue N0 = Op.getOperand(0);
8800 if (Op.getValueType().isVector())
8801 return lowerUINT_TO_FP_vec(Op, DAG);
8803 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8804 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8805 // the optimization here.
8806 if (DAG.SignBitIsZero(N0))
8807 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8809 MVT SrcVT = N0.getSimpleValueType();
8810 MVT DstVT = Op.getSimpleValueType();
8811 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8812 return LowerUINT_TO_FP_i64(Op, DAG);
8813 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8814 return LowerUINT_TO_FP_i32(Op, DAG);
8815 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8818 // Make a 64-bit buffer, and use it to build an FILD.
8819 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8820 if (SrcVT == MVT::i32) {
8821 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8822 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8823 getPointerTy(), StackSlot, WordOff);
8824 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8825 StackSlot, MachinePointerInfo(),
8827 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8828 OffsetSlot, MachinePointerInfo(),
8830 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8834 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8835 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8836 StackSlot, MachinePointerInfo(),
8838 // For i64 source, we need to add the appropriate power of 2 if the input
8839 // was negative. This is the same as the optimization in
8840 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8841 // we must be careful to do the computation in x87 extended precision, not
8842 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8843 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8844 MachineMemOperand *MMO =
8845 DAG.getMachineFunction()
8846 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8847 MachineMemOperand::MOLoad, 8, 8);
8849 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8850 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8851 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8852 array_lengthof(Ops), MVT::i64, MMO);
8854 APInt FF(32, 0x5F800000ULL);
8856 // Check whether the sign bit is set.
8857 SDValue SignSet = DAG.getSetCC(dl,
8858 getSetCCResultType(*DAG.getContext(), MVT::i64),
8859 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8862 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8863 SDValue FudgePtr = DAG.getConstantPool(
8864 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8867 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8868 SDValue Zero = DAG.getIntPtrConstant(0);
8869 SDValue Four = DAG.getIntPtrConstant(4);
8870 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8872 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8874 // Load the value out, extending it from f32 to f80.
8875 // FIXME: Avoid the extend by constructing the right constant pool?
8876 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8877 FudgePtr, MachinePointerInfo::getConstantPool(),
8878 MVT::f32, false, false, 4);
8879 // Extend everything to 80 bits to force it to be done on x87.
8880 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8881 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8884 std::pair<SDValue,SDValue>
8885 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8886 bool IsSigned, bool IsReplace) const {
8889 EVT DstTy = Op.getValueType();
8891 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8892 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8896 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8897 DstTy.getSimpleVT() >= MVT::i16 &&
8898 "Unknown FP_TO_INT to lower!");
8900 // These are really Legal.
8901 if (DstTy == MVT::i32 &&
8902 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8903 return std::make_pair(SDValue(), SDValue());
8904 if (Subtarget->is64Bit() &&
8905 DstTy == MVT::i64 &&
8906 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8907 return std::make_pair(SDValue(), SDValue());
8909 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8910 // stack slot, or into the FTOL runtime function.
8911 MachineFunction &MF = DAG.getMachineFunction();
8912 unsigned MemSize = DstTy.getSizeInBits()/8;
8913 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8914 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8917 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8918 Opc = X86ISD::WIN_FTOL;
8920 switch (DstTy.getSimpleVT().SimpleTy) {
8921 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8922 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8923 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8924 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8927 SDValue Chain = DAG.getEntryNode();
8928 SDValue Value = Op.getOperand(0);
8929 EVT TheVT = Op.getOperand(0).getValueType();
8930 // FIXME This causes a redundant load/store if the SSE-class value is already
8931 // in memory, such as if it is on the callstack.
8932 if (isScalarFPTypeInSSEReg(TheVT)) {
8933 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8934 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8935 MachinePointerInfo::getFixedStack(SSFI),
8937 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8939 Chain, StackSlot, DAG.getValueType(TheVT)
8942 MachineMemOperand *MMO =
8943 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8944 MachineMemOperand::MOLoad, MemSize, MemSize);
8945 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8946 array_lengthof(Ops), DstTy, MMO);
8947 Chain = Value.getValue(1);
8948 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8949 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8952 MachineMemOperand *MMO =
8953 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8954 MachineMemOperand::MOStore, MemSize, MemSize);
8956 if (Opc != X86ISD::WIN_FTOL) {
8957 // Build the FP_TO_INT*_IN_MEM
8958 SDValue Ops[] = { Chain, Value, StackSlot };
8959 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8960 Ops, array_lengthof(Ops), DstTy,
8962 return std::make_pair(FIST, StackSlot);
8964 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8965 DAG.getVTList(MVT::Other, MVT::Glue),
8967 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8968 MVT::i32, ftol.getValue(1));
8969 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8970 MVT::i32, eax.getValue(2));
8971 SDValue Ops[] = { eax, edx };
8972 SDValue pair = IsReplace
8973 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8974 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8975 return std::make_pair(pair, SDValue());
8979 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8980 const X86Subtarget *Subtarget) {
8981 MVT VT = Op->getSimpleValueType(0);
8982 SDValue In = Op->getOperand(0);
8983 MVT InVT = In.getSimpleValueType();
8986 // Optimize vectors in AVX mode:
8989 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8990 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8991 // Concat upper and lower parts.
8994 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8995 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8996 // Concat upper and lower parts.
8999 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9000 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9001 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9004 if (Subtarget->hasInt256())
9005 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9007 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9008 SDValue Undef = DAG.getUNDEF(InVT);
9009 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9010 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9011 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9013 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9014 VT.getVectorNumElements()/2);
9016 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9017 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9019 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9022 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9023 SelectionDAG &DAG) {
9024 MVT VT = Op->getSimpleValueType(0);
9025 SDValue In = Op->getOperand(0);
9026 MVT InVT = In.getSimpleValueType();
9028 unsigned int NumElts = VT.getVectorNumElements();
9029 if (NumElts != 8 && NumElts != 16)
9032 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9033 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9035 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9036 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9037 // Now we have only mask extension
9038 assert(InVT.getVectorElementType() == MVT::i1);
9039 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9040 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9041 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9042 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9043 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9044 MachinePointerInfo::getConstantPool(),
9045 false, false, false, Alignment);
9047 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9048 if (VT.is512BitVector())
9050 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9053 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9054 SelectionDAG &DAG) {
9055 if (Subtarget->hasFp256()) {
9056 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9064 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9065 SelectionDAG &DAG) {
9067 MVT VT = Op.getSimpleValueType();
9068 SDValue In = Op.getOperand(0);
9069 MVT SVT = In.getSimpleValueType();
9071 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9072 return LowerZERO_EXTEND_AVX512(Op, DAG);
9074 if (Subtarget->hasFp256()) {
9075 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9080 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9081 VT.getVectorNumElements() != SVT.getVectorNumElements());
9085 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9087 MVT VT = Op.getSimpleValueType();
9088 SDValue In = Op.getOperand(0);
9089 MVT InVT = In.getSimpleValueType();
9091 if (VT == MVT::i1) {
9092 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9093 "Invalid scalar TRUNCATE operation");
9094 if (InVT == MVT::i32)
9096 if (InVT.getSizeInBits() == 64)
9097 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9098 else if (InVT.getSizeInBits() < 32)
9099 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9100 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9102 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9103 "Invalid TRUNCATE operation");
9105 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9106 if (VT.getVectorElementType().getSizeInBits() >=8)
9107 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9109 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9110 unsigned NumElts = InVT.getVectorNumElements();
9111 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9112 if (InVT.getSizeInBits() < 512) {
9113 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9114 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9118 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9119 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9120 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9121 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9122 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9123 MachinePointerInfo::getConstantPool(),
9124 false, false, false, Alignment);
9125 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9126 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9127 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9130 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9131 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9132 if (Subtarget->hasInt256()) {
9133 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9134 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9135 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9137 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9138 DAG.getIntPtrConstant(0));
9141 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9142 DAG.getIntPtrConstant(0));
9143 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9144 DAG.getIntPtrConstant(2));
9145 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9146 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9147 static const int ShufMask[] = {0, 2, 4, 6};
9148 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9151 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9152 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9153 if (Subtarget->hasInt256()) {
9154 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9156 SmallVector<SDValue,32> pshufbMask;
9157 for (unsigned i = 0; i < 2; ++i) {
9158 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9159 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9160 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9161 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9162 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9163 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9164 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9165 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9166 for (unsigned j = 0; j < 8; ++j)
9167 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9169 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9170 &pshufbMask[0], 32);
9171 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9172 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9174 static const int ShufMask[] = {0, 2, -1, -1};
9175 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9177 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9178 DAG.getIntPtrConstant(0));
9179 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9182 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9183 DAG.getIntPtrConstant(0));
9185 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9186 DAG.getIntPtrConstant(4));
9188 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9189 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9192 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9193 -1, -1, -1, -1, -1, -1, -1, -1};
9195 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9196 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9197 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9199 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9200 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9202 // The MOVLHPS Mask:
9203 static const int ShufMask2[] = {0, 1, 4, 5};
9204 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9205 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9208 // Handle truncation of V256 to V128 using shuffles.
9209 if (!VT.is128BitVector() || !InVT.is256BitVector())
9212 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9214 unsigned NumElems = VT.getVectorNumElements();
9215 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9217 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9218 // Prepare truncation shuffle mask
9219 for (unsigned i = 0; i != NumElems; ++i)
9221 SDValue V = DAG.getVectorShuffle(NVT, DL,
9222 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9223 DAG.getUNDEF(NVT), &MaskVec[0]);
9224 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9225 DAG.getIntPtrConstant(0));
9228 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9229 SelectionDAG &DAG) const {
9230 assert(!Op.getSimpleValueType().isVector());
9232 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9233 /*IsSigned=*/ true, /*IsReplace=*/ false);
9234 SDValue FIST = Vals.first, StackSlot = Vals.second;
9235 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9236 if (FIST.getNode() == 0) return Op;
9238 if (StackSlot.getNode())
9240 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9241 FIST, StackSlot, MachinePointerInfo(),
9242 false, false, false, 0);
9244 // The node is the result.
9248 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9249 SelectionDAG &DAG) const {
9250 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9251 /*IsSigned=*/ false, /*IsReplace=*/ false);
9252 SDValue FIST = Vals.first, StackSlot = Vals.second;
9253 assert(FIST.getNode() && "Unexpected failure");
9255 if (StackSlot.getNode())
9257 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9258 FIST, StackSlot, MachinePointerInfo(),
9259 false, false, false, 0);
9261 // The node is the result.
9265 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9267 MVT VT = Op.getSimpleValueType();
9268 SDValue In = Op.getOperand(0);
9269 MVT SVT = In.getSimpleValueType();
9271 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9273 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9274 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9275 In, DAG.getUNDEF(SVT)));
9278 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9279 LLVMContext *Context = DAG.getContext();
9281 MVT VT = Op.getSimpleValueType();
9283 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9284 if (VT.isVector()) {
9285 EltVT = VT.getVectorElementType();
9286 NumElts = VT.getVectorNumElements();
9289 if (EltVT == MVT::f64)
9290 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9291 APInt(64, ~(1ULL << 63))));
9293 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9294 APInt(32, ~(1U << 31))));
9295 C = ConstantVector::getSplat(NumElts, C);
9296 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9297 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9298 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9299 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9300 MachinePointerInfo::getConstantPool(),
9301 false, false, false, Alignment);
9302 if (VT.isVector()) {
9303 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9304 return DAG.getNode(ISD::BITCAST, dl, VT,
9305 DAG.getNode(ISD::AND, dl, ANDVT,
9306 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9308 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9310 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9313 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9314 LLVMContext *Context = DAG.getContext();
9316 MVT VT = Op.getSimpleValueType();
9318 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9319 if (VT.isVector()) {
9320 EltVT = VT.getVectorElementType();
9321 NumElts = VT.getVectorNumElements();
9324 if (EltVT == MVT::f64)
9325 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9326 APInt(64, 1ULL << 63)));
9328 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9329 APInt(32, 1U << 31)));
9330 C = ConstantVector::getSplat(NumElts, C);
9331 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9332 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9333 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9334 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9335 MachinePointerInfo::getConstantPool(),
9336 false, false, false, Alignment);
9337 if (VT.isVector()) {
9338 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9339 return DAG.getNode(ISD::BITCAST, dl, VT,
9340 DAG.getNode(ISD::XOR, dl, XORVT,
9341 DAG.getNode(ISD::BITCAST, dl, XORVT,
9343 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9346 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9349 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9350 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9351 LLVMContext *Context = DAG.getContext();
9352 SDValue Op0 = Op.getOperand(0);
9353 SDValue Op1 = Op.getOperand(1);
9355 MVT VT = Op.getSimpleValueType();
9356 MVT SrcVT = Op1.getSimpleValueType();
9358 // If second operand is smaller, extend it first.
9359 if (SrcVT.bitsLT(VT)) {
9360 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9363 // And if it is bigger, shrink it first.
9364 if (SrcVT.bitsGT(VT)) {
9365 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9369 // At this point the operands and the result should have the same
9370 // type, and that won't be f80 since that is not custom lowered.
9372 // First get the sign bit of second operand.
9373 SmallVector<Constant*,4> CV;
9374 if (SrcVT == MVT::f64) {
9375 const fltSemantics &Sem = APFloat::IEEEdouble;
9376 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9377 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9379 const fltSemantics &Sem = APFloat::IEEEsingle;
9380 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9381 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9382 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9383 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9385 Constant *C = ConstantVector::get(CV);
9386 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9387 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9388 MachinePointerInfo::getConstantPool(),
9389 false, false, false, 16);
9390 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9392 // Shift sign bit right or left if the two operands have different types.
9393 if (SrcVT.bitsGT(VT)) {
9394 // Op0 is MVT::f32, Op1 is MVT::f64.
9395 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9396 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9397 DAG.getConstant(32, MVT::i32));
9398 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9399 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9400 DAG.getIntPtrConstant(0));
9403 // Clear first operand sign bit.
9405 if (VT == MVT::f64) {
9406 const fltSemantics &Sem = APFloat::IEEEdouble;
9407 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9408 APInt(64, ~(1ULL << 63)))));
9409 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9411 const fltSemantics &Sem = APFloat::IEEEsingle;
9412 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9413 APInt(32, ~(1U << 31)))));
9414 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9415 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9416 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9418 C = ConstantVector::get(CV);
9419 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9420 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9421 MachinePointerInfo::getConstantPool(),
9422 false, false, false, 16);
9423 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9425 // Or the value with the sign bit.
9426 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9429 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9430 SDValue N0 = Op.getOperand(0);
9432 MVT VT = Op.getSimpleValueType();
9434 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9435 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9436 DAG.getConstant(1, VT));
9437 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9440 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9442 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9443 SelectionDAG &DAG) {
9444 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9446 if (!Subtarget->hasSSE41())
9449 if (!Op->hasOneUse())
9452 SDNode *N = Op.getNode();
9455 SmallVector<SDValue, 8> Opnds;
9456 DenseMap<SDValue, unsigned> VecInMap;
9457 EVT VT = MVT::Other;
9459 // Recognize a special case where a vector is casted into wide integer to
9461 Opnds.push_back(N->getOperand(0));
9462 Opnds.push_back(N->getOperand(1));
9464 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9465 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9466 // BFS traverse all OR'd operands.
9467 if (I->getOpcode() == ISD::OR) {
9468 Opnds.push_back(I->getOperand(0));
9469 Opnds.push_back(I->getOperand(1));
9470 // Re-evaluate the number of nodes to be traversed.
9471 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9475 // Quit if a non-EXTRACT_VECTOR_ELT
9476 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9479 // Quit if without a constant index.
9480 SDValue Idx = I->getOperand(1);
9481 if (!isa<ConstantSDNode>(Idx))
9484 SDValue ExtractedFromVec = I->getOperand(0);
9485 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9486 if (M == VecInMap.end()) {
9487 VT = ExtractedFromVec.getValueType();
9488 // Quit if not 128/256-bit vector.
9489 if (!VT.is128BitVector() && !VT.is256BitVector())
9491 // Quit if not the same type.
9492 if (VecInMap.begin() != VecInMap.end() &&
9493 VT != VecInMap.begin()->first.getValueType())
9495 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9497 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9500 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9501 "Not extracted from 128-/256-bit vector.");
9503 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9504 SmallVector<SDValue, 8> VecIns;
9506 for (DenseMap<SDValue, unsigned>::const_iterator
9507 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9508 // Quit if not all elements are used.
9509 if (I->second != FullMask)
9511 VecIns.push_back(I->first);
9514 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9516 // Cast all vectors into TestVT for PTEST.
9517 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9518 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9520 // If more than one full vectors are evaluated, OR them first before PTEST.
9521 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9522 // Each iteration will OR 2 nodes and append the result until there is only
9523 // 1 node left, i.e. the final OR'd value of all vectors.
9524 SDValue LHS = VecIns[Slot];
9525 SDValue RHS = VecIns[Slot + 1];
9526 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9529 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9530 VecIns.back(), VecIns.back());
9533 /// Emit nodes that will be selected as "test Op0,Op0", or something
9535 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9536 SelectionDAG &DAG) const {
9539 if (Op.getValueType() == MVT::i1)
9540 // KORTEST instruction should be selected
9541 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9542 DAG.getConstant(0, Op.getValueType()));
9544 // CF and OF aren't always set the way we want. Determine which
9545 // of these we need.
9546 bool NeedCF = false;
9547 bool NeedOF = false;
9550 case X86::COND_A: case X86::COND_AE:
9551 case X86::COND_B: case X86::COND_BE:
9554 case X86::COND_G: case X86::COND_GE:
9555 case X86::COND_L: case X86::COND_LE:
9556 case X86::COND_O: case X86::COND_NO:
9560 // See if we can use the EFLAGS value from the operand instead of
9561 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9562 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9563 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9564 // Emit a CMP with 0, which is the TEST pattern.
9565 //if (Op.getValueType() == MVT::i1)
9566 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9567 // DAG.getConstant(0, MVT::i1));
9568 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9569 DAG.getConstant(0, Op.getValueType()));
9571 unsigned Opcode = 0;
9572 unsigned NumOperands = 0;
9574 // Truncate operations may prevent the merge of the SETCC instruction
9575 // and the arithmetic instruction before it. Attempt to truncate the operands
9576 // of the arithmetic instruction and use a reduced bit-width instruction.
9577 bool NeedTruncation = false;
9578 SDValue ArithOp = Op;
9579 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9580 SDValue Arith = Op->getOperand(0);
9581 // Both the trunc and the arithmetic op need to have one user each.
9582 if (Arith->hasOneUse())
9583 switch (Arith.getOpcode()) {
9590 NeedTruncation = true;
9596 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9597 // which may be the result of a CAST. We use the variable 'Op', which is the
9598 // non-casted variable when we check for possible users.
9599 switch (ArithOp.getOpcode()) {
9601 // Due to an isel shortcoming, be conservative if this add is likely to be
9602 // selected as part of a load-modify-store instruction. When the root node
9603 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9604 // uses of other nodes in the match, such as the ADD in this case. This
9605 // leads to the ADD being left around and reselected, with the result being
9606 // two adds in the output. Alas, even if none our users are stores, that
9607 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9608 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9609 // climbing the DAG back to the root, and it doesn't seem to be worth the
9611 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9612 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9613 if (UI->getOpcode() != ISD::CopyToReg &&
9614 UI->getOpcode() != ISD::SETCC &&
9615 UI->getOpcode() != ISD::STORE)
9618 if (ConstantSDNode *C =
9619 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9620 // An add of one will be selected as an INC.
9621 if (C->getAPIntValue() == 1) {
9622 Opcode = X86ISD::INC;
9627 // An add of negative one (subtract of one) will be selected as a DEC.
9628 if (C->getAPIntValue().isAllOnesValue()) {
9629 Opcode = X86ISD::DEC;
9635 // Otherwise use a regular EFLAGS-setting add.
9636 Opcode = X86ISD::ADD;
9640 // If the primary and result isn't used, don't bother using X86ISD::AND,
9641 // because a TEST instruction will be better.
9642 bool NonFlagUse = false;
9643 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9644 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9646 unsigned UOpNo = UI.getOperandNo();
9647 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9648 // Look pass truncate.
9649 UOpNo = User->use_begin().getOperandNo();
9650 User = *User->use_begin();
9653 if (User->getOpcode() != ISD::BRCOND &&
9654 User->getOpcode() != ISD::SETCC &&
9655 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9668 // Due to the ISEL shortcoming noted above, be conservative if this op is
9669 // likely to be selected as part of a load-modify-store instruction.
9670 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9671 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9672 if (UI->getOpcode() == ISD::STORE)
9675 // Otherwise use a regular EFLAGS-setting instruction.
9676 switch (ArithOp.getOpcode()) {
9677 default: llvm_unreachable("unexpected operator!");
9678 case ISD::SUB: Opcode = X86ISD::SUB; break;
9679 case ISD::XOR: Opcode = X86ISD::XOR; break;
9680 case ISD::AND: Opcode = X86ISD::AND; break;
9682 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9683 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9684 if (EFLAGS.getNode())
9687 Opcode = X86ISD::OR;
9701 return SDValue(Op.getNode(), 1);
9707 // If we found that truncation is beneficial, perform the truncation and
9709 if (NeedTruncation) {
9710 EVT VT = Op.getValueType();
9711 SDValue WideVal = Op->getOperand(0);
9712 EVT WideVT = WideVal.getValueType();
9713 unsigned ConvertedOp = 0;
9714 // Use a target machine opcode to prevent further DAGCombine
9715 // optimizations that may separate the arithmetic operations
9716 // from the setcc node.
9717 switch (WideVal.getOpcode()) {
9719 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9720 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9721 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9722 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9723 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9727 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9728 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9729 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9730 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9731 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9737 // Emit a CMP with 0, which is the TEST pattern.
9738 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9739 DAG.getConstant(0, Op.getValueType()));
9741 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9742 SmallVector<SDValue, 4> Ops;
9743 for (unsigned i = 0; i != NumOperands; ++i)
9744 Ops.push_back(Op.getOperand(i));
9746 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9747 DAG.ReplaceAllUsesWith(Op, New);
9748 return SDValue(New.getNode(), 1);
9751 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9753 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9754 SelectionDAG &DAG) const {
9756 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9757 if (C->getAPIntValue() == 0)
9758 return EmitTest(Op0, X86CC, DAG);
9760 if (Op0.getValueType() == MVT::i1)
9761 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
9764 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9765 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9766 // Do the comparison at i32 if it's smaller. This avoids subregister
9767 // aliasing issues. Keep the smaller reference if we're optimizing for
9768 // size, however, as that'll allow better folding of memory operations.
9769 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9770 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9771 AttributeSet::FunctionIndex, Attribute::MinSize)) {
9773 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9774 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9775 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9777 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9778 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9779 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9781 return SDValue(Sub.getNode(), 1);
9783 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9786 /// Convert a comparison if required by the subtarget.
9787 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9788 SelectionDAG &DAG) const {
9789 // If the subtarget does not support the FUCOMI instruction, floating-point
9790 // comparisons have to be converted.
9791 if (Subtarget->hasCMov() ||
9792 Cmp.getOpcode() != X86ISD::CMP ||
9793 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9794 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9797 // The instruction selector will select an FUCOM instruction instead of
9798 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9799 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9800 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9802 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9803 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9804 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9805 DAG.getConstant(8, MVT::i8));
9806 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9807 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9810 static bool isAllOnes(SDValue V) {
9811 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9812 return C && C->isAllOnesValue();
9815 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9816 /// if it's possible.
9817 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9818 SDLoc dl, SelectionDAG &DAG) const {
9819 SDValue Op0 = And.getOperand(0);
9820 SDValue Op1 = And.getOperand(1);
9821 if (Op0.getOpcode() == ISD::TRUNCATE)
9822 Op0 = Op0.getOperand(0);
9823 if (Op1.getOpcode() == ISD::TRUNCATE)
9824 Op1 = Op1.getOperand(0);
9827 if (Op1.getOpcode() == ISD::SHL)
9828 std::swap(Op0, Op1);
9829 if (Op0.getOpcode() == ISD::SHL) {
9830 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9831 if (And00C->getZExtValue() == 1) {
9832 // If we looked past a truncate, check that it's only truncating away
9834 unsigned BitWidth = Op0.getValueSizeInBits();
9835 unsigned AndBitWidth = And.getValueSizeInBits();
9836 if (BitWidth > AndBitWidth) {
9838 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9839 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9843 RHS = Op0.getOperand(1);
9845 } else if (Op1.getOpcode() == ISD::Constant) {
9846 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9847 uint64_t AndRHSVal = AndRHS->getZExtValue();
9848 SDValue AndLHS = Op0;
9850 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9851 LHS = AndLHS.getOperand(0);
9852 RHS = AndLHS.getOperand(1);
9855 // Use BT if the immediate can't be encoded in a TEST instruction.
9856 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9858 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9862 if (LHS.getNode()) {
9863 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9864 // instruction. Since the shift amount is in-range-or-undefined, we know
9865 // that doing a bittest on the i32 value is ok. We extend to i32 because
9866 // the encoding for the i16 version is larger than the i32 version.
9867 // Also promote i16 to i32 for performance / code size reason.
9868 if (LHS.getValueType() == MVT::i8 ||
9869 LHS.getValueType() == MVT::i16)
9870 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9872 // If the operand types disagree, extend the shift amount to match. Since
9873 // BT ignores high bits (like shifts) we can use anyextend.
9874 if (LHS.getValueType() != RHS.getValueType())
9875 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9877 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9878 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9879 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9880 DAG.getConstant(Cond, MVT::i8), BT);
9886 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9888 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9893 // SSE Condition code mapping:
9902 switch (SetCCOpcode) {
9903 default: llvm_unreachable("Unexpected SETCC condition");
9905 case ISD::SETEQ: SSECC = 0; break;
9907 case ISD::SETGT: Swap = true; // Fallthrough
9909 case ISD::SETOLT: SSECC = 1; break;
9911 case ISD::SETGE: Swap = true; // Fallthrough
9913 case ISD::SETOLE: SSECC = 2; break;
9914 case ISD::SETUO: SSECC = 3; break;
9916 case ISD::SETNE: SSECC = 4; break;
9917 case ISD::SETULE: Swap = true; // Fallthrough
9918 case ISD::SETUGE: SSECC = 5; break;
9919 case ISD::SETULT: Swap = true; // Fallthrough
9920 case ISD::SETUGT: SSECC = 6; break;
9921 case ISD::SETO: SSECC = 7; break;
9923 case ISD::SETONE: SSECC = 8; break;
9926 std::swap(Op0, Op1);
9931 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9932 // ones, and then concatenate the result back.
9933 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9934 MVT VT = Op.getSimpleValueType();
9936 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9937 "Unsupported value type for operation");
9939 unsigned NumElems = VT.getVectorNumElements();
9941 SDValue CC = Op.getOperand(2);
9943 // Extract the LHS vectors
9944 SDValue LHS = Op.getOperand(0);
9945 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9946 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9948 // Extract the RHS vectors
9949 SDValue RHS = Op.getOperand(1);
9950 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9951 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9953 // Issue the operation on the smaller types and concatenate the result back
9954 MVT EltVT = VT.getVectorElementType();
9955 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9956 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9957 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9958 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9961 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
9962 const X86Subtarget *Subtarget) {
9963 SDValue Op0 = Op.getOperand(0);
9964 SDValue Op1 = Op.getOperand(1);
9965 SDValue CC = Op.getOperand(2);
9966 MVT VT = Op.getSimpleValueType();
9969 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9970 Op.getValueType().getScalarType() == MVT::i1 &&
9971 "Cannot set masked compare for this operation");
9973 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9975 bool Unsigned = false;
9978 switch (SetCCOpcode) {
9979 default: llvm_unreachable("Unexpected SETCC condition");
9980 case ISD::SETNE: SSECC = 4; break;
9981 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
9982 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
9983 case ISD::SETLT: Swap = true; //fall-through
9984 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
9985 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
9986 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
9987 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
9988 case ISD::SETULE: Unsigned = true; //fall-through
9989 case ISD::SETLE: SSECC = 2; break;
9993 std::swap(Op0, Op1);
9995 return DAG.getNode(Opc, dl, VT, Op0, Op1);
9996 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
9997 return DAG.getNode(Opc, dl, VT, Op0, Op1,
9998 DAG.getConstant(SSECC, MVT::i8));
10001 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10002 /// operand \p Op1. If non-trivial (for example because it's not constant)
10003 /// return an empty value.
10004 static SDValue ChangeVSETULTtoVSETULE(SDValue Op1, SelectionDAG &DAG)
10006 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10010 MVT VT = Op1.getSimpleValueType();
10011 MVT EVT = VT.getVectorElementType();
10012 unsigned n = VT.getVectorNumElements();
10013 SmallVector<SDValue, 8> ULTOp1;
10015 for (unsigned i = 0; i < n; ++i) {
10016 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10017 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10020 // Avoid underflow.
10021 APInt Val = Elt->getAPIntValue();
10025 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10028 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op1), VT, ULTOp1.data(),
10032 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10033 SelectionDAG &DAG) {
10034 SDValue Op0 = Op.getOperand(0);
10035 SDValue Op1 = Op.getOperand(1);
10036 SDValue CC = Op.getOperand(2);
10037 MVT VT = Op.getSimpleValueType();
10038 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10039 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10044 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10045 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10048 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10049 unsigned Opc = X86ISD::CMPP;
10050 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10051 assert(VT.getVectorNumElements() <= 16);
10052 Opc = X86ISD::CMPM;
10054 // In the two special cases we can't handle, emit two comparisons.
10057 unsigned CombineOpc;
10058 if (SetCCOpcode == ISD::SETUEQ) {
10059 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10061 assert(SetCCOpcode == ISD::SETONE);
10062 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10065 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10066 DAG.getConstant(CC0, MVT::i8));
10067 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10068 DAG.getConstant(CC1, MVT::i8));
10069 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10071 // Handle all other FP comparisons here.
10072 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10073 DAG.getConstant(SSECC, MVT::i8));
10076 // Break 256-bit integer vector compare into smaller ones.
10077 if (VT.is256BitVector() && !Subtarget->hasInt256())
10078 return Lower256IntVSETCC(Op, DAG);
10080 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10081 EVT OpVT = Op1.getValueType();
10082 if (Subtarget->hasAVX512()) {
10083 if (Op1.getValueType().is512BitVector() ||
10084 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10085 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10087 // In AVX-512 architecture setcc returns mask with i1 elements,
10088 // But there is no compare instruction for i8 and i16 elements.
10089 // We are not talking about 512-bit operands in this case, these
10090 // types are illegal.
10092 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10093 OpVT.getVectorElementType().getSizeInBits() >= 8))
10094 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10095 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10098 // We are handling one of the integer comparisons here. Since SSE only has
10099 // GT and EQ comparisons for integer, swapping operands and multiple
10100 // operations may be required for some comparisons.
10102 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10103 bool Subus = false;
10105 switch (SetCCOpcode) {
10106 default: llvm_unreachable("Unexpected SETCC condition");
10107 case ISD::SETNE: Invert = true;
10108 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10109 case ISD::SETLT: Swap = true;
10110 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10111 case ISD::SETGE: Swap = true;
10112 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10113 Invert = true; break;
10114 case ISD::SETULT: Swap = true;
10115 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10116 FlipSigns = true; break;
10117 case ISD::SETUGE: Swap = true;
10118 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10119 FlipSigns = true; Invert = true; break;
10122 // Special case: Use min/max operations for SETULE/SETUGE
10123 MVT VET = VT.getVectorElementType();
10125 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10126 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10129 switch (SetCCOpcode) {
10131 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10132 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10135 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10138 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10139 if (!MinMax && hasSubus) {
10140 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10142 // t = psubus Op0, Op1
10143 // pcmpeq t, <0..0>
10144 switch (SetCCOpcode) {
10146 case ISD::SETULT: {
10147 // If the comparison is against a constant we can turn this into a
10148 // setule. With psubus, setule does not require a swap. This is
10149 // beneficial because the constant in the register is no longer
10150 // destructed as the destination so it can be hoisted out of a loop.
10151 // Only do this pre-AVX since vpcmp* is no longer destructive.
10152 if (Subtarget->hasAVX())
10154 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(Op1, DAG);
10155 if (ULEOp1.getNode()) {
10157 Subus = true; Invert = false; Swap = false;
10161 // Psubus is better than flip-sign because it requires no inversion.
10162 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10163 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10167 Opc = X86ISD::SUBUS;
10173 std::swap(Op0, Op1);
10175 // Check that the operation in question is available (most are plain SSE2,
10176 // but PCMPGTQ and PCMPEQQ have different requirements).
10177 if (VT == MVT::v2i64) {
10178 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10179 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10181 // First cast everything to the right type.
10182 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10183 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10185 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10186 // bits of the inputs before performing those operations. The lower
10187 // compare is always unsigned.
10190 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10192 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10193 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10194 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10195 Sign, Zero, Sign, Zero);
10197 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10198 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10200 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10201 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10202 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10204 // Create masks for only the low parts/high parts of the 64 bit integers.
10205 static const int MaskHi[] = { 1, 1, 3, 3 };
10206 static const int MaskLo[] = { 0, 0, 2, 2 };
10207 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10208 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10209 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10211 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10212 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10215 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10217 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10220 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10221 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10222 // pcmpeqd + pshufd + pand.
10223 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10225 // First cast everything to the right type.
10226 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10227 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10230 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10232 // Make sure the lower and upper halves are both all-ones.
10233 static const int Mask[] = { 1, 0, 3, 2 };
10234 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10235 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10238 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10240 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10244 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10245 // bits of the inputs before performing those operations.
10247 EVT EltVT = VT.getVectorElementType();
10248 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10249 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10250 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10253 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10255 // If the logical-not of the result is required, perform that now.
10257 Result = DAG.getNOT(dl, Result, VT);
10260 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10263 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10264 getZeroVector(VT, Subtarget, DAG, dl));
10269 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10271 MVT VT = Op.getSimpleValueType();
10273 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10275 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10276 && "SetCC type must be 8-bit or 1-bit integer");
10277 SDValue Op0 = Op.getOperand(0);
10278 SDValue Op1 = Op.getOperand(1);
10280 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10282 // Optimize to BT if possible.
10283 // Lower (X & (1 << N)) == 0 to BT(X, N).
10284 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10285 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10286 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10287 Op1.getOpcode() == ISD::Constant &&
10288 cast<ConstantSDNode>(Op1)->isNullValue() &&
10289 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10290 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10291 if (NewSetCC.getNode())
10295 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10297 if (Op1.getOpcode() == ISD::Constant &&
10298 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10299 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10300 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10302 // If the input is a setcc, then reuse the input setcc or use a new one with
10303 // the inverted condition.
10304 if (Op0.getOpcode() == X86ISD::SETCC) {
10305 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10306 bool Invert = (CC == ISD::SETNE) ^
10307 cast<ConstantSDNode>(Op1)->isNullValue();
10311 CCode = X86::GetOppositeBranchCondition(CCode);
10312 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10313 DAG.getConstant(CCode, MVT::i8),
10314 Op0.getOperand(1));
10316 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10320 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10321 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10322 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10324 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10325 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10328 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10329 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10330 if (X86CC == X86::COND_INVALID)
10333 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10334 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10335 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10336 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10338 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10342 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10343 static bool isX86LogicalCmp(SDValue Op) {
10344 unsigned Opc = Op.getNode()->getOpcode();
10345 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10346 Opc == X86ISD::SAHF)
10348 if (Op.getResNo() == 1 &&
10349 (Opc == X86ISD::ADD ||
10350 Opc == X86ISD::SUB ||
10351 Opc == X86ISD::ADC ||
10352 Opc == X86ISD::SBB ||
10353 Opc == X86ISD::SMUL ||
10354 Opc == X86ISD::UMUL ||
10355 Opc == X86ISD::INC ||
10356 Opc == X86ISD::DEC ||
10357 Opc == X86ISD::OR ||
10358 Opc == X86ISD::XOR ||
10359 Opc == X86ISD::AND))
10362 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10368 static bool isZero(SDValue V) {
10369 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10370 return C && C->isNullValue();
10373 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10374 if (V.getOpcode() != ISD::TRUNCATE)
10377 SDValue VOp0 = V.getOperand(0);
10378 unsigned InBits = VOp0.getValueSizeInBits();
10379 unsigned Bits = V.getValueSizeInBits();
10380 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10383 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10384 bool addTest = true;
10385 SDValue Cond = Op.getOperand(0);
10386 SDValue Op1 = Op.getOperand(1);
10387 SDValue Op2 = Op.getOperand(2);
10389 EVT VT = Op1.getValueType();
10392 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10393 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10394 // sequence later on.
10395 if (Cond.getOpcode() == ISD::SETCC &&
10396 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10397 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10398 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10399 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10400 int SSECC = translateX86FSETCC(
10401 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10404 if (Subtarget->hasAVX512()) {
10405 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10406 DAG.getConstant(SSECC, MVT::i8));
10407 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10409 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10410 DAG.getConstant(SSECC, MVT::i8));
10411 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10412 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10413 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10417 if (Cond.getOpcode() == ISD::SETCC) {
10418 SDValue NewCond = LowerSETCC(Cond, DAG);
10419 if (NewCond.getNode())
10423 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10424 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10425 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10426 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10427 if (Cond.getOpcode() == X86ISD::SETCC &&
10428 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10429 isZero(Cond.getOperand(1).getOperand(1))) {
10430 SDValue Cmp = Cond.getOperand(1);
10432 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10434 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10435 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10436 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10438 SDValue CmpOp0 = Cmp.getOperand(0);
10439 // Apply further optimizations for special cases
10440 // (select (x != 0), -1, 0) -> neg & sbb
10441 // (select (x == 0), 0, -1) -> neg & sbb
10442 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10443 if (YC->isNullValue() &&
10444 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10445 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10446 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10447 DAG.getConstant(0, CmpOp0.getValueType()),
10449 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10450 DAG.getConstant(X86::COND_B, MVT::i8),
10451 SDValue(Neg.getNode(), 1));
10455 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10456 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10457 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10459 SDValue Res = // Res = 0 or -1.
10460 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10461 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10463 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10464 Res = DAG.getNOT(DL, Res, Res.getValueType());
10466 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10467 if (N2C == 0 || !N2C->isNullValue())
10468 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10473 // Look past (and (setcc_carry (cmp ...)), 1).
10474 if (Cond.getOpcode() == ISD::AND &&
10475 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10476 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10477 if (C && C->getAPIntValue() == 1)
10478 Cond = Cond.getOperand(0);
10481 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10482 // setting operand in place of the X86ISD::SETCC.
10483 unsigned CondOpcode = Cond.getOpcode();
10484 if (CondOpcode == X86ISD::SETCC ||
10485 CondOpcode == X86ISD::SETCC_CARRY) {
10486 CC = Cond.getOperand(0);
10488 SDValue Cmp = Cond.getOperand(1);
10489 unsigned Opc = Cmp.getOpcode();
10490 MVT VT = Op.getSimpleValueType();
10492 bool IllegalFPCMov = false;
10493 if (VT.isFloatingPoint() && !VT.isVector() &&
10494 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10495 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10497 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10498 Opc == X86ISD::BT) { // FIXME
10502 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10503 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10504 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10505 Cond.getOperand(0).getValueType() != MVT::i8)) {
10506 SDValue LHS = Cond.getOperand(0);
10507 SDValue RHS = Cond.getOperand(1);
10508 unsigned X86Opcode;
10511 switch (CondOpcode) {
10512 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10513 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10514 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10515 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10516 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10517 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10518 default: llvm_unreachable("unexpected overflowing operator");
10520 if (CondOpcode == ISD::UMULO)
10521 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10524 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10526 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10528 if (CondOpcode == ISD::UMULO)
10529 Cond = X86Op.getValue(2);
10531 Cond = X86Op.getValue(1);
10533 CC = DAG.getConstant(X86Cond, MVT::i8);
10538 // Look pass the truncate if the high bits are known zero.
10539 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10540 Cond = Cond.getOperand(0);
10542 // We know the result of AND is compared against zero. Try to match
10544 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10545 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10546 if (NewSetCC.getNode()) {
10547 CC = NewSetCC.getOperand(0);
10548 Cond = NewSetCC.getOperand(1);
10555 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10556 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10559 // a < b ? -1 : 0 -> RES = ~setcc_carry
10560 // a < b ? 0 : -1 -> RES = setcc_carry
10561 // a >= b ? -1 : 0 -> RES = setcc_carry
10562 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10563 if (Cond.getOpcode() == X86ISD::SUB) {
10564 Cond = ConvertCmpIfNecessary(Cond, DAG);
10565 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10567 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10568 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10569 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10570 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10571 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10572 return DAG.getNOT(DL, Res, Res.getValueType());
10577 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10578 // widen the cmov and push the truncate through. This avoids introducing a new
10579 // branch during isel and doesn't add any extensions.
10580 if (Op.getValueType() == MVT::i8 &&
10581 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10582 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10583 if (T1.getValueType() == T2.getValueType() &&
10584 // Blacklist CopyFromReg to avoid partial register stalls.
10585 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10586 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10587 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10588 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10592 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10593 // condition is true.
10594 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10595 SDValue Ops[] = { Op2, Op1, CC, Cond };
10596 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10599 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10600 MVT VT = Op->getSimpleValueType(0);
10601 SDValue In = Op->getOperand(0);
10602 MVT InVT = In.getSimpleValueType();
10605 unsigned int NumElts = VT.getVectorNumElements();
10606 if (NumElts != 8 && NumElts != 16)
10609 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10610 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10612 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10613 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10615 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10616 Constant *C = ConstantInt::get(*DAG.getContext(),
10617 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10619 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10620 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10621 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10622 MachinePointerInfo::getConstantPool(),
10623 false, false, false, Alignment);
10624 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10625 if (VT.is512BitVector())
10627 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10630 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10631 SelectionDAG &DAG) {
10632 MVT VT = Op->getSimpleValueType(0);
10633 SDValue In = Op->getOperand(0);
10634 MVT InVT = In.getSimpleValueType();
10637 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10638 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10640 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10641 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10642 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10645 if (Subtarget->hasInt256())
10646 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10648 // Optimize vectors in AVX mode
10649 // Sign extend v8i16 to v8i32 and
10652 // Divide input vector into two parts
10653 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10654 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10655 // concat the vectors to original VT
10657 unsigned NumElems = InVT.getVectorNumElements();
10658 SDValue Undef = DAG.getUNDEF(InVT);
10660 SmallVector<int,8> ShufMask1(NumElems, -1);
10661 for (unsigned i = 0; i != NumElems/2; ++i)
10664 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10666 SmallVector<int,8> ShufMask2(NumElems, -1);
10667 for (unsigned i = 0; i != NumElems/2; ++i)
10668 ShufMask2[i] = i + NumElems/2;
10670 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10672 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10673 VT.getVectorNumElements()/2);
10675 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10676 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10678 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10681 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10682 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10683 // from the AND / OR.
10684 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10685 Opc = Op.getOpcode();
10686 if (Opc != ISD::OR && Opc != ISD::AND)
10688 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10689 Op.getOperand(0).hasOneUse() &&
10690 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10691 Op.getOperand(1).hasOneUse());
10694 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10695 // 1 and that the SETCC node has a single use.
10696 static bool isXor1OfSetCC(SDValue Op) {
10697 if (Op.getOpcode() != ISD::XOR)
10699 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10700 if (N1C && N1C->getAPIntValue() == 1) {
10701 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10702 Op.getOperand(0).hasOneUse();
10707 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10708 bool addTest = true;
10709 SDValue Chain = Op.getOperand(0);
10710 SDValue Cond = Op.getOperand(1);
10711 SDValue Dest = Op.getOperand(2);
10714 bool Inverted = false;
10716 if (Cond.getOpcode() == ISD::SETCC) {
10717 // Check for setcc([su]{add,sub,mul}o == 0).
10718 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10719 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10720 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10721 Cond.getOperand(0).getResNo() == 1 &&
10722 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10723 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10724 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10725 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10726 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10727 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10729 Cond = Cond.getOperand(0);
10731 SDValue NewCond = LowerSETCC(Cond, DAG);
10732 if (NewCond.getNode())
10737 // FIXME: LowerXALUO doesn't handle these!!
10738 else if (Cond.getOpcode() == X86ISD::ADD ||
10739 Cond.getOpcode() == X86ISD::SUB ||
10740 Cond.getOpcode() == X86ISD::SMUL ||
10741 Cond.getOpcode() == X86ISD::UMUL)
10742 Cond = LowerXALUO(Cond, DAG);
10745 // Look pass (and (setcc_carry (cmp ...)), 1).
10746 if (Cond.getOpcode() == ISD::AND &&
10747 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10748 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10749 if (C && C->getAPIntValue() == 1)
10750 Cond = Cond.getOperand(0);
10753 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10754 // setting operand in place of the X86ISD::SETCC.
10755 unsigned CondOpcode = Cond.getOpcode();
10756 if (CondOpcode == X86ISD::SETCC ||
10757 CondOpcode == X86ISD::SETCC_CARRY) {
10758 CC = Cond.getOperand(0);
10760 SDValue Cmp = Cond.getOperand(1);
10761 unsigned Opc = Cmp.getOpcode();
10762 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10763 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10767 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10771 // These can only come from an arithmetic instruction with overflow,
10772 // e.g. SADDO, UADDO.
10773 Cond = Cond.getNode()->getOperand(1);
10779 CondOpcode = Cond.getOpcode();
10780 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10781 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10782 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10783 Cond.getOperand(0).getValueType() != MVT::i8)) {
10784 SDValue LHS = Cond.getOperand(0);
10785 SDValue RHS = Cond.getOperand(1);
10786 unsigned X86Opcode;
10789 // Keep this in sync with LowerXALUO, otherwise we might create redundant
10790 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10792 switch (CondOpcode) {
10793 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10795 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10797 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10800 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10801 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10803 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10805 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10808 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10809 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10810 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10811 default: llvm_unreachable("unexpected overflowing operator");
10814 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10815 if (CondOpcode == ISD::UMULO)
10816 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10819 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10821 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10823 if (CondOpcode == ISD::UMULO)
10824 Cond = X86Op.getValue(2);
10826 Cond = X86Op.getValue(1);
10828 CC = DAG.getConstant(X86Cond, MVT::i8);
10832 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10833 SDValue Cmp = Cond.getOperand(0).getOperand(1);
10834 if (CondOpc == ISD::OR) {
10835 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10836 // two branches instead of an explicit OR instruction with a
10838 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10839 isX86LogicalCmp(Cmp)) {
10840 CC = Cond.getOperand(0).getOperand(0);
10841 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10842 Chain, Dest, CC, Cmp);
10843 CC = Cond.getOperand(1).getOperand(0);
10847 } else { // ISD::AND
10848 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10849 // two branches instead of an explicit AND instruction with a
10850 // separate test. However, we only do this if this block doesn't
10851 // have a fall-through edge, because this requires an explicit
10852 // jmp when the condition is false.
10853 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10854 isX86LogicalCmp(Cmp) &&
10855 Op.getNode()->hasOneUse()) {
10856 X86::CondCode CCode =
10857 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10858 CCode = X86::GetOppositeBranchCondition(CCode);
10859 CC = DAG.getConstant(CCode, MVT::i8);
10860 SDNode *User = *Op.getNode()->use_begin();
10861 // Look for an unconditional branch following this conditional branch.
10862 // We need this because we need to reverse the successors in order
10863 // to implement FCMP_OEQ.
10864 if (User->getOpcode() == ISD::BR) {
10865 SDValue FalseBB = User->getOperand(1);
10867 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10868 assert(NewBR == User);
10872 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10873 Chain, Dest, CC, Cmp);
10874 X86::CondCode CCode =
10875 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10876 CCode = X86::GetOppositeBranchCondition(CCode);
10877 CC = DAG.getConstant(CCode, MVT::i8);
10883 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10884 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10885 // It should be transformed during dag combiner except when the condition
10886 // is set by a arithmetics with overflow node.
10887 X86::CondCode CCode =
10888 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10889 CCode = X86::GetOppositeBranchCondition(CCode);
10890 CC = DAG.getConstant(CCode, MVT::i8);
10891 Cond = Cond.getOperand(0).getOperand(1);
10893 } else if (Cond.getOpcode() == ISD::SETCC &&
10894 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10895 // For FCMP_OEQ, we can emit
10896 // two branches instead of an explicit AND instruction with a
10897 // separate test. However, we only do this if this block doesn't
10898 // have a fall-through edge, because this requires an explicit
10899 // jmp when the condition is false.
10900 if (Op.getNode()->hasOneUse()) {
10901 SDNode *User = *Op.getNode()->use_begin();
10902 // Look for an unconditional branch following this conditional branch.
10903 // We need this because we need to reverse the successors in order
10904 // to implement FCMP_OEQ.
10905 if (User->getOpcode() == ISD::BR) {
10906 SDValue FalseBB = User->getOperand(1);
10908 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10909 assert(NewBR == User);
10913 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10914 Cond.getOperand(0), Cond.getOperand(1));
10915 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10916 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10917 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10918 Chain, Dest, CC, Cmp);
10919 CC = DAG.getConstant(X86::COND_P, MVT::i8);
10924 } else if (Cond.getOpcode() == ISD::SETCC &&
10925 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10926 // For FCMP_UNE, we can emit
10927 // two branches instead of an explicit AND instruction with a
10928 // separate test. However, we only do this if this block doesn't
10929 // have a fall-through edge, because this requires an explicit
10930 // jmp when the condition is false.
10931 if (Op.getNode()->hasOneUse()) {
10932 SDNode *User = *Op.getNode()->use_begin();
10933 // Look for an unconditional branch following this conditional branch.
10934 // We need this because we need to reverse the successors in order
10935 // to implement FCMP_UNE.
10936 if (User->getOpcode() == ISD::BR) {
10937 SDValue FalseBB = User->getOperand(1);
10939 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10940 assert(NewBR == User);
10943 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10944 Cond.getOperand(0), Cond.getOperand(1));
10945 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10946 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10947 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10948 Chain, Dest, CC, Cmp);
10949 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10959 // Look pass the truncate if the high bits are known zero.
10960 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10961 Cond = Cond.getOperand(0);
10963 // We know the result of AND is compared against zero. Try to match
10965 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10966 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10967 if (NewSetCC.getNode()) {
10968 CC = NewSetCC.getOperand(0);
10969 Cond = NewSetCC.getOperand(1);
10976 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10977 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10979 Cond = ConvertCmpIfNecessary(Cond, DAG);
10980 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10981 Chain, Dest, CC, Cond);
10984 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10985 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10986 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10987 // that the guard pages used by the OS virtual memory manager are allocated in
10988 // correct sequence.
10990 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10991 SelectionDAG &DAG) const {
10992 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10993 getTargetMachine().Options.EnableSegmentedStacks) &&
10994 "This should be used only on Windows targets or when segmented stacks "
10996 assert(!Subtarget->isTargetMacho() && "Not implemented");
11000 SDValue Chain = Op.getOperand(0);
11001 SDValue Size = Op.getOperand(1);
11002 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11003 EVT VT = Op.getNode()->getValueType(0);
11005 bool Is64Bit = Subtarget->is64Bit();
11006 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11008 if (getTargetMachine().Options.EnableSegmentedStacks) {
11009 MachineFunction &MF = DAG.getMachineFunction();
11010 MachineRegisterInfo &MRI = MF.getRegInfo();
11013 // The 64 bit implementation of segmented stacks needs to clobber both r10
11014 // r11. This makes it impossible to use it along with nested parameters.
11015 const Function *F = MF.getFunction();
11017 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11019 if (I->hasNestAttr())
11020 report_fatal_error("Cannot use segmented stacks with functions that "
11021 "have nested arguments.");
11024 const TargetRegisterClass *AddrRegClass =
11025 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11026 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11027 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11028 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11029 DAG.getRegister(Vreg, SPTy));
11030 SDValue Ops1[2] = { Value, Chain };
11031 return DAG.getMergeValues(Ops1, 2, dl);
11034 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11036 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11037 Flag = Chain.getValue(1);
11038 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11040 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11042 const X86RegisterInfo *RegInfo =
11043 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11044 unsigned SPReg = RegInfo->getStackRegister();
11045 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11046 Chain = SP.getValue(1);
11049 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11050 DAG.getConstant(-(uint64_t)Align, VT));
11051 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11054 SDValue Ops1[2] = { SP, Chain };
11055 return DAG.getMergeValues(Ops1, 2, dl);
11059 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11060 MachineFunction &MF = DAG.getMachineFunction();
11061 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11063 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11066 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11067 // vastart just stores the address of the VarArgsFrameIndex slot into the
11068 // memory location argument.
11069 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11071 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11072 MachinePointerInfo(SV), false, false, 0);
11076 // gp_offset (0 - 6 * 8)
11077 // fp_offset (48 - 48 + 8 * 16)
11078 // overflow_arg_area (point to parameters coming in memory).
11080 SmallVector<SDValue, 8> MemOps;
11081 SDValue FIN = Op.getOperand(1);
11083 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11084 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11086 FIN, MachinePointerInfo(SV), false, false, 0);
11087 MemOps.push_back(Store);
11090 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11091 FIN, DAG.getIntPtrConstant(4));
11092 Store = DAG.getStore(Op.getOperand(0), DL,
11093 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11095 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11096 MemOps.push_back(Store);
11098 // Store ptr to overflow_arg_area
11099 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11100 FIN, DAG.getIntPtrConstant(4));
11101 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11103 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11104 MachinePointerInfo(SV, 8),
11106 MemOps.push_back(Store);
11108 // Store ptr to reg_save_area.
11109 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11110 FIN, DAG.getIntPtrConstant(8));
11111 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11113 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11114 MachinePointerInfo(SV, 16), false, false, 0);
11115 MemOps.push_back(Store);
11116 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11117 &MemOps[0], MemOps.size());
11120 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11121 assert(Subtarget->is64Bit() &&
11122 "LowerVAARG only handles 64-bit va_arg!");
11123 assert((Subtarget->isTargetLinux() ||
11124 Subtarget->isTargetDarwin()) &&
11125 "Unhandled target in LowerVAARG");
11126 assert(Op.getNode()->getNumOperands() == 4);
11127 SDValue Chain = Op.getOperand(0);
11128 SDValue SrcPtr = Op.getOperand(1);
11129 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11130 unsigned Align = Op.getConstantOperandVal(3);
11133 EVT ArgVT = Op.getNode()->getValueType(0);
11134 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11135 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11138 // Decide which area this value should be read from.
11139 // TODO: Implement the AMD64 ABI in its entirety. This simple
11140 // selection mechanism works only for the basic types.
11141 if (ArgVT == MVT::f80) {
11142 llvm_unreachable("va_arg for f80 not yet implemented");
11143 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11144 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11145 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11146 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11148 llvm_unreachable("Unhandled argument type in LowerVAARG");
11151 if (ArgMode == 2) {
11152 // Sanity Check: Make sure using fp_offset makes sense.
11153 assert(!getTargetMachine().Options.UseSoftFloat &&
11154 !(DAG.getMachineFunction()
11155 .getFunction()->getAttributes()
11156 .hasAttribute(AttributeSet::FunctionIndex,
11157 Attribute::NoImplicitFloat)) &&
11158 Subtarget->hasSSE1());
11161 // Insert VAARG_64 node into the DAG
11162 // VAARG_64 returns two values: Variable Argument Address, Chain
11163 SmallVector<SDValue, 11> InstOps;
11164 InstOps.push_back(Chain);
11165 InstOps.push_back(SrcPtr);
11166 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11167 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11168 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11169 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11170 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11171 VTs, &InstOps[0], InstOps.size(),
11173 MachinePointerInfo(SV),
11175 /*Volatile=*/false,
11177 /*WriteMem=*/true);
11178 Chain = VAARG.getValue(1);
11180 // Load the next argument and return it
11181 return DAG.getLoad(ArgVT, dl,
11184 MachinePointerInfo(),
11185 false, false, false, 0);
11188 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11189 SelectionDAG &DAG) {
11190 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11191 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11192 SDValue Chain = Op.getOperand(0);
11193 SDValue DstPtr = Op.getOperand(1);
11194 SDValue SrcPtr = Op.getOperand(2);
11195 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11196 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11199 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11200 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11202 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11205 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11206 // amount is a constant. Takes immediate version of shift as input.
11207 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11208 SDValue SrcOp, uint64_t ShiftAmt,
11209 SelectionDAG &DAG) {
11210 MVT ElementType = VT.getVectorElementType();
11212 // Check for ShiftAmt >= element width
11213 if (ShiftAmt >= ElementType.getSizeInBits()) {
11214 if (Opc == X86ISD::VSRAI)
11215 ShiftAmt = ElementType.getSizeInBits() - 1;
11217 return DAG.getConstant(0, VT);
11220 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11221 && "Unknown target vector shift-by-constant node");
11223 // Fold this packed vector shift into a build vector if SrcOp is a
11224 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11225 if (VT == SrcOp.getSimpleValueType() &&
11226 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11227 SmallVector<SDValue, 8> Elts;
11228 unsigned NumElts = SrcOp->getNumOperands();
11229 ConstantSDNode *ND;
11232 default: llvm_unreachable(0);
11233 case X86ISD::VSHLI:
11234 for (unsigned i=0; i!=NumElts; ++i) {
11235 SDValue CurrentOp = SrcOp->getOperand(i);
11236 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11237 Elts.push_back(CurrentOp);
11240 ND = cast<ConstantSDNode>(CurrentOp);
11241 const APInt &C = ND->getAPIntValue();
11242 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11245 case X86ISD::VSRLI:
11246 for (unsigned i=0; i!=NumElts; ++i) {
11247 SDValue CurrentOp = SrcOp->getOperand(i);
11248 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11249 Elts.push_back(CurrentOp);
11252 ND = cast<ConstantSDNode>(CurrentOp);
11253 const APInt &C = ND->getAPIntValue();
11254 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11257 case X86ISD::VSRAI:
11258 for (unsigned i=0; i!=NumElts; ++i) {
11259 SDValue CurrentOp = SrcOp->getOperand(i);
11260 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11261 Elts.push_back(CurrentOp);
11264 ND = cast<ConstantSDNode>(CurrentOp);
11265 const APInt &C = ND->getAPIntValue();
11266 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11271 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11274 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11277 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11278 // may or may not be a constant. Takes immediate version of shift as input.
11279 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11280 SDValue SrcOp, SDValue ShAmt,
11281 SelectionDAG &DAG) {
11282 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11284 // Catch shift-by-constant.
11285 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11286 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11287 CShAmt->getZExtValue(), DAG);
11289 // Change opcode to non-immediate version
11291 default: llvm_unreachable("Unknown target vector shift node");
11292 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11293 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11294 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11297 // Need to build a vector containing shift amount
11298 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11301 ShOps[1] = DAG.getConstant(0, MVT::i32);
11302 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11303 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11305 // The return type has to be a 128-bit type with the same element
11306 // type as the input type.
11307 MVT EltVT = VT.getVectorElementType();
11308 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11310 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11311 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11314 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11316 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11318 default: return SDValue(); // Don't custom lower most intrinsics.
11319 // Comparison intrinsics.
11320 case Intrinsic::x86_sse_comieq_ss:
11321 case Intrinsic::x86_sse_comilt_ss:
11322 case Intrinsic::x86_sse_comile_ss:
11323 case Intrinsic::x86_sse_comigt_ss:
11324 case Intrinsic::x86_sse_comige_ss:
11325 case Intrinsic::x86_sse_comineq_ss:
11326 case Intrinsic::x86_sse_ucomieq_ss:
11327 case Intrinsic::x86_sse_ucomilt_ss:
11328 case Intrinsic::x86_sse_ucomile_ss:
11329 case Intrinsic::x86_sse_ucomigt_ss:
11330 case Intrinsic::x86_sse_ucomige_ss:
11331 case Intrinsic::x86_sse_ucomineq_ss:
11332 case Intrinsic::x86_sse2_comieq_sd:
11333 case Intrinsic::x86_sse2_comilt_sd:
11334 case Intrinsic::x86_sse2_comile_sd:
11335 case Intrinsic::x86_sse2_comigt_sd:
11336 case Intrinsic::x86_sse2_comige_sd:
11337 case Intrinsic::x86_sse2_comineq_sd:
11338 case Intrinsic::x86_sse2_ucomieq_sd:
11339 case Intrinsic::x86_sse2_ucomilt_sd:
11340 case Intrinsic::x86_sse2_ucomile_sd:
11341 case Intrinsic::x86_sse2_ucomigt_sd:
11342 case Intrinsic::x86_sse2_ucomige_sd:
11343 case Intrinsic::x86_sse2_ucomineq_sd: {
11347 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11348 case Intrinsic::x86_sse_comieq_ss:
11349 case Intrinsic::x86_sse2_comieq_sd:
11350 Opc = X86ISD::COMI;
11353 case Intrinsic::x86_sse_comilt_ss:
11354 case Intrinsic::x86_sse2_comilt_sd:
11355 Opc = X86ISD::COMI;
11358 case Intrinsic::x86_sse_comile_ss:
11359 case Intrinsic::x86_sse2_comile_sd:
11360 Opc = X86ISD::COMI;
11363 case Intrinsic::x86_sse_comigt_ss:
11364 case Intrinsic::x86_sse2_comigt_sd:
11365 Opc = X86ISD::COMI;
11368 case Intrinsic::x86_sse_comige_ss:
11369 case Intrinsic::x86_sse2_comige_sd:
11370 Opc = X86ISD::COMI;
11373 case Intrinsic::x86_sse_comineq_ss:
11374 case Intrinsic::x86_sse2_comineq_sd:
11375 Opc = X86ISD::COMI;
11378 case Intrinsic::x86_sse_ucomieq_ss:
11379 case Intrinsic::x86_sse2_ucomieq_sd:
11380 Opc = X86ISD::UCOMI;
11383 case Intrinsic::x86_sse_ucomilt_ss:
11384 case Intrinsic::x86_sse2_ucomilt_sd:
11385 Opc = X86ISD::UCOMI;
11388 case Intrinsic::x86_sse_ucomile_ss:
11389 case Intrinsic::x86_sse2_ucomile_sd:
11390 Opc = X86ISD::UCOMI;
11393 case Intrinsic::x86_sse_ucomigt_ss:
11394 case Intrinsic::x86_sse2_ucomigt_sd:
11395 Opc = X86ISD::UCOMI;
11398 case Intrinsic::x86_sse_ucomige_ss:
11399 case Intrinsic::x86_sse2_ucomige_sd:
11400 Opc = X86ISD::UCOMI;
11403 case Intrinsic::x86_sse_ucomineq_ss:
11404 case Intrinsic::x86_sse2_ucomineq_sd:
11405 Opc = X86ISD::UCOMI;
11410 SDValue LHS = Op.getOperand(1);
11411 SDValue RHS = Op.getOperand(2);
11412 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11413 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11414 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11415 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11416 DAG.getConstant(X86CC, MVT::i8), Cond);
11417 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11420 // Arithmetic intrinsics.
11421 case Intrinsic::x86_sse2_pmulu_dq:
11422 case Intrinsic::x86_avx2_pmulu_dq:
11423 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11424 Op.getOperand(1), Op.getOperand(2));
11426 // SSE2/AVX2 sub with unsigned saturation intrinsics
11427 case Intrinsic::x86_sse2_psubus_b:
11428 case Intrinsic::x86_sse2_psubus_w:
11429 case Intrinsic::x86_avx2_psubus_b:
11430 case Intrinsic::x86_avx2_psubus_w:
11431 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11432 Op.getOperand(1), Op.getOperand(2));
11434 // SSE3/AVX horizontal add/sub intrinsics
11435 case Intrinsic::x86_sse3_hadd_ps:
11436 case Intrinsic::x86_sse3_hadd_pd:
11437 case Intrinsic::x86_avx_hadd_ps_256:
11438 case Intrinsic::x86_avx_hadd_pd_256:
11439 case Intrinsic::x86_sse3_hsub_ps:
11440 case Intrinsic::x86_sse3_hsub_pd:
11441 case Intrinsic::x86_avx_hsub_ps_256:
11442 case Intrinsic::x86_avx_hsub_pd_256:
11443 case Intrinsic::x86_ssse3_phadd_w_128:
11444 case Intrinsic::x86_ssse3_phadd_d_128:
11445 case Intrinsic::x86_avx2_phadd_w:
11446 case Intrinsic::x86_avx2_phadd_d:
11447 case Intrinsic::x86_ssse3_phsub_w_128:
11448 case Intrinsic::x86_ssse3_phsub_d_128:
11449 case Intrinsic::x86_avx2_phsub_w:
11450 case Intrinsic::x86_avx2_phsub_d: {
11453 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11454 case Intrinsic::x86_sse3_hadd_ps:
11455 case Intrinsic::x86_sse3_hadd_pd:
11456 case Intrinsic::x86_avx_hadd_ps_256:
11457 case Intrinsic::x86_avx_hadd_pd_256:
11458 Opcode = X86ISD::FHADD;
11460 case Intrinsic::x86_sse3_hsub_ps:
11461 case Intrinsic::x86_sse3_hsub_pd:
11462 case Intrinsic::x86_avx_hsub_ps_256:
11463 case Intrinsic::x86_avx_hsub_pd_256:
11464 Opcode = X86ISD::FHSUB;
11466 case Intrinsic::x86_ssse3_phadd_w_128:
11467 case Intrinsic::x86_ssse3_phadd_d_128:
11468 case Intrinsic::x86_avx2_phadd_w:
11469 case Intrinsic::x86_avx2_phadd_d:
11470 Opcode = X86ISD::HADD;
11472 case Intrinsic::x86_ssse3_phsub_w_128:
11473 case Intrinsic::x86_ssse3_phsub_d_128:
11474 case Intrinsic::x86_avx2_phsub_w:
11475 case Intrinsic::x86_avx2_phsub_d:
11476 Opcode = X86ISD::HSUB;
11479 return DAG.getNode(Opcode, dl, Op.getValueType(),
11480 Op.getOperand(1), Op.getOperand(2));
11483 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11484 case Intrinsic::x86_sse2_pmaxu_b:
11485 case Intrinsic::x86_sse41_pmaxuw:
11486 case Intrinsic::x86_sse41_pmaxud:
11487 case Intrinsic::x86_avx2_pmaxu_b:
11488 case Intrinsic::x86_avx2_pmaxu_w:
11489 case Intrinsic::x86_avx2_pmaxu_d:
11490 case Intrinsic::x86_sse2_pminu_b:
11491 case Intrinsic::x86_sse41_pminuw:
11492 case Intrinsic::x86_sse41_pminud:
11493 case Intrinsic::x86_avx2_pminu_b:
11494 case Intrinsic::x86_avx2_pminu_w:
11495 case Intrinsic::x86_avx2_pminu_d:
11496 case Intrinsic::x86_sse41_pmaxsb:
11497 case Intrinsic::x86_sse2_pmaxs_w:
11498 case Intrinsic::x86_sse41_pmaxsd:
11499 case Intrinsic::x86_avx2_pmaxs_b:
11500 case Intrinsic::x86_avx2_pmaxs_w:
11501 case Intrinsic::x86_avx2_pmaxs_d:
11502 case Intrinsic::x86_sse41_pminsb:
11503 case Intrinsic::x86_sse2_pmins_w:
11504 case Intrinsic::x86_sse41_pminsd:
11505 case Intrinsic::x86_avx2_pmins_b:
11506 case Intrinsic::x86_avx2_pmins_w:
11507 case Intrinsic::x86_avx2_pmins_d: {
11510 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11511 case Intrinsic::x86_sse2_pmaxu_b:
11512 case Intrinsic::x86_sse41_pmaxuw:
11513 case Intrinsic::x86_sse41_pmaxud:
11514 case Intrinsic::x86_avx2_pmaxu_b:
11515 case Intrinsic::x86_avx2_pmaxu_w:
11516 case Intrinsic::x86_avx2_pmaxu_d:
11517 Opcode = X86ISD::UMAX;
11519 case Intrinsic::x86_sse2_pminu_b:
11520 case Intrinsic::x86_sse41_pminuw:
11521 case Intrinsic::x86_sse41_pminud:
11522 case Intrinsic::x86_avx2_pminu_b:
11523 case Intrinsic::x86_avx2_pminu_w:
11524 case Intrinsic::x86_avx2_pminu_d:
11525 Opcode = X86ISD::UMIN;
11527 case Intrinsic::x86_sse41_pmaxsb:
11528 case Intrinsic::x86_sse2_pmaxs_w:
11529 case Intrinsic::x86_sse41_pmaxsd:
11530 case Intrinsic::x86_avx2_pmaxs_b:
11531 case Intrinsic::x86_avx2_pmaxs_w:
11532 case Intrinsic::x86_avx2_pmaxs_d:
11533 Opcode = X86ISD::SMAX;
11535 case Intrinsic::x86_sse41_pminsb:
11536 case Intrinsic::x86_sse2_pmins_w:
11537 case Intrinsic::x86_sse41_pminsd:
11538 case Intrinsic::x86_avx2_pmins_b:
11539 case Intrinsic::x86_avx2_pmins_w:
11540 case Intrinsic::x86_avx2_pmins_d:
11541 Opcode = X86ISD::SMIN;
11544 return DAG.getNode(Opcode, dl, Op.getValueType(),
11545 Op.getOperand(1), Op.getOperand(2));
11548 // SSE/SSE2/AVX floating point max/min intrinsics.
11549 case Intrinsic::x86_sse_max_ps:
11550 case Intrinsic::x86_sse2_max_pd:
11551 case Intrinsic::x86_avx_max_ps_256:
11552 case Intrinsic::x86_avx_max_pd_256:
11553 case Intrinsic::x86_sse_min_ps:
11554 case Intrinsic::x86_sse2_min_pd:
11555 case Intrinsic::x86_avx_min_ps_256:
11556 case Intrinsic::x86_avx_min_pd_256: {
11559 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11560 case Intrinsic::x86_sse_max_ps:
11561 case Intrinsic::x86_sse2_max_pd:
11562 case Intrinsic::x86_avx_max_ps_256:
11563 case Intrinsic::x86_avx_max_pd_256:
11564 Opcode = X86ISD::FMAX;
11566 case Intrinsic::x86_sse_min_ps:
11567 case Intrinsic::x86_sse2_min_pd:
11568 case Intrinsic::x86_avx_min_ps_256:
11569 case Intrinsic::x86_avx_min_pd_256:
11570 Opcode = X86ISD::FMIN;
11573 return DAG.getNode(Opcode, dl, Op.getValueType(),
11574 Op.getOperand(1), Op.getOperand(2));
11577 // AVX2 variable shift intrinsics
11578 case Intrinsic::x86_avx2_psllv_d:
11579 case Intrinsic::x86_avx2_psllv_q:
11580 case Intrinsic::x86_avx2_psllv_d_256:
11581 case Intrinsic::x86_avx2_psllv_q_256:
11582 case Intrinsic::x86_avx2_psrlv_d:
11583 case Intrinsic::x86_avx2_psrlv_q:
11584 case Intrinsic::x86_avx2_psrlv_d_256:
11585 case Intrinsic::x86_avx2_psrlv_q_256:
11586 case Intrinsic::x86_avx2_psrav_d:
11587 case Intrinsic::x86_avx2_psrav_d_256: {
11590 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11591 case Intrinsic::x86_avx2_psllv_d:
11592 case Intrinsic::x86_avx2_psllv_q:
11593 case Intrinsic::x86_avx2_psllv_d_256:
11594 case Intrinsic::x86_avx2_psllv_q_256:
11597 case Intrinsic::x86_avx2_psrlv_d:
11598 case Intrinsic::x86_avx2_psrlv_q:
11599 case Intrinsic::x86_avx2_psrlv_d_256:
11600 case Intrinsic::x86_avx2_psrlv_q_256:
11603 case Intrinsic::x86_avx2_psrav_d:
11604 case Intrinsic::x86_avx2_psrav_d_256:
11608 return DAG.getNode(Opcode, dl, Op.getValueType(),
11609 Op.getOperand(1), Op.getOperand(2));
11612 case Intrinsic::x86_ssse3_pshuf_b_128:
11613 case Intrinsic::x86_avx2_pshuf_b:
11614 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11615 Op.getOperand(1), Op.getOperand(2));
11617 case Intrinsic::x86_ssse3_psign_b_128:
11618 case Intrinsic::x86_ssse3_psign_w_128:
11619 case Intrinsic::x86_ssse3_psign_d_128:
11620 case Intrinsic::x86_avx2_psign_b:
11621 case Intrinsic::x86_avx2_psign_w:
11622 case Intrinsic::x86_avx2_psign_d:
11623 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11624 Op.getOperand(1), Op.getOperand(2));
11626 case Intrinsic::x86_sse41_insertps:
11627 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11628 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11630 case Intrinsic::x86_avx_vperm2f128_ps_256:
11631 case Intrinsic::x86_avx_vperm2f128_pd_256:
11632 case Intrinsic::x86_avx_vperm2f128_si_256:
11633 case Intrinsic::x86_avx2_vperm2i128:
11634 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11635 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11637 case Intrinsic::x86_avx2_permd:
11638 case Intrinsic::x86_avx2_permps:
11639 // Operands intentionally swapped. Mask is last operand to intrinsic,
11640 // but second operand for node/instruction.
11641 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11642 Op.getOperand(2), Op.getOperand(1));
11644 case Intrinsic::x86_sse_sqrt_ps:
11645 case Intrinsic::x86_sse2_sqrt_pd:
11646 case Intrinsic::x86_avx_sqrt_ps_256:
11647 case Intrinsic::x86_avx_sqrt_pd_256:
11648 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11650 // ptest and testp intrinsics. The intrinsic these come from are designed to
11651 // return an integer value, not just an instruction so lower it to the ptest
11652 // or testp pattern and a setcc for the result.
11653 case Intrinsic::x86_sse41_ptestz:
11654 case Intrinsic::x86_sse41_ptestc:
11655 case Intrinsic::x86_sse41_ptestnzc:
11656 case Intrinsic::x86_avx_ptestz_256:
11657 case Intrinsic::x86_avx_ptestc_256:
11658 case Intrinsic::x86_avx_ptestnzc_256:
11659 case Intrinsic::x86_avx_vtestz_ps:
11660 case Intrinsic::x86_avx_vtestc_ps:
11661 case Intrinsic::x86_avx_vtestnzc_ps:
11662 case Intrinsic::x86_avx_vtestz_pd:
11663 case Intrinsic::x86_avx_vtestc_pd:
11664 case Intrinsic::x86_avx_vtestnzc_pd:
11665 case Intrinsic::x86_avx_vtestz_ps_256:
11666 case Intrinsic::x86_avx_vtestc_ps_256:
11667 case Intrinsic::x86_avx_vtestnzc_ps_256:
11668 case Intrinsic::x86_avx_vtestz_pd_256:
11669 case Intrinsic::x86_avx_vtestc_pd_256:
11670 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11671 bool IsTestPacked = false;
11674 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11675 case Intrinsic::x86_avx_vtestz_ps:
11676 case Intrinsic::x86_avx_vtestz_pd:
11677 case Intrinsic::x86_avx_vtestz_ps_256:
11678 case Intrinsic::x86_avx_vtestz_pd_256:
11679 IsTestPacked = true; // Fallthrough
11680 case Intrinsic::x86_sse41_ptestz:
11681 case Intrinsic::x86_avx_ptestz_256:
11683 X86CC = X86::COND_E;
11685 case Intrinsic::x86_avx_vtestc_ps:
11686 case Intrinsic::x86_avx_vtestc_pd:
11687 case Intrinsic::x86_avx_vtestc_ps_256:
11688 case Intrinsic::x86_avx_vtestc_pd_256:
11689 IsTestPacked = true; // Fallthrough
11690 case Intrinsic::x86_sse41_ptestc:
11691 case Intrinsic::x86_avx_ptestc_256:
11693 X86CC = X86::COND_B;
11695 case Intrinsic::x86_avx_vtestnzc_ps:
11696 case Intrinsic::x86_avx_vtestnzc_pd:
11697 case Intrinsic::x86_avx_vtestnzc_ps_256:
11698 case Intrinsic::x86_avx_vtestnzc_pd_256:
11699 IsTestPacked = true; // Fallthrough
11700 case Intrinsic::x86_sse41_ptestnzc:
11701 case Intrinsic::x86_avx_ptestnzc_256:
11703 X86CC = X86::COND_A;
11707 SDValue LHS = Op.getOperand(1);
11708 SDValue RHS = Op.getOperand(2);
11709 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11710 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11711 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11712 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11713 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11715 case Intrinsic::x86_avx512_kortestz_w:
11716 case Intrinsic::x86_avx512_kortestc_w: {
11717 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11718 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11719 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11720 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11721 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11722 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11723 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11726 // SSE/AVX shift intrinsics
11727 case Intrinsic::x86_sse2_psll_w:
11728 case Intrinsic::x86_sse2_psll_d:
11729 case Intrinsic::x86_sse2_psll_q:
11730 case Intrinsic::x86_avx2_psll_w:
11731 case Intrinsic::x86_avx2_psll_d:
11732 case Intrinsic::x86_avx2_psll_q:
11733 case Intrinsic::x86_sse2_psrl_w:
11734 case Intrinsic::x86_sse2_psrl_d:
11735 case Intrinsic::x86_sse2_psrl_q:
11736 case Intrinsic::x86_avx2_psrl_w:
11737 case Intrinsic::x86_avx2_psrl_d:
11738 case Intrinsic::x86_avx2_psrl_q:
11739 case Intrinsic::x86_sse2_psra_w:
11740 case Intrinsic::x86_sse2_psra_d:
11741 case Intrinsic::x86_avx2_psra_w:
11742 case Intrinsic::x86_avx2_psra_d: {
11745 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11746 case Intrinsic::x86_sse2_psll_w:
11747 case Intrinsic::x86_sse2_psll_d:
11748 case Intrinsic::x86_sse2_psll_q:
11749 case Intrinsic::x86_avx2_psll_w:
11750 case Intrinsic::x86_avx2_psll_d:
11751 case Intrinsic::x86_avx2_psll_q:
11752 Opcode = X86ISD::VSHL;
11754 case Intrinsic::x86_sse2_psrl_w:
11755 case Intrinsic::x86_sse2_psrl_d:
11756 case Intrinsic::x86_sse2_psrl_q:
11757 case Intrinsic::x86_avx2_psrl_w:
11758 case Intrinsic::x86_avx2_psrl_d:
11759 case Intrinsic::x86_avx2_psrl_q:
11760 Opcode = X86ISD::VSRL;
11762 case Intrinsic::x86_sse2_psra_w:
11763 case Intrinsic::x86_sse2_psra_d:
11764 case Intrinsic::x86_avx2_psra_w:
11765 case Intrinsic::x86_avx2_psra_d:
11766 Opcode = X86ISD::VSRA;
11769 return DAG.getNode(Opcode, dl, Op.getValueType(),
11770 Op.getOperand(1), Op.getOperand(2));
11773 // SSE/AVX immediate shift intrinsics
11774 case Intrinsic::x86_sse2_pslli_w:
11775 case Intrinsic::x86_sse2_pslli_d:
11776 case Intrinsic::x86_sse2_pslli_q:
11777 case Intrinsic::x86_avx2_pslli_w:
11778 case Intrinsic::x86_avx2_pslli_d:
11779 case Intrinsic::x86_avx2_pslli_q:
11780 case Intrinsic::x86_sse2_psrli_w:
11781 case Intrinsic::x86_sse2_psrli_d:
11782 case Intrinsic::x86_sse2_psrli_q:
11783 case Intrinsic::x86_avx2_psrli_w:
11784 case Intrinsic::x86_avx2_psrli_d:
11785 case Intrinsic::x86_avx2_psrli_q:
11786 case Intrinsic::x86_sse2_psrai_w:
11787 case Intrinsic::x86_sse2_psrai_d:
11788 case Intrinsic::x86_avx2_psrai_w:
11789 case Intrinsic::x86_avx2_psrai_d: {
11792 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11793 case Intrinsic::x86_sse2_pslli_w:
11794 case Intrinsic::x86_sse2_pslli_d:
11795 case Intrinsic::x86_sse2_pslli_q:
11796 case Intrinsic::x86_avx2_pslli_w:
11797 case Intrinsic::x86_avx2_pslli_d:
11798 case Intrinsic::x86_avx2_pslli_q:
11799 Opcode = X86ISD::VSHLI;
11801 case Intrinsic::x86_sse2_psrli_w:
11802 case Intrinsic::x86_sse2_psrli_d:
11803 case Intrinsic::x86_sse2_psrli_q:
11804 case Intrinsic::x86_avx2_psrli_w:
11805 case Intrinsic::x86_avx2_psrli_d:
11806 case Intrinsic::x86_avx2_psrli_q:
11807 Opcode = X86ISD::VSRLI;
11809 case Intrinsic::x86_sse2_psrai_w:
11810 case Intrinsic::x86_sse2_psrai_d:
11811 case Intrinsic::x86_avx2_psrai_w:
11812 case Intrinsic::x86_avx2_psrai_d:
11813 Opcode = X86ISD::VSRAI;
11816 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11817 Op.getOperand(1), Op.getOperand(2), DAG);
11820 case Intrinsic::x86_sse42_pcmpistria128:
11821 case Intrinsic::x86_sse42_pcmpestria128:
11822 case Intrinsic::x86_sse42_pcmpistric128:
11823 case Intrinsic::x86_sse42_pcmpestric128:
11824 case Intrinsic::x86_sse42_pcmpistrio128:
11825 case Intrinsic::x86_sse42_pcmpestrio128:
11826 case Intrinsic::x86_sse42_pcmpistris128:
11827 case Intrinsic::x86_sse42_pcmpestris128:
11828 case Intrinsic::x86_sse42_pcmpistriz128:
11829 case Intrinsic::x86_sse42_pcmpestriz128: {
11833 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11834 case Intrinsic::x86_sse42_pcmpistria128:
11835 Opcode = X86ISD::PCMPISTRI;
11836 X86CC = X86::COND_A;
11838 case Intrinsic::x86_sse42_pcmpestria128:
11839 Opcode = X86ISD::PCMPESTRI;
11840 X86CC = X86::COND_A;
11842 case Intrinsic::x86_sse42_pcmpistric128:
11843 Opcode = X86ISD::PCMPISTRI;
11844 X86CC = X86::COND_B;
11846 case Intrinsic::x86_sse42_pcmpestric128:
11847 Opcode = X86ISD::PCMPESTRI;
11848 X86CC = X86::COND_B;
11850 case Intrinsic::x86_sse42_pcmpistrio128:
11851 Opcode = X86ISD::PCMPISTRI;
11852 X86CC = X86::COND_O;
11854 case Intrinsic::x86_sse42_pcmpestrio128:
11855 Opcode = X86ISD::PCMPESTRI;
11856 X86CC = X86::COND_O;
11858 case Intrinsic::x86_sse42_pcmpistris128:
11859 Opcode = X86ISD::PCMPISTRI;
11860 X86CC = X86::COND_S;
11862 case Intrinsic::x86_sse42_pcmpestris128:
11863 Opcode = X86ISD::PCMPESTRI;
11864 X86CC = X86::COND_S;
11866 case Intrinsic::x86_sse42_pcmpistriz128:
11867 Opcode = X86ISD::PCMPISTRI;
11868 X86CC = X86::COND_E;
11870 case Intrinsic::x86_sse42_pcmpestriz128:
11871 Opcode = X86ISD::PCMPESTRI;
11872 X86CC = X86::COND_E;
11875 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11876 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11877 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11878 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11879 DAG.getConstant(X86CC, MVT::i8),
11880 SDValue(PCMP.getNode(), 1));
11881 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11884 case Intrinsic::x86_sse42_pcmpistri128:
11885 case Intrinsic::x86_sse42_pcmpestri128: {
11887 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11888 Opcode = X86ISD::PCMPISTRI;
11890 Opcode = X86ISD::PCMPESTRI;
11892 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11893 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11894 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11896 case Intrinsic::x86_fma_vfmadd_ps:
11897 case Intrinsic::x86_fma_vfmadd_pd:
11898 case Intrinsic::x86_fma_vfmsub_ps:
11899 case Intrinsic::x86_fma_vfmsub_pd:
11900 case Intrinsic::x86_fma_vfnmadd_ps:
11901 case Intrinsic::x86_fma_vfnmadd_pd:
11902 case Intrinsic::x86_fma_vfnmsub_ps:
11903 case Intrinsic::x86_fma_vfnmsub_pd:
11904 case Intrinsic::x86_fma_vfmaddsub_ps:
11905 case Intrinsic::x86_fma_vfmaddsub_pd:
11906 case Intrinsic::x86_fma_vfmsubadd_ps:
11907 case Intrinsic::x86_fma_vfmsubadd_pd:
11908 case Intrinsic::x86_fma_vfmadd_ps_256:
11909 case Intrinsic::x86_fma_vfmadd_pd_256:
11910 case Intrinsic::x86_fma_vfmsub_ps_256:
11911 case Intrinsic::x86_fma_vfmsub_pd_256:
11912 case Intrinsic::x86_fma_vfnmadd_ps_256:
11913 case Intrinsic::x86_fma_vfnmadd_pd_256:
11914 case Intrinsic::x86_fma_vfnmsub_ps_256:
11915 case Intrinsic::x86_fma_vfnmsub_pd_256:
11916 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11917 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11918 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11919 case Intrinsic::x86_fma_vfmsubadd_pd_256:
11920 case Intrinsic::x86_fma_vfmadd_ps_512:
11921 case Intrinsic::x86_fma_vfmadd_pd_512:
11922 case Intrinsic::x86_fma_vfmsub_ps_512:
11923 case Intrinsic::x86_fma_vfmsub_pd_512:
11924 case Intrinsic::x86_fma_vfnmadd_ps_512:
11925 case Intrinsic::x86_fma_vfnmadd_pd_512:
11926 case Intrinsic::x86_fma_vfnmsub_ps_512:
11927 case Intrinsic::x86_fma_vfnmsub_pd_512:
11928 case Intrinsic::x86_fma_vfmaddsub_ps_512:
11929 case Intrinsic::x86_fma_vfmaddsub_pd_512:
11930 case Intrinsic::x86_fma_vfmsubadd_ps_512:
11931 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11934 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11935 case Intrinsic::x86_fma_vfmadd_ps:
11936 case Intrinsic::x86_fma_vfmadd_pd:
11937 case Intrinsic::x86_fma_vfmadd_ps_256:
11938 case Intrinsic::x86_fma_vfmadd_pd_256:
11939 case Intrinsic::x86_fma_vfmadd_ps_512:
11940 case Intrinsic::x86_fma_vfmadd_pd_512:
11941 Opc = X86ISD::FMADD;
11943 case Intrinsic::x86_fma_vfmsub_ps:
11944 case Intrinsic::x86_fma_vfmsub_pd:
11945 case Intrinsic::x86_fma_vfmsub_ps_256:
11946 case Intrinsic::x86_fma_vfmsub_pd_256:
11947 case Intrinsic::x86_fma_vfmsub_ps_512:
11948 case Intrinsic::x86_fma_vfmsub_pd_512:
11949 Opc = X86ISD::FMSUB;
11951 case Intrinsic::x86_fma_vfnmadd_ps:
11952 case Intrinsic::x86_fma_vfnmadd_pd:
11953 case Intrinsic::x86_fma_vfnmadd_ps_256:
11954 case Intrinsic::x86_fma_vfnmadd_pd_256:
11955 case Intrinsic::x86_fma_vfnmadd_ps_512:
11956 case Intrinsic::x86_fma_vfnmadd_pd_512:
11957 Opc = X86ISD::FNMADD;
11959 case Intrinsic::x86_fma_vfnmsub_ps:
11960 case Intrinsic::x86_fma_vfnmsub_pd:
11961 case Intrinsic::x86_fma_vfnmsub_ps_256:
11962 case Intrinsic::x86_fma_vfnmsub_pd_256:
11963 case Intrinsic::x86_fma_vfnmsub_ps_512:
11964 case Intrinsic::x86_fma_vfnmsub_pd_512:
11965 Opc = X86ISD::FNMSUB;
11967 case Intrinsic::x86_fma_vfmaddsub_ps:
11968 case Intrinsic::x86_fma_vfmaddsub_pd:
11969 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11970 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11971 case Intrinsic::x86_fma_vfmaddsub_ps_512:
11972 case Intrinsic::x86_fma_vfmaddsub_pd_512:
11973 Opc = X86ISD::FMADDSUB;
11975 case Intrinsic::x86_fma_vfmsubadd_ps:
11976 case Intrinsic::x86_fma_vfmsubadd_pd:
11977 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11978 case Intrinsic::x86_fma_vfmsubadd_pd_256:
11979 case Intrinsic::x86_fma_vfmsubadd_ps_512:
11980 case Intrinsic::x86_fma_vfmsubadd_pd_512:
11981 Opc = X86ISD::FMSUBADD;
11985 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11986 Op.getOperand(2), Op.getOperand(3));
11991 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11992 SDValue Base, SDValue Index,
11993 SDValue ScaleOp, SDValue Chain,
11994 const X86Subtarget * Subtarget) {
11996 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11997 assert(C && "Invalid scale type");
11998 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11999 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12000 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12001 Index.getSimpleValueType().getVectorNumElements());
12002 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12003 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12004 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12005 SDValue Segment = DAG.getRegister(0, MVT::i32);
12006 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12007 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12008 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12009 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12012 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12013 SDValue Src, SDValue Mask, SDValue Base,
12014 SDValue Index, SDValue ScaleOp, SDValue Chain,
12015 const X86Subtarget * Subtarget) {
12017 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12018 assert(C && "Invalid scale type");
12019 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12020 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12021 Index.getSimpleValueType().getVectorNumElements());
12022 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12023 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12024 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12025 SDValue Segment = DAG.getRegister(0, MVT::i32);
12026 if (Src.getOpcode() == ISD::UNDEF)
12027 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12028 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12029 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12030 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12031 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12034 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12035 SDValue Src, SDValue Base, SDValue Index,
12036 SDValue ScaleOp, SDValue Chain) {
12038 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12039 assert(C && "Invalid scale type");
12040 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12041 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12042 SDValue Segment = DAG.getRegister(0, MVT::i32);
12043 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12044 Index.getSimpleValueType().getVectorNumElements());
12045 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12046 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12047 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12048 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12049 return SDValue(Res, 1);
12052 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12053 SDValue Src, SDValue Mask, SDValue Base,
12054 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12056 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12057 assert(C && "Invalid scale type");
12058 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12059 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12060 SDValue Segment = DAG.getRegister(0, MVT::i32);
12061 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12062 Index.getSimpleValueType().getVectorNumElements());
12063 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12064 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12065 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12066 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12067 return SDValue(Res, 1);
12070 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12071 SelectionDAG &DAG) {
12073 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12075 default: return SDValue(); // Don't custom lower most intrinsics.
12077 // RDRAND/RDSEED intrinsics.
12078 case Intrinsic::x86_rdrand_16:
12079 case Intrinsic::x86_rdrand_32:
12080 case Intrinsic::x86_rdrand_64:
12081 case Intrinsic::x86_rdseed_16:
12082 case Intrinsic::x86_rdseed_32:
12083 case Intrinsic::x86_rdseed_64: {
12084 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12085 IntNo == Intrinsic::x86_rdseed_32 ||
12086 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12088 // Emit the node with the right value type.
12089 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12090 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12092 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12093 // Otherwise return the value from Rand, which is always 0, casted to i32.
12094 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12095 DAG.getConstant(1, Op->getValueType(1)),
12096 DAG.getConstant(X86::COND_B, MVT::i32),
12097 SDValue(Result.getNode(), 1) };
12098 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12099 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12100 Ops, array_lengthof(Ops));
12102 // Return { result, isValid, chain }.
12103 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12104 SDValue(Result.getNode(), 2));
12106 //int_gather(index, base, scale);
12107 case Intrinsic::x86_avx512_gather_qpd_512:
12108 case Intrinsic::x86_avx512_gather_qps_512:
12109 case Intrinsic::x86_avx512_gather_dpd_512:
12110 case Intrinsic::x86_avx512_gather_qpi_512:
12111 case Intrinsic::x86_avx512_gather_qpq_512:
12112 case Intrinsic::x86_avx512_gather_dpq_512:
12113 case Intrinsic::x86_avx512_gather_dps_512:
12114 case Intrinsic::x86_avx512_gather_dpi_512: {
12117 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12118 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12119 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12120 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12121 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12122 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12123 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12124 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12125 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12127 SDValue Chain = Op.getOperand(0);
12128 SDValue Index = Op.getOperand(2);
12129 SDValue Base = Op.getOperand(3);
12130 SDValue Scale = Op.getOperand(4);
12131 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12133 //int_gather_mask(v1, mask, index, base, scale);
12134 case Intrinsic::x86_avx512_gather_qps_mask_512:
12135 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12136 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12137 case Intrinsic::x86_avx512_gather_dps_mask_512:
12138 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12139 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12140 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12141 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12144 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12145 case Intrinsic::x86_avx512_gather_qps_mask_512:
12146 Opc = X86::VGATHERQPSZrm; break;
12147 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12148 Opc = X86::VGATHERQPDZrm; break;
12149 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12150 Opc = X86::VGATHERDPDZrm; break;
12151 case Intrinsic::x86_avx512_gather_dps_mask_512:
12152 Opc = X86::VGATHERDPSZrm; break;
12153 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12154 Opc = X86::VPGATHERQDZrm; break;
12155 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12156 Opc = X86::VPGATHERQQZrm; break;
12157 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12158 Opc = X86::VPGATHERDDZrm; break;
12159 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12160 Opc = X86::VPGATHERDQZrm; break;
12162 SDValue Chain = Op.getOperand(0);
12163 SDValue Src = Op.getOperand(2);
12164 SDValue Mask = Op.getOperand(3);
12165 SDValue Index = Op.getOperand(4);
12166 SDValue Base = Op.getOperand(5);
12167 SDValue Scale = Op.getOperand(6);
12168 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12171 //int_scatter(base, index, v1, scale);
12172 case Intrinsic::x86_avx512_scatter_qpd_512:
12173 case Intrinsic::x86_avx512_scatter_qps_512:
12174 case Intrinsic::x86_avx512_scatter_dpd_512:
12175 case Intrinsic::x86_avx512_scatter_qpi_512:
12176 case Intrinsic::x86_avx512_scatter_qpq_512:
12177 case Intrinsic::x86_avx512_scatter_dpq_512:
12178 case Intrinsic::x86_avx512_scatter_dps_512:
12179 case Intrinsic::x86_avx512_scatter_dpi_512: {
12182 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12183 case Intrinsic::x86_avx512_scatter_qpd_512:
12184 Opc = X86::VSCATTERQPDZmr; break;
12185 case Intrinsic::x86_avx512_scatter_qps_512:
12186 Opc = X86::VSCATTERQPSZmr; break;
12187 case Intrinsic::x86_avx512_scatter_dpd_512:
12188 Opc = X86::VSCATTERDPDZmr; break;
12189 case Intrinsic::x86_avx512_scatter_dps_512:
12190 Opc = X86::VSCATTERDPSZmr; break;
12191 case Intrinsic::x86_avx512_scatter_qpi_512:
12192 Opc = X86::VPSCATTERQDZmr; break;
12193 case Intrinsic::x86_avx512_scatter_qpq_512:
12194 Opc = X86::VPSCATTERQQZmr; break;
12195 case Intrinsic::x86_avx512_scatter_dpq_512:
12196 Opc = X86::VPSCATTERDQZmr; break;
12197 case Intrinsic::x86_avx512_scatter_dpi_512:
12198 Opc = X86::VPSCATTERDDZmr; break;
12200 SDValue Chain = Op.getOperand(0);
12201 SDValue Base = Op.getOperand(2);
12202 SDValue Index = Op.getOperand(3);
12203 SDValue Src = Op.getOperand(4);
12204 SDValue Scale = Op.getOperand(5);
12205 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12207 //int_scatter_mask(base, mask, index, v1, scale);
12208 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12209 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12210 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12211 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12212 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12213 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12214 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12215 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12218 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12219 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12220 Opc = X86::VSCATTERQPDZmr; break;
12221 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12222 Opc = X86::VSCATTERQPSZmr; break;
12223 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12224 Opc = X86::VSCATTERDPDZmr; break;
12225 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12226 Opc = X86::VSCATTERDPSZmr; break;
12227 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12228 Opc = X86::VPSCATTERQDZmr; break;
12229 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12230 Opc = X86::VPSCATTERQQZmr; break;
12231 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12232 Opc = X86::VPSCATTERDQZmr; break;
12233 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12234 Opc = X86::VPSCATTERDDZmr; break;
12236 SDValue Chain = Op.getOperand(0);
12237 SDValue Base = Op.getOperand(2);
12238 SDValue Mask = Op.getOperand(3);
12239 SDValue Index = Op.getOperand(4);
12240 SDValue Src = Op.getOperand(5);
12241 SDValue Scale = Op.getOperand(6);
12242 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12244 // XTEST intrinsics.
12245 case Intrinsic::x86_xtest: {
12246 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12247 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12248 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12249 DAG.getConstant(X86::COND_NE, MVT::i8),
12251 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12252 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12253 Ret, SDValue(InTrans.getNode(), 1));
12258 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12259 SelectionDAG &DAG) const {
12260 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12261 MFI->setReturnAddressIsTaken(true);
12263 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12266 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12268 EVT PtrVT = getPointerTy();
12271 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12272 const X86RegisterInfo *RegInfo =
12273 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12274 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12275 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12276 DAG.getNode(ISD::ADD, dl, PtrVT,
12277 FrameAddr, Offset),
12278 MachinePointerInfo(), false, false, false, 0);
12281 // Just load the return address.
12282 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12283 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12284 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12287 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12288 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12289 MFI->setFrameAddressIsTaken(true);
12291 EVT VT = Op.getValueType();
12292 SDLoc dl(Op); // FIXME probably not meaningful
12293 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12294 const X86RegisterInfo *RegInfo =
12295 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12296 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12297 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12298 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12299 "Invalid Frame Register!");
12300 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12302 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12303 MachinePointerInfo(),
12304 false, false, false, 0);
12308 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12309 SelectionDAG &DAG) const {
12310 const X86RegisterInfo *RegInfo =
12311 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12312 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12315 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12316 SDValue Chain = Op.getOperand(0);
12317 SDValue Offset = Op.getOperand(1);
12318 SDValue Handler = Op.getOperand(2);
12321 EVT PtrVT = getPointerTy();
12322 const X86RegisterInfo *RegInfo =
12323 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12324 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12325 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12326 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12327 "Invalid Frame Register!");
12328 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12329 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12331 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12332 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12333 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12334 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12336 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12338 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12339 DAG.getRegister(StoreAddrReg, PtrVT));
12342 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12343 SelectionDAG &DAG) const {
12345 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12346 DAG.getVTList(MVT::i32, MVT::Other),
12347 Op.getOperand(0), Op.getOperand(1));
12350 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12351 SelectionDAG &DAG) const {
12353 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12354 Op.getOperand(0), Op.getOperand(1));
12357 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12358 return Op.getOperand(0);
12361 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12362 SelectionDAG &DAG) const {
12363 SDValue Root = Op.getOperand(0);
12364 SDValue Trmp = Op.getOperand(1); // trampoline
12365 SDValue FPtr = Op.getOperand(2); // nested function
12366 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12369 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12370 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12372 if (Subtarget->is64Bit()) {
12373 SDValue OutChains[6];
12375 // Large code-model.
12376 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12377 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12379 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12380 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12382 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12384 // Load the pointer to the nested function into R11.
12385 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12386 SDValue Addr = Trmp;
12387 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12388 Addr, MachinePointerInfo(TrmpAddr),
12391 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12392 DAG.getConstant(2, MVT::i64));
12393 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12394 MachinePointerInfo(TrmpAddr, 2),
12397 // Load the 'nest' parameter value into R10.
12398 // R10 is specified in X86CallingConv.td
12399 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12400 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12401 DAG.getConstant(10, MVT::i64));
12402 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12403 Addr, MachinePointerInfo(TrmpAddr, 10),
12406 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12407 DAG.getConstant(12, MVT::i64));
12408 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12409 MachinePointerInfo(TrmpAddr, 12),
12412 // Jump to the nested function.
12413 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12414 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12415 DAG.getConstant(20, MVT::i64));
12416 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12417 Addr, MachinePointerInfo(TrmpAddr, 20),
12420 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12421 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12422 DAG.getConstant(22, MVT::i64));
12423 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12424 MachinePointerInfo(TrmpAddr, 22),
12427 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12429 const Function *Func =
12430 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12431 CallingConv::ID CC = Func->getCallingConv();
12436 llvm_unreachable("Unsupported calling convention");
12437 case CallingConv::C:
12438 case CallingConv::X86_StdCall: {
12439 // Pass 'nest' parameter in ECX.
12440 // Must be kept in sync with X86CallingConv.td
12441 NestReg = X86::ECX;
12443 // Check that ECX wasn't needed by an 'inreg' parameter.
12444 FunctionType *FTy = Func->getFunctionType();
12445 const AttributeSet &Attrs = Func->getAttributes();
12447 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12448 unsigned InRegCount = 0;
12451 for (FunctionType::param_iterator I = FTy->param_begin(),
12452 E = FTy->param_end(); I != E; ++I, ++Idx)
12453 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12454 // FIXME: should only count parameters that are lowered to integers.
12455 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12457 if (InRegCount > 2) {
12458 report_fatal_error("Nest register in use - reduce number of inreg"
12464 case CallingConv::X86_FastCall:
12465 case CallingConv::X86_ThisCall:
12466 case CallingConv::Fast:
12467 // Pass 'nest' parameter in EAX.
12468 // Must be kept in sync with X86CallingConv.td
12469 NestReg = X86::EAX;
12473 SDValue OutChains[4];
12474 SDValue Addr, Disp;
12476 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12477 DAG.getConstant(10, MVT::i32));
12478 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12480 // This is storing the opcode for MOV32ri.
12481 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12482 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12483 OutChains[0] = DAG.getStore(Root, dl,
12484 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12485 Trmp, MachinePointerInfo(TrmpAddr),
12488 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12489 DAG.getConstant(1, MVT::i32));
12490 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12491 MachinePointerInfo(TrmpAddr, 1),
12494 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12495 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12496 DAG.getConstant(5, MVT::i32));
12497 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12498 MachinePointerInfo(TrmpAddr, 5),
12501 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12502 DAG.getConstant(6, MVT::i32));
12503 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12504 MachinePointerInfo(TrmpAddr, 6),
12507 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12511 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12512 SelectionDAG &DAG) const {
12514 The rounding mode is in bits 11:10 of FPSR, and has the following
12516 00 Round to nearest
12521 FLT_ROUNDS, on the other hand, expects the following:
12528 To perform the conversion, we do:
12529 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12532 MachineFunction &MF = DAG.getMachineFunction();
12533 const TargetMachine &TM = MF.getTarget();
12534 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12535 unsigned StackAlignment = TFI.getStackAlignment();
12536 MVT VT = Op.getSimpleValueType();
12539 // Save FP Control Word to stack slot
12540 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12541 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12543 MachineMemOperand *MMO =
12544 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12545 MachineMemOperand::MOStore, 2, 2);
12547 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12548 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12549 DAG.getVTList(MVT::Other),
12550 Ops, array_lengthof(Ops), MVT::i16,
12553 // Load FP Control Word from stack slot
12554 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12555 MachinePointerInfo(), false, false, false, 0);
12557 // Transform as necessary
12559 DAG.getNode(ISD::SRL, DL, MVT::i16,
12560 DAG.getNode(ISD::AND, DL, MVT::i16,
12561 CWD, DAG.getConstant(0x800, MVT::i16)),
12562 DAG.getConstant(11, MVT::i8));
12564 DAG.getNode(ISD::SRL, DL, MVT::i16,
12565 DAG.getNode(ISD::AND, DL, MVT::i16,
12566 CWD, DAG.getConstant(0x400, MVT::i16)),
12567 DAG.getConstant(9, MVT::i8));
12570 DAG.getNode(ISD::AND, DL, MVT::i16,
12571 DAG.getNode(ISD::ADD, DL, MVT::i16,
12572 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12573 DAG.getConstant(1, MVT::i16)),
12574 DAG.getConstant(3, MVT::i16));
12576 return DAG.getNode((VT.getSizeInBits() < 16 ?
12577 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12580 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12581 MVT VT = Op.getSimpleValueType();
12583 unsigned NumBits = VT.getSizeInBits();
12586 Op = Op.getOperand(0);
12587 if (VT == MVT::i8) {
12588 // Zero extend to i32 since there is not an i8 bsr.
12590 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12593 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12594 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12595 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12597 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12600 DAG.getConstant(NumBits+NumBits-1, OpVT),
12601 DAG.getConstant(X86::COND_E, MVT::i8),
12604 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12606 // Finally xor with NumBits-1.
12607 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12610 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12614 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12615 MVT VT = Op.getSimpleValueType();
12617 unsigned NumBits = VT.getSizeInBits();
12620 Op = Op.getOperand(0);
12621 if (VT == MVT::i8) {
12622 // Zero extend to i32 since there is not an i8 bsr.
12624 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12627 // Issue a bsr (scan bits in reverse).
12628 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12629 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12631 // And xor with NumBits-1.
12632 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12635 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12639 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12640 MVT VT = Op.getSimpleValueType();
12641 unsigned NumBits = VT.getSizeInBits();
12643 Op = Op.getOperand(0);
12645 // Issue a bsf (scan bits forward) which also sets EFLAGS.
12646 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12647 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12649 // If src is zero (i.e. bsf sets ZF), returns NumBits.
12652 DAG.getConstant(NumBits, VT),
12653 DAG.getConstant(X86::COND_E, MVT::i8),
12656 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12659 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12660 // ones, and then concatenate the result back.
12661 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12662 MVT VT = Op.getSimpleValueType();
12664 assert(VT.is256BitVector() && VT.isInteger() &&
12665 "Unsupported value type for operation");
12667 unsigned NumElems = VT.getVectorNumElements();
12670 // Extract the LHS vectors
12671 SDValue LHS = Op.getOperand(0);
12672 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12673 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12675 // Extract the RHS vectors
12676 SDValue RHS = Op.getOperand(1);
12677 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12678 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12680 MVT EltVT = VT.getVectorElementType();
12681 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12683 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12684 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12685 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12688 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12689 assert(Op.getSimpleValueType().is256BitVector() &&
12690 Op.getSimpleValueType().isInteger() &&
12691 "Only handle AVX 256-bit vector integer operation");
12692 return Lower256IntArith(Op, DAG);
12695 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12696 assert(Op.getSimpleValueType().is256BitVector() &&
12697 Op.getSimpleValueType().isInteger() &&
12698 "Only handle AVX 256-bit vector integer operation");
12699 return Lower256IntArith(Op, DAG);
12702 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12703 SelectionDAG &DAG) {
12705 MVT VT = Op.getSimpleValueType();
12707 // Decompose 256-bit ops into smaller 128-bit ops.
12708 if (VT.is256BitVector() && !Subtarget->hasInt256())
12709 return Lower256IntArith(Op, DAG);
12711 SDValue A = Op.getOperand(0);
12712 SDValue B = Op.getOperand(1);
12714 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12715 if (VT == MVT::v4i32) {
12716 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12717 "Should not custom lower when pmuldq is available!");
12719 // Extract the odd parts.
12720 static const int UnpackMask[] = { 1, -1, 3, -1 };
12721 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12722 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12724 // Multiply the even parts.
12725 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12726 // Now multiply odd parts.
12727 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12729 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12730 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12732 // Merge the two vectors back together with a shuffle. This expands into 2
12734 static const int ShufMask[] = { 0, 4, 2, 6 };
12735 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12738 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12739 "Only know how to lower V2I64/V4I64/V8I64 multiply");
12741 // Ahi = psrlqi(a, 32);
12742 // Bhi = psrlqi(b, 32);
12744 // AloBlo = pmuludq(a, b);
12745 // AloBhi = pmuludq(a, Bhi);
12746 // AhiBlo = pmuludq(Ahi, b);
12748 // AloBhi = psllqi(AloBhi, 32);
12749 // AhiBlo = psllqi(AhiBlo, 32);
12750 // return AloBlo + AloBhi + AhiBlo;
12752 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12753 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12755 // Bit cast to 32-bit vectors for MULUDQ
12756 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12757 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12758 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12759 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12760 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12761 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12763 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12764 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12765 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12767 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12768 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12770 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12771 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12774 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12775 MVT VT = Op.getSimpleValueType();
12776 MVT EltTy = VT.getVectorElementType();
12777 unsigned NumElts = VT.getVectorNumElements();
12778 SDValue N0 = Op.getOperand(0);
12781 // Lower sdiv X, pow2-const.
12782 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12786 APInt SplatValue, SplatUndef;
12787 unsigned SplatBitSize;
12789 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12791 EltTy.getSizeInBits() < SplatBitSize)
12794 if ((SplatValue != 0) &&
12795 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12796 unsigned Lg2 = SplatValue.countTrailingZeros();
12797 // Splat the sign bit.
12798 SmallVector<SDValue, 16> Sz(NumElts,
12799 DAG.getConstant(EltTy.getSizeInBits() - 1,
12801 SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12802 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12804 // Add (N0 < 0) ? abs2 - 1 : 0;
12805 SmallVector<SDValue, 16> Amt(NumElts,
12806 DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12808 SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12809 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12811 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12812 SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12813 SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12814 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12817 // If we're dividing by a positive value, we're done. Otherwise, we must
12818 // negate the result.
12819 if (SplatValue.isNonNegative())
12822 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12823 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12824 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12829 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12830 const X86Subtarget *Subtarget) {
12831 MVT VT = Op.getSimpleValueType();
12833 SDValue R = Op.getOperand(0);
12834 SDValue Amt = Op.getOperand(1);
12836 // Optimize shl/srl/sra with constant shift amount.
12837 if (isSplatVector(Amt.getNode())) {
12838 SDValue SclrAmt = Amt->getOperand(0);
12839 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12840 uint64_t ShiftAmt = C->getZExtValue();
12842 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12843 (Subtarget->hasInt256() &&
12844 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12845 (Subtarget->hasAVX512() &&
12846 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12847 if (Op.getOpcode() == ISD::SHL)
12848 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12850 if (Op.getOpcode() == ISD::SRL)
12851 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12853 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12854 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12858 if (VT == MVT::v16i8) {
12859 if (Op.getOpcode() == ISD::SHL) {
12860 // Make a large shift.
12861 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12862 MVT::v8i16, R, ShiftAmt,
12864 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12865 // Zero out the rightmost bits.
12866 SmallVector<SDValue, 16> V(16,
12867 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12869 return DAG.getNode(ISD::AND, dl, VT, SHL,
12870 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12872 if (Op.getOpcode() == ISD::SRL) {
12873 // Make a large shift.
12874 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12875 MVT::v8i16, R, ShiftAmt,
12877 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12878 // Zero out the leftmost bits.
12879 SmallVector<SDValue, 16> V(16,
12880 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12882 return DAG.getNode(ISD::AND, dl, VT, SRL,
12883 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12885 if (Op.getOpcode() == ISD::SRA) {
12886 if (ShiftAmt == 7) {
12887 // R s>> 7 === R s< 0
12888 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12889 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12892 // R s>> a === ((R u>> a) ^ m) - m
12893 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12894 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12896 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12897 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12898 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12901 llvm_unreachable("Unknown shift opcode.");
12904 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12905 if (Op.getOpcode() == ISD::SHL) {
12906 // Make a large shift.
12907 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12908 MVT::v16i16, R, ShiftAmt,
12910 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12911 // Zero out the rightmost bits.
12912 SmallVector<SDValue, 32> V(32,
12913 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12915 return DAG.getNode(ISD::AND, dl, VT, SHL,
12916 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12918 if (Op.getOpcode() == ISD::SRL) {
12919 // Make a large shift.
12920 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12921 MVT::v16i16, R, ShiftAmt,
12923 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12924 // Zero out the leftmost bits.
12925 SmallVector<SDValue, 32> V(32,
12926 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12928 return DAG.getNode(ISD::AND, dl, VT, SRL,
12929 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12931 if (Op.getOpcode() == ISD::SRA) {
12932 if (ShiftAmt == 7) {
12933 // R s>> 7 === R s< 0
12934 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12935 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12938 // R s>> a === ((R u>> a) ^ m) - m
12939 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12940 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12942 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12943 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12944 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12947 llvm_unreachable("Unknown shift opcode.");
12952 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12953 if (!Subtarget->is64Bit() &&
12954 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12955 Amt.getOpcode() == ISD::BITCAST &&
12956 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12957 Amt = Amt.getOperand(0);
12958 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
12959 VT.getVectorNumElements();
12960 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12961 uint64_t ShiftAmt = 0;
12962 for (unsigned i = 0; i != Ratio; ++i) {
12963 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12967 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12969 // Check remaining shift amounts.
12970 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12971 uint64_t ShAmt = 0;
12972 for (unsigned j = 0; j != Ratio; ++j) {
12973 ConstantSDNode *C =
12974 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12978 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12980 if (ShAmt != ShiftAmt)
12983 switch (Op.getOpcode()) {
12985 llvm_unreachable("Unknown shift opcode!");
12987 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12990 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12993 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13001 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13002 const X86Subtarget* Subtarget) {
13003 MVT VT = Op.getSimpleValueType();
13005 SDValue R = Op.getOperand(0);
13006 SDValue Amt = Op.getOperand(1);
13008 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13009 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13010 (Subtarget->hasInt256() &&
13011 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13012 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13013 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13015 EVT EltVT = VT.getVectorElementType();
13017 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13018 unsigned NumElts = VT.getVectorNumElements();
13020 for (i = 0; i != NumElts; ++i) {
13021 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13025 for (j = i; j != NumElts; ++j) {
13026 SDValue Arg = Amt.getOperand(j);
13027 if (Arg.getOpcode() == ISD::UNDEF) continue;
13028 if (Arg != Amt.getOperand(i))
13031 if (i != NumElts && j == NumElts)
13032 BaseShAmt = Amt.getOperand(i);
13034 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13035 Amt = Amt.getOperand(0);
13036 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13037 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13038 SDValue InVec = Amt.getOperand(0);
13039 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13040 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13042 for (; i != NumElts; ++i) {
13043 SDValue Arg = InVec.getOperand(i);
13044 if (Arg.getOpcode() == ISD::UNDEF) continue;
13048 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13049 if (ConstantSDNode *C =
13050 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13051 unsigned SplatIdx =
13052 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13053 if (C->getZExtValue() == SplatIdx)
13054 BaseShAmt = InVec.getOperand(1);
13057 if (BaseShAmt.getNode() == 0)
13058 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13059 DAG.getIntPtrConstant(0));
13063 if (BaseShAmt.getNode()) {
13064 if (EltVT.bitsGT(MVT::i32))
13065 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13066 else if (EltVT.bitsLT(MVT::i32))
13067 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13069 switch (Op.getOpcode()) {
13071 llvm_unreachable("Unknown shift opcode!");
13073 switch (VT.SimpleTy) {
13074 default: return SDValue();
13083 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13086 switch (VT.SimpleTy) {
13087 default: return SDValue();
13094 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13097 switch (VT.SimpleTy) {
13098 default: return SDValue();
13107 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13113 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13114 if (!Subtarget->is64Bit() &&
13115 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13116 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13117 Amt.getOpcode() == ISD::BITCAST &&
13118 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13119 Amt = Amt.getOperand(0);
13120 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13121 VT.getVectorNumElements();
13122 std::vector<SDValue> Vals(Ratio);
13123 for (unsigned i = 0; i != Ratio; ++i)
13124 Vals[i] = Amt.getOperand(i);
13125 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13126 for (unsigned j = 0; j != Ratio; ++j)
13127 if (Vals[j] != Amt.getOperand(i + j))
13130 switch (Op.getOpcode()) {
13132 llvm_unreachable("Unknown shift opcode!");
13134 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13136 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13138 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13145 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13146 SelectionDAG &DAG) {
13148 MVT VT = Op.getSimpleValueType();
13150 SDValue R = Op.getOperand(0);
13151 SDValue Amt = Op.getOperand(1);
13154 if (!Subtarget->hasSSE2())
13157 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13161 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13165 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13167 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13168 if (Subtarget->hasInt256()) {
13169 if (Op.getOpcode() == ISD::SRL &&
13170 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13171 VT == MVT::v4i64 || VT == MVT::v8i32))
13173 if (Op.getOpcode() == ISD::SHL &&
13174 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13175 VT == MVT::v4i64 || VT == MVT::v8i32))
13177 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13181 // If possible, lower this packed shift into a vector multiply instead of
13182 // expanding it into a sequence of scalar shifts.
13183 // Do this only if the vector shift count is a constant build_vector.
13184 if (Op.getOpcode() == ISD::SHL &&
13185 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13186 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13187 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13188 SmallVector<SDValue, 8> Elts;
13189 EVT SVT = VT.getScalarType();
13190 unsigned SVTBits = SVT.getSizeInBits();
13191 const APInt &One = APInt(SVTBits, 1);
13192 unsigned NumElems = VT.getVectorNumElements();
13194 for (unsigned i=0; i !=NumElems; ++i) {
13195 SDValue Op = Amt->getOperand(i);
13196 if (Op->getOpcode() == ISD::UNDEF) {
13197 Elts.push_back(Op);
13201 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13202 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13203 uint64_t ShAmt = C.getZExtValue();
13204 if (ShAmt >= SVTBits) {
13205 Elts.push_back(DAG.getUNDEF(SVT));
13208 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13210 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13211 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13214 // Lower SHL with variable shift amount.
13215 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13216 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13218 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13219 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13220 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13221 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13224 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13225 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13228 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13229 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13231 // Turn 'a' into a mask suitable for VSELECT
13232 SDValue VSelM = DAG.getConstant(0x80, VT);
13233 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13234 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13236 SDValue CM1 = DAG.getConstant(0x0f, VT);
13237 SDValue CM2 = DAG.getConstant(0x3f, VT);
13239 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13240 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13241 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13242 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13243 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13246 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13247 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13248 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13250 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13251 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13252 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13253 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13254 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13257 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13258 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13259 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13261 // return VSELECT(r, r+r, a);
13262 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13263 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13267 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13268 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13269 // solution better.
13270 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13271 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13273 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13274 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13275 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13276 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13277 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13280 // Decompose 256-bit shifts into smaller 128-bit shifts.
13281 if (VT.is256BitVector()) {
13282 unsigned NumElems = VT.getVectorNumElements();
13283 MVT EltVT = VT.getVectorElementType();
13284 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13286 // Extract the two vectors
13287 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13288 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13290 // Recreate the shift amount vectors
13291 SDValue Amt1, Amt2;
13292 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13293 // Constant shift amount
13294 SmallVector<SDValue, 4> Amt1Csts;
13295 SmallVector<SDValue, 4> Amt2Csts;
13296 for (unsigned i = 0; i != NumElems/2; ++i)
13297 Amt1Csts.push_back(Amt->getOperand(i));
13298 for (unsigned i = NumElems/2; i != NumElems; ++i)
13299 Amt2Csts.push_back(Amt->getOperand(i));
13301 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13302 &Amt1Csts[0], NumElems/2);
13303 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13304 &Amt2Csts[0], NumElems/2);
13306 // Variable shift amount
13307 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13308 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13311 // Issue new vector shifts for the smaller types
13312 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13313 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13315 // Concatenate the result back
13316 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13322 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13323 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13324 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13325 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13326 // has only one use.
13327 SDNode *N = Op.getNode();
13328 SDValue LHS = N->getOperand(0);
13329 SDValue RHS = N->getOperand(1);
13330 unsigned BaseOp = 0;
13333 switch (Op.getOpcode()) {
13334 default: llvm_unreachable("Unknown ovf instruction!");
13336 // A subtract of one will be selected as a INC. Note that INC doesn't
13337 // set CF, so we can't do this for UADDO.
13338 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13340 BaseOp = X86ISD::INC;
13341 Cond = X86::COND_O;
13344 BaseOp = X86ISD::ADD;
13345 Cond = X86::COND_O;
13348 BaseOp = X86ISD::ADD;
13349 Cond = X86::COND_B;
13352 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13353 // set CF, so we can't do this for USUBO.
13354 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13356 BaseOp = X86ISD::DEC;
13357 Cond = X86::COND_O;
13360 BaseOp = X86ISD::SUB;
13361 Cond = X86::COND_O;
13364 BaseOp = X86ISD::SUB;
13365 Cond = X86::COND_B;
13368 BaseOp = X86ISD::SMUL;
13369 Cond = X86::COND_O;
13371 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13372 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13374 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13377 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13378 DAG.getConstant(X86::COND_O, MVT::i32),
13379 SDValue(Sum.getNode(), 2));
13381 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13385 // Also sets EFLAGS.
13386 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13387 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13390 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13391 DAG.getConstant(Cond, MVT::i32),
13392 SDValue(Sum.getNode(), 1));
13394 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13397 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13398 SelectionDAG &DAG) const {
13400 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13401 MVT VT = Op.getSimpleValueType();
13403 if (!Subtarget->hasSSE2() || !VT.isVector())
13406 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13407 ExtraVT.getScalarType().getSizeInBits();
13409 switch (VT.SimpleTy) {
13410 default: return SDValue();
13413 if (!Subtarget->hasFp256())
13415 if (!Subtarget->hasInt256()) {
13416 // needs to be split
13417 unsigned NumElems = VT.getVectorNumElements();
13419 // Extract the LHS vectors
13420 SDValue LHS = Op.getOperand(0);
13421 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13422 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13424 MVT EltVT = VT.getVectorElementType();
13425 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13427 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13428 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13429 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13431 SDValue Extra = DAG.getValueType(ExtraVT);
13433 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13434 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13436 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13441 SDValue Op0 = Op.getOperand(0);
13442 SDValue Op00 = Op0.getOperand(0);
13444 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13445 if (Op0.getOpcode() == ISD::BITCAST &&
13446 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13447 // (sext (vzext x)) -> (vsext x)
13448 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13449 if (Tmp1.getNode()) {
13450 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13451 // This folding is only valid when the in-reg type is a vector of i8,
13453 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13454 ExtraEltVT == MVT::i32) {
13455 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13456 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13457 "This optimization is invalid without a VZEXT.");
13458 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13464 // If the above didn't work, then just use Shift-Left + Shift-Right.
13465 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13467 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13473 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13474 SelectionDAG &DAG) {
13476 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13477 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13478 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13479 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13481 // The only fence that needs an instruction is a sequentially-consistent
13482 // cross-thread fence.
13483 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13484 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13485 // no-sse2). There isn't any reason to disable it if the target processor
13487 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13488 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13490 SDValue Chain = Op.getOperand(0);
13491 SDValue Zero = DAG.getConstant(0, MVT::i32);
13493 DAG.getRegister(X86::ESP, MVT::i32), // Base
13494 DAG.getTargetConstant(1, MVT::i8), // Scale
13495 DAG.getRegister(0, MVT::i32), // Index
13496 DAG.getTargetConstant(0, MVT::i32), // Disp
13497 DAG.getRegister(0, MVT::i32), // Segment.
13501 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13502 return SDValue(Res, 0);
13505 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13506 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13509 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13510 SelectionDAG &DAG) {
13511 MVT T = Op.getSimpleValueType();
13515 switch(T.SimpleTy) {
13516 default: llvm_unreachable("Invalid value type!");
13517 case MVT::i8: Reg = X86::AL; size = 1; break;
13518 case MVT::i16: Reg = X86::AX; size = 2; break;
13519 case MVT::i32: Reg = X86::EAX; size = 4; break;
13521 assert(Subtarget->is64Bit() && "Node not type legal!");
13522 Reg = X86::RAX; size = 8;
13525 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13526 Op.getOperand(2), SDValue());
13527 SDValue Ops[] = { cpIn.getValue(0),
13530 DAG.getTargetConstant(size, MVT::i8),
13531 cpIn.getValue(1) };
13532 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13533 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13534 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13535 Ops, array_lengthof(Ops), T, MMO);
13537 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13541 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13542 SelectionDAG &DAG) {
13543 assert(Subtarget->is64Bit() && "Result not type legalized?");
13544 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13545 SDValue TheChain = Op.getOperand(0);
13547 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13548 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13549 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13551 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13552 DAG.getConstant(32, MVT::i8));
13554 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13557 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13560 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13561 SelectionDAG &DAG) {
13562 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13563 MVT DstVT = Op.getSimpleValueType();
13564 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13565 Subtarget->hasMMX() && "Unexpected custom BITCAST");
13566 assert((DstVT == MVT::i64 ||
13567 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13568 "Unexpected custom BITCAST");
13569 // i64 <=> MMX conversions are Legal.
13570 if (SrcVT==MVT::i64 && DstVT.isVector())
13572 if (DstVT==MVT::i64 && SrcVT.isVector())
13574 // MMX <=> MMX conversions are Legal.
13575 if (SrcVT.isVector() && DstVT.isVector())
13577 // All other conversions need to be expanded.
13581 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13582 SDNode *Node = Op.getNode();
13584 EVT T = Node->getValueType(0);
13585 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13586 DAG.getConstant(0, T), Node->getOperand(2));
13587 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13588 cast<AtomicSDNode>(Node)->getMemoryVT(),
13589 Node->getOperand(0),
13590 Node->getOperand(1), negOp,
13591 cast<AtomicSDNode>(Node)->getSrcValue(),
13592 cast<AtomicSDNode>(Node)->getAlignment(),
13593 cast<AtomicSDNode>(Node)->getOrdering(),
13594 cast<AtomicSDNode>(Node)->getSynchScope());
13597 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13598 SDNode *Node = Op.getNode();
13600 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13602 // Convert seq_cst store -> xchg
13603 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13604 // FIXME: On 32-bit, store -> fist or movq would be more efficient
13605 // (The only way to get a 16-byte store is cmpxchg16b)
13606 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13607 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13608 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13609 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13610 cast<AtomicSDNode>(Node)->getMemoryVT(),
13611 Node->getOperand(0),
13612 Node->getOperand(1), Node->getOperand(2),
13613 cast<AtomicSDNode>(Node)->getMemOperand(),
13614 cast<AtomicSDNode>(Node)->getOrdering(),
13615 cast<AtomicSDNode>(Node)->getSynchScope());
13616 return Swap.getValue(1);
13618 // Other atomic stores have a simple pattern.
13622 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13623 EVT VT = Op.getNode()->getSimpleValueType(0);
13625 // Let legalize expand this if it isn't a legal type yet.
13626 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13629 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13632 bool ExtraOp = false;
13633 switch (Op.getOpcode()) {
13634 default: llvm_unreachable("Invalid code");
13635 case ISD::ADDC: Opc = X86ISD::ADD; break;
13636 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13637 case ISD::SUBC: Opc = X86ISD::SUB; break;
13638 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13642 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13644 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13645 Op.getOperand(1), Op.getOperand(2));
13648 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13649 SelectionDAG &DAG) {
13650 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13652 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13653 // which returns the values as { float, float } (in XMM0) or
13654 // { double, double } (which is returned in XMM0, XMM1).
13656 SDValue Arg = Op.getOperand(0);
13657 EVT ArgVT = Arg.getValueType();
13658 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13660 TargetLowering::ArgListTy Args;
13661 TargetLowering::ArgListEntry Entry;
13665 Entry.isSExt = false;
13666 Entry.isZExt = false;
13667 Args.push_back(Entry);
13669 bool isF64 = ArgVT == MVT::f64;
13670 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13671 // the small struct {f32, f32} is returned in (eax, edx). For f64,
13672 // the results are returned via SRet in memory.
13673 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
13674 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13675 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13677 Type *RetTy = isF64
13678 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13679 : (Type*)VectorType::get(ArgTy, 4);
13681 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13682 false, false, false, false, 0,
13683 CallingConv::C, /*isTaillCall=*/false,
13684 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13685 Callee, Args, DAG, dl);
13686 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13689 // Returned in xmm0 and xmm1.
13690 return CallResult.first;
13692 // Returned in bits 0:31 and 32:64 xmm0.
13693 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13694 CallResult.first, DAG.getIntPtrConstant(0));
13695 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13696 CallResult.first, DAG.getIntPtrConstant(1));
13697 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13698 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13701 /// LowerOperation - Provide custom lowering hooks for some operations.
13703 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13704 switch (Op.getOpcode()) {
13705 default: llvm_unreachable("Should not custom lower this!");
13706 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
13707 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13708 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
13709 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
13710 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
13711 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
13712 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
13713 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
13714 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13715 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
13716 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13717 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13718 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
13719 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
13720 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
13721 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
13722 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
13723 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
13724 case ISD::SHL_PARTS:
13725 case ISD::SRA_PARTS:
13726 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
13727 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
13728 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
13729 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
13730 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
13731 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13732 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
13733 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
13734 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
13735 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
13736 case ISD::FABS: return LowerFABS(Op, DAG);
13737 case ISD::FNEG: return LowerFNEG(Op, DAG);
13738 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
13739 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
13740 case ISD::SETCC: return LowerSETCC(Op, DAG);
13741 case ISD::SELECT: return LowerSELECT(Op, DAG);
13742 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
13743 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
13744 case ISD::VASTART: return LowerVASTART(Op, DAG);
13745 case ISD::VAARG: return LowerVAARG(Op, DAG);
13746 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
13747 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13748 case ISD::INTRINSIC_VOID:
13749 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13750 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
13751 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
13752 case ISD::FRAME_TO_ARGS_OFFSET:
13753 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13754 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13755 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
13756 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
13757 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
13758 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
13759 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
13760 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
13761 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
13762 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13763 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
13764 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
13767 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
13773 case ISD::UMULO: return LowerXALUO(Op, DAG);
13774 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13775 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
13779 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13780 case ISD::ADD: return LowerADD(Op, DAG);
13781 case ISD::SUB: return LowerSUB(Op, DAG);
13782 case ISD::SDIV: return LowerSDIV(Op, DAG);
13783 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
13787 static void ReplaceATOMIC_LOAD(SDNode *Node,
13788 SmallVectorImpl<SDValue> &Results,
13789 SelectionDAG &DAG) {
13791 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13793 // Convert wide load -> cmpxchg8b/cmpxchg16b
13794 // FIXME: On 32-bit, load -> fild or movq would be more efficient
13795 // (The only way to get a 16-byte load is cmpxchg16b)
13796 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13797 SDValue Zero = DAG.getConstant(0, VT);
13798 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13799 Node->getOperand(0),
13800 Node->getOperand(1), Zero, Zero,
13801 cast<AtomicSDNode>(Node)->getMemOperand(),
13802 cast<AtomicSDNode>(Node)->getOrdering(),
13803 cast<AtomicSDNode>(Node)->getOrdering(),
13804 cast<AtomicSDNode>(Node)->getSynchScope());
13805 Results.push_back(Swap.getValue(0));
13806 Results.push_back(Swap.getValue(1));
13810 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13811 SelectionDAG &DAG, unsigned NewOp) {
13813 assert (Node->getValueType(0) == MVT::i64 &&
13814 "Only know how to expand i64 atomics");
13816 SDValue Chain = Node->getOperand(0);
13817 SDValue In1 = Node->getOperand(1);
13818 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13819 Node->getOperand(2), DAG.getIntPtrConstant(0));
13820 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13821 Node->getOperand(2), DAG.getIntPtrConstant(1));
13822 SDValue Ops[] = { Chain, In1, In2L, In2H };
13823 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13825 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13826 cast<MemSDNode>(Node)->getMemOperand());
13827 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13828 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13829 Results.push_back(Result.getValue(2));
13832 /// ReplaceNodeResults - Replace a node with an illegal result type
13833 /// with a new node built out of custom code.
13834 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13835 SmallVectorImpl<SDValue>&Results,
13836 SelectionDAG &DAG) const {
13838 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13839 switch (N->getOpcode()) {
13841 llvm_unreachable("Do not know how to custom type legalize this operation!");
13842 case ISD::SIGN_EXTEND_INREG:
13847 // We don't want to expand or promote these.
13849 case ISD::FP_TO_SINT:
13850 case ISD::FP_TO_UINT: {
13851 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13853 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13856 std::pair<SDValue,SDValue> Vals =
13857 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13858 SDValue FIST = Vals.first, StackSlot = Vals.second;
13859 if (FIST.getNode() != 0) {
13860 EVT VT = N->getValueType(0);
13861 // Return a load from the stack slot.
13862 if (StackSlot.getNode() != 0)
13863 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13864 MachinePointerInfo(),
13865 false, false, false, 0));
13867 Results.push_back(FIST);
13871 case ISD::UINT_TO_FP: {
13872 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13873 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13874 N->getValueType(0) != MVT::v2f32)
13876 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13878 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13880 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13881 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13882 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13883 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13884 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13885 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13888 case ISD::FP_ROUND: {
13889 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13891 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13892 Results.push_back(V);
13895 case ISD::READCYCLECOUNTER: {
13896 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13897 SDValue TheChain = N->getOperand(0);
13898 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13899 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13901 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13903 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13904 SDValue Ops[] = { eax, edx };
13905 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13906 array_lengthof(Ops)));
13907 Results.push_back(edx.getValue(1));
13910 case ISD::ATOMIC_CMP_SWAP: {
13911 EVT T = N->getValueType(0);
13912 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13913 bool Regs64bit = T == MVT::i128;
13914 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13915 SDValue cpInL, cpInH;
13916 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13917 DAG.getConstant(0, HalfT));
13918 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13919 DAG.getConstant(1, HalfT));
13920 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13921 Regs64bit ? X86::RAX : X86::EAX,
13923 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13924 Regs64bit ? X86::RDX : X86::EDX,
13925 cpInH, cpInL.getValue(1));
13926 SDValue swapInL, swapInH;
13927 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13928 DAG.getConstant(0, HalfT));
13929 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13930 DAG.getConstant(1, HalfT));
13931 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13932 Regs64bit ? X86::RBX : X86::EBX,
13933 swapInL, cpInH.getValue(1));
13934 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13935 Regs64bit ? X86::RCX : X86::ECX,
13936 swapInH, swapInL.getValue(1));
13937 SDValue Ops[] = { swapInH.getValue(0),
13939 swapInH.getValue(1) };
13940 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13941 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13942 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13943 X86ISD::LCMPXCHG8_DAG;
13944 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13945 Ops, array_lengthof(Ops), T, MMO);
13946 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13947 Regs64bit ? X86::RAX : X86::EAX,
13948 HalfT, Result.getValue(1));
13949 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13950 Regs64bit ? X86::RDX : X86::EDX,
13951 HalfT, cpOutL.getValue(2));
13952 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13953 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13954 Results.push_back(cpOutH.getValue(1));
13957 case ISD::ATOMIC_LOAD_ADD:
13958 case ISD::ATOMIC_LOAD_AND:
13959 case ISD::ATOMIC_LOAD_NAND:
13960 case ISD::ATOMIC_LOAD_OR:
13961 case ISD::ATOMIC_LOAD_SUB:
13962 case ISD::ATOMIC_LOAD_XOR:
13963 case ISD::ATOMIC_LOAD_MAX:
13964 case ISD::ATOMIC_LOAD_MIN:
13965 case ISD::ATOMIC_LOAD_UMAX:
13966 case ISD::ATOMIC_LOAD_UMIN:
13967 case ISD::ATOMIC_SWAP: {
13969 switch (N->getOpcode()) {
13970 default: llvm_unreachable("Unexpected opcode");
13971 case ISD::ATOMIC_LOAD_ADD:
13972 Opc = X86ISD::ATOMADD64_DAG;
13974 case ISD::ATOMIC_LOAD_AND:
13975 Opc = X86ISD::ATOMAND64_DAG;
13977 case ISD::ATOMIC_LOAD_NAND:
13978 Opc = X86ISD::ATOMNAND64_DAG;
13980 case ISD::ATOMIC_LOAD_OR:
13981 Opc = X86ISD::ATOMOR64_DAG;
13983 case ISD::ATOMIC_LOAD_SUB:
13984 Opc = X86ISD::ATOMSUB64_DAG;
13986 case ISD::ATOMIC_LOAD_XOR:
13987 Opc = X86ISD::ATOMXOR64_DAG;
13989 case ISD::ATOMIC_LOAD_MAX:
13990 Opc = X86ISD::ATOMMAX64_DAG;
13992 case ISD::ATOMIC_LOAD_MIN:
13993 Opc = X86ISD::ATOMMIN64_DAG;
13995 case ISD::ATOMIC_LOAD_UMAX:
13996 Opc = X86ISD::ATOMUMAX64_DAG;
13998 case ISD::ATOMIC_LOAD_UMIN:
13999 Opc = X86ISD::ATOMUMIN64_DAG;
14001 case ISD::ATOMIC_SWAP:
14002 Opc = X86ISD::ATOMSWAP64_DAG;
14005 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14008 case ISD::ATOMIC_LOAD:
14009 ReplaceATOMIC_LOAD(N, Results, DAG);
14013 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14015 default: return NULL;
14016 case X86ISD::BSF: return "X86ISD::BSF";
14017 case X86ISD::BSR: return "X86ISD::BSR";
14018 case X86ISD::SHLD: return "X86ISD::SHLD";
14019 case X86ISD::SHRD: return "X86ISD::SHRD";
14020 case X86ISD::FAND: return "X86ISD::FAND";
14021 case X86ISD::FANDN: return "X86ISD::FANDN";
14022 case X86ISD::FOR: return "X86ISD::FOR";
14023 case X86ISD::FXOR: return "X86ISD::FXOR";
14024 case X86ISD::FSRL: return "X86ISD::FSRL";
14025 case X86ISD::FILD: return "X86ISD::FILD";
14026 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14027 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14028 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14029 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14030 case X86ISD::FLD: return "X86ISD::FLD";
14031 case X86ISD::FST: return "X86ISD::FST";
14032 case X86ISD::CALL: return "X86ISD::CALL";
14033 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14034 case X86ISD::BT: return "X86ISD::BT";
14035 case X86ISD::CMP: return "X86ISD::CMP";
14036 case X86ISD::COMI: return "X86ISD::COMI";
14037 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14038 case X86ISD::CMPM: return "X86ISD::CMPM";
14039 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14040 case X86ISD::SETCC: return "X86ISD::SETCC";
14041 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14042 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14043 case X86ISD::CMOV: return "X86ISD::CMOV";
14044 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14045 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14046 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14047 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14048 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14049 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14050 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14051 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14052 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14053 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14054 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14055 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14056 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14057 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14058 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14059 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14060 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14061 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14062 case X86ISD::HADD: return "X86ISD::HADD";
14063 case X86ISD::HSUB: return "X86ISD::HSUB";
14064 case X86ISD::FHADD: return "X86ISD::FHADD";
14065 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14066 case X86ISD::UMAX: return "X86ISD::UMAX";
14067 case X86ISD::UMIN: return "X86ISD::UMIN";
14068 case X86ISD::SMAX: return "X86ISD::SMAX";
14069 case X86ISD::SMIN: return "X86ISD::SMIN";
14070 case X86ISD::FMAX: return "X86ISD::FMAX";
14071 case X86ISD::FMIN: return "X86ISD::FMIN";
14072 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14073 case X86ISD::FMINC: return "X86ISD::FMINC";
14074 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14075 case X86ISD::FRCP: return "X86ISD::FRCP";
14076 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14077 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14078 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14079 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14080 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14081 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14082 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14083 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14084 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14085 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14086 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14087 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14088 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14089 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14090 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14091 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14092 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14093 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14094 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14095 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14096 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14097 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14098 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14099 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14100 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14101 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14102 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14103 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14104 case X86ISD::VSHL: return "X86ISD::VSHL";
14105 case X86ISD::VSRL: return "X86ISD::VSRL";
14106 case X86ISD::VSRA: return "X86ISD::VSRA";
14107 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14108 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14109 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14110 case X86ISD::CMPP: return "X86ISD::CMPP";
14111 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14112 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14113 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14114 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14115 case X86ISD::ADD: return "X86ISD::ADD";
14116 case X86ISD::SUB: return "X86ISD::SUB";
14117 case X86ISD::ADC: return "X86ISD::ADC";
14118 case X86ISD::SBB: return "X86ISD::SBB";
14119 case X86ISD::SMUL: return "X86ISD::SMUL";
14120 case X86ISD::UMUL: return "X86ISD::UMUL";
14121 case X86ISD::INC: return "X86ISD::INC";
14122 case X86ISD::DEC: return "X86ISD::DEC";
14123 case X86ISD::OR: return "X86ISD::OR";
14124 case X86ISD::XOR: return "X86ISD::XOR";
14125 case X86ISD::AND: return "X86ISD::AND";
14126 case X86ISD::BZHI: return "X86ISD::BZHI";
14127 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14128 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14129 case X86ISD::PTEST: return "X86ISD::PTEST";
14130 case X86ISD::TESTP: return "X86ISD::TESTP";
14131 case X86ISD::TESTM: return "X86ISD::TESTM";
14132 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14133 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14134 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14135 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14136 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14137 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14138 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14139 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14140 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14141 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14142 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14143 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14144 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14145 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14146 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14147 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14148 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14149 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14150 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14151 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14152 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14153 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14154 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14155 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14156 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14157 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14158 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14159 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14160 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14161 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14162 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14163 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14164 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14165 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14166 case X86ISD::SAHF: return "X86ISD::SAHF";
14167 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14168 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14169 case X86ISD::FMADD: return "X86ISD::FMADD";
14170 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14171 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14172 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14173 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14174 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14175 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14176 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14177 case X86ISD::XTEST: return "X86ISD::XTEST";
14181 // isLegalAddressingMode - Return true if the addressing mode represented
14182 // by AM is legal for this target, for a load/store of the specified type.
14183 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14185 // X86 supports extremely general addressing modes.
14186 CodeModel::Model M = getTargetMachine().getCodeModel();
14187 Reloc::Model R = getTargetMachine().getRelocationModel();
14189 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14190 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14195 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14197 // If a reference to this global requires an extra load, we can't fold it.
14198 if (isGlobalStubReference(GVFlags))
14201 // If BaseGV requires a register for the PIC base, we cannot also have a
14202 // BaseReg specified.
14203 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14206 // If lower 4G is not available, then we must use rip-relative addressing.
14207 if ((M != CodeModel::Small || R != Reloc::Static) &&
14208 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14212 switch (AM.Scale) {
14218 // These scales always work.
14223 // These scales are formed with basereg+scalereg. Only accept if there is
14228 default: // Other stuff never works.
14235 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14236 unsigned Bits = Ty->getScalarSizeInBits();
14238 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14239 // particularly cheaper than those without.
14243 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14244 // variable shifts just as cheap as scalar ones.
14245 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14248 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14249 // fully general vector.
14253 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14254 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14256 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14257 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14258 return NumBits1 > NumBits2;
14261 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14262 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14265 if (!isTypeLegal(EVT::getEVT(Ty1)))
14268 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14270 // Assuming the caller doesn't have a zeroext or signext return parameter,
14271 // truncation all the way down to i1 is valid.
14275 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14276 return isInt<32>(Imm);
14279 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14280 // Can also use sub to handle negated immediates.
14281 return isInt<32>(Imm);
14284 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14285 if (!VT1.isInteger() || !VT2.isInteger())
14287 unsigned NumBits1 = VT1.getSizeInBits();
14288 unsigned NumBits2 = VT2.getSizeInBits();
14289 return NumBits1 > NumBits2;
14292 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14293 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14294 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14297 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14298 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14299 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14302 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14303 EVT VT1 = Val.getValueType();
14304 if (isZExtFree(VT1, VT2))
14307 if (Val.getOpcode() != ISD::LOAD)
14310 if (!VT1.isSimple() || !VT1.isInteger() ||
14311 !VT2.isSimple() || !VT2.isInteger())
14314 switch (VT1.getSimpleVT().SimpleTy) {
14319 // X86 has 8, 16, and 32-bit zero-extending loads.
14327 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14328 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14331 VT = VT.getScalarType();
14333 if (!VT.isSimple())
14336 switch (VT.getSimpleVT().SimpleTy) {
14347 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14348 // i16 instructions are longer (0x66 prefix) and potentially slower.
14349 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14352 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14353 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14354 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14355 /// are assumed to be legal.
14357 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14359 if (!VT.isSimple())
14362 MVT SVT = VT.getSimpleVT();
14364 // Very little shuffling can be done for 64-bit vectors right now.
14365 if (VT.getSizeInBits() == 64)
14368 // FIXME: pshufb, blends, shifts.
14369 return (SVT.getVectorNumElements() == 2 ||
14370 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14371 isMOVLMask(M, SVT) ||
14372 isSHUFPMask(M, SVT) ||
14373 isPSHUFDMask(M, SVT) ||
14374 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14375 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14376 isPALIGNRMask(M, SVT, Subtarget) ||
14377 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14378 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14379 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14380 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14384 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14386 if (!VT.isSimple())
14389 MVT SVT = VT.getSimpleVT();
14390 unsigned NumElts = SVT.getVectorNumElements();
14391 // FIXME: This collection of masks seems suspect.
14394 if (NumElts == 4 && SVT.is128BitVector()) {
14395 return (isMOVLMask(Mask, SVT) ||
14396 isCommutedMOVLMask(Mask, SVT, true) ||
14397 isSHUFPMask(Mask, SVT) ||
14398 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14403 //===----------------------------------------------------------------------===//
14404 // X86 Scheduler Hooks
14405 //===----------------------------------------------------------------------===//
14407 /// Utility function to emit xbegin specifying the start of an RTM region.
14408 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14409 const TargetInstrInfo *TII) {
14410 DebugLoc DL = MI->getDebugLoc();
14412 const BasicBlock *BB = MBB->getBasicBlock();
14413 MachineFunction::iterator I = MBB;
14416 // For the v = xbegin(), we generate
14427 MachineBasicBlock *thisMBB = MBB;
14428 MachineFunction *MF = MBB->getParent();
14429 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14430 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14431 MF->insert(I, mainMBB);
14432 MF->insert(I, sinkMBB);
14434 // Transfer the remainder of BB and its successor edges to sinkMBB.
14435 sinkMBB->splice(sinkMBB->begin(), MBB,
14436 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14437 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14441 // # fallthrough to mainMBB
14442 // # abortion to sinkMBB
14443 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14444 thisMBB->addSuccessor(mainMBB);
14445 thisMBB->addSuccessor(sinkMBB);
14449 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14450 mainMBB->addSuccessor(sinkMBB);
14453 // EAX is live into the sinkMBB
14454 sinkMBB->addLiveIn(X86::EAX);
14455 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14456 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14459 MI->eraseFromParent();
14463 // Get CMPXCHG opcode for the specified data type.
14464 static unsigned getCmpXChgOpcode(EVT VT) {
14465 switch (VT.getSimpleVT().SimpleTy) {
14466 case MVT::i8: return X86::LCMPXCHG8;
14467 case MVT::i16: return X86::LCMPXCHG16;
14468 case MVT::i32: return X86::LCMPXCHG32;
14469 case MVT::i64: return X86::LCMPXCHG64;
14473 llvm_unreachable("Invalid operand size!");
14476 // Get LOAD opcode for the specified data type.
14477 static unsigned getLoadOpcode(EVT VT) {
14478 switch (VT.getSimpleVT().SimpleTy) {
14479 case MVT::i8: return X86::MOV8rm;
14480 case MVT::i16: return X86::MOV16rm;
14481 case MVT::i32: return X86::MOV32rm;
14482 case MVT::i64: return X86::MOV64rm;
14486 llvm_unreachable("Invalid operand size!");
14489 // Get opcode of the non-atomic one from the specified atomic instruction.
14490 static unsigned getNonAtomicOpcode(unsigned Opc) {
14492 case X86::ATOMAND8: return X86::AND8rr;
14493 case X86::ATOMAND16: return X86::AND16rr;
14494 case X86::ATOMAND32: return X86::AND32rr;
14495 case X86::ATOMAND64: return X86::AND64rr;
14496 case X86::ATOMOR8: return X86::OR8rr;
14497 case X86::ATOMOR16: return X86::OR16rr;
14498 case X86::ATOMOR32: return X86::OR32rr;
14499 case X86::ATOMOR64: return X86::OR64rr;
14500 case X86::ATOMXOR8: return X86::XOR8rr;
14501 case X86::ATOMXOR16: return X86::XOR16rr;
14502 case X86::ATOMXOR32: return X86::XOR32rr;
14503 case X86::ATOMXOR64: return X86::XOR64rr;
14505 llvm_unreachable("Unhandled atomic-load-op opcode!");
14508 // Get opcode of the non-atomic one from the specified atomic instruction with
14510 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14511 unsigned &ExtraOpc) {
14513 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14514 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14515 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14516 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14517 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14518 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14519 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14520 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14521 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14522 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14523 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14524 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14525 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14526 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14527 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14528 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14529 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14530 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14531 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14532 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14534 llvm_unreachable("Unhandled atomic-load-op opcode!");
14537 // Get opcode of the non-atomic one from the specified atomic instruction for
14538 // 64-bit data type on 32-bit target.
14539 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14541 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14542 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14543 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14544 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14545 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14546 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14547 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14548 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14549 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14550 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14552 llvm_unreachable("Unhandled atomic-load-op opcode!");
14555 // Get opcode of the non-atomic one from the specified atomic instruction for
14556 // 64-bit data type on 32-bit target with extra opcode.
14557 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14559 unsigned &ExtraOpc) {
14561 case X86::ATOMNAND6432:
14562 ExtraOpc = X86::NOT32r;
14563 HiOpc = X86::AND32rr;
14564 return X86::AND32rr;
14566 llvm_unreachable("Unhandled atomic-load-op opcode!");
14569 // Get pseudo CMOV opcode from the specified data type.
14570 static unsigned getPseudoCMOVOpc(EVT VT) {
14571 switch (VT.getSimpleVT().SimpleTy) {
14572 case MVT::i8: return X86::CMOV_GR8;
14573 case MVT::i16: return X86::CMOV_GR16;
14574 case MVT::i32: return X86::CMOV_GR32;
14578 llvm_unreachable("Unknown CMOV opcode!");
14581 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14582 // They will be translated into a spin-loop or compare-exchange loop from
14585 // dst = atomic-fetch-op MI.addr, MI.val
14591 // t1 = LOAD MI.addr
14593 // t4 = phi(t1, t3 / loop)
14594 // t2 = OP MI.val, t4
14596 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14602 MachineBasicBlock *
14603 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14604 MachineBasicBlock *MBB) const {
14605 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14606 DebugLoc DL = MI->getDebugLoc();
14608 MachineFunction *MF = MBB->getParent();
14609 MachineRegisterInfo &MRI = MF->getRegInfo();
14611 const BasicBlock *BB = MBB->getBasicBlock();
14612 MachineFunction::iterator I = MBB;
14615 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14616 "Unexpected number of operands");
14618 assert(MI->hasOneMemOperand() &&
14619 "Expected atomic-load-op to have one memoperand");
14621 // Memory Reference
14622 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14623 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14625 unsigned DstReg, SrcReg;
14626 unsigned MemOpndSlot;
14628 unsigned CurOp = 0;
14630 DstReg = MI->getOperand(CurOp++).getReg();
14631 MemOpndSlot = CurOp;
14632 CurOp += X86::AddrNumOperands;
14633 SrcReg = MI->getOperand(CurOp++).getReg();
14635 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14636 MVT::SimpleValueType VT = *RC->vt_begin();
14637 unsigned t1 = MRI.createVirtualRegister(RC);
14638 unsigned t2 = MRI.createVirtualRegister(RC);
14639 unsigned t3 = MRI.createVirtualRegister(RC);
14640 unsigned t4 = MRI.createVirtualRegister(RC);
14641 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14643 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14644 unsigned LOADOpc = getLoadOpcode(VT);
14646 // For the atomic load-arith operator, we generate
14649 // t1 = LOAD [MI.addr]
14651 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
14652 // t1 = OP MI.val, EAX
14654 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14660 MachineBasicBlock *thisMBB = MBB;
14661 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14662 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14663 MF->insert(I, mainMBB);
14664 MF->insert(I, sinkMBB);
14666 MachineInstrBuilder MIB;
14668 // Transfer the remainder of BB and its successor edges to sinkMBB.
14669 sinkMBB->splice(sinkMBB->begin(), MBB,
14670 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14671 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14674 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14675 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14676 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14678 NewMO.setIsKill(false);
14679 MIB.addOperand(NewMO);
14681 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14682 unsigned flags = (*MMOI)->getFlags();
14683 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14684 MachineMemOperand *MMO =
14685 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14686 (*MMOI)->getSize(),
14687 (*MMOI)->getBaseAlignment(),
14688 (*MMOI)->getTBAAInfo(),
14689 (*MMOI)->getRanges());
14690 MIB.addMemOperand(MMO);
14693 thisMBB->addSuccessor(mainMBB);
14696 MachineBasicBlock *origMainMBB = mainMBB;
14699 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14700 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14702 unsigned Opc = MI->getOpcode();
14705 llvm_unreachable("Unhandled atomic-load-op opcode!");
14706 case X86::ATOMAND8:
14707 case X86::ATOMAND16:
14708 case X86::ATOMAND32:
14709 case X86::ATOMAND64:
14711 case X86::ATOMOR16:
14712 case X86::ATOMOR32:
14713 case X86::ATOMOR64:
14714 case X86::ATOMXOR8:
14715 case X86::ATOMXOR16:
14716 case X86::ATOMXOR32:
14717 case X86::ATOMXOR64: {
14718 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14719 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14723 case X86::ATOMNAND8:
14724 case X86::ATOMNAND16:
14725 case X86::ATOMNAND32:
14726 case X86::ATOMNAND64: {
14727 unsigned Tmp = MRI.createVirtualRegister(RC);
14729 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14730 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14732 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14735 case X86::ATOMMAX8:
14736 case X86::ATOMMAX16:
14737 case X86::ATOMMAX32:
14738 case X86::ATOMMAX64:
14739 case X86::ATOMMIN8:
14740 case X86::ATOMMIN16:
14741 case X86::ATOMMIN32:
14742 case X86::ATOMMIN64:
14743 case X86::ATOMUMAX8:
14744 case X86::ATOMUMAX16:
14745 case X86::ATOMUMAX32:
14746 case X86::ATOMUMAX64:
14747 case X86::ATOMUMIN8:
14748 case X86::ATOMUMIN16:
14749 case X86::ATOMUMIN32:
14750 case X86::ATOMUMIN64: {
14752 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14754 BuildMI(mainMBB, DL, TII->get(CMPOpc))
14758 if (Subtarget->hasCMov()) {
14759 if (VT != MVT::i8) {
14761 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14765 // Promote i8 to i32 to use CMOV32
14766 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14767 const TargetRegisterClass *RC32 =
14768 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14769 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14770 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14771 unsigned Tmp = MRI.createVirtualRegister(RC32);
14773 unsigned Undef = MRI.createVirtualRegister(RC32);
14774 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14776 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14779 .addImm(X86::sub_8bit);
14780 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14783 .addImm(X86::sub_8bit);
14785 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14789 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14790 .addReg(Tmp, 0, X86::sub_8bit);
14793 // Use pseudo select and lower them.
14794 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14795 "Invalid atomic-load-op transformation!");
14796 unsigned SelOpc = getPseudoCMOVOpc(VT);
14797 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14798 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14799 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14800 .addReg(SrcReg).addReg(t4)
14802 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14803 // Replace the original PHI node as mainMBB is changed after CMOV
14805 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14806 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14807 Phi->eraseFromParent();
14813 // Copy PhyReg back from virtual register.
14814 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14817 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14818 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14819 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14821 NewMO.setIsKill(false);
14822 MIB.addOperand(NewMO);
14825 MIB.setMemRefs(MMOBegin, MMOEnd);
14827 // Copy PhyReg back to virtual register.
14828 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14831 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14833 mainMBB->addSuccessor(origMainMBB);
14834 mainMBB->addSuccessor(sinkMBB);
14837 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14838 TII->get(TargetOpcode::COPY), DstReg)
14841 MI->eraseFromParent();
14845 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14846 // instructions. They will be translated into a spin-loop or compare-exchange
14850 // dst = atomic-fetch-op MI.addr, MI.val
14856 // t1L = LOAD [MI.addr + 0]
14857 // t1H = LOAD [MI.addr + 4]
14859 // t4L = phi(t1L, t3L / loop)
14860 // t4H = phi(t1H, t3H / loop)
14861 // t2L = OP MI.val.lo, t4L
14862 // t2H = OP MI.val.hi, t4H
14867 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14875 MachineBasicBlock *
14876 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14877 MachineBasicBlock *MBB) const {
14878 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14879 DebugLoc DL = MI->getDebugLoc();
14881 MachineFunction *MF = MBB->getParent();
14882 MachineRegisterInfo &MRI = MF->getRegInfo();
14884 const BasicBlock *BB = MBB->getBasicBlock();
14885 MachineFunction::iterator I = MBB;
14888 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14889 "Unexpected number of operands");
14891 assert(MI->hasOneMemOperand() &&
14892 "Expected atomic-load-op32 to have one memoperand");
14894 // Memory Reference
14895 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14896 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14898 unsigned DstLoReg, DstHiReg;
14899 unsigned SrcLoReg, SrcHiReg;
14900 unsigned MemOpndSlot;
14902 unsigned CurOp = 0;
14904 DstLoReg = MI->getOperand(CurOp++).getReg();
14905 DstHiReg = MI->getOperand(CurOp++).getReg();
14906 MemOpndSlot = CurOp;
14907 CurOp += X86::AddrNumOperands;
14908 SrcLoReg = MI->getOperand(CurOp++).getReg();
14909 SrcHiReg = MI->getOperand(CurOp++).getReg();
14911 const TargetRegisterClass *RC = &X86::GR32RegClass;
14912 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14914 unsigned t1L = MRI.createVirtualRegister(RC);
14915 unsigned t1H = MRI.createVirtualRegister(RC);
14916 unsigned t2L = MRI.createVirtualRegister(RC);
14917 unsigned t2H = MRI.createVirtualRegister(RC);
14918 unsigned t3L = MRI.createVirtualRegister(RC);
14919 unsigned t3H = MRI.createVirtualRegister(RC);
14920 unsigned t4L = MRI.createVirtualRegister(RC);
14921 unsigned t4H = MRI.createVirtualRegister(RC);
14923 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14924 unsigned LOADOpc = X86::MOV32rm;
14926 // For the atomic load-arith operator, we generate
14929 // t1L = LOAD [MI.addr + 0]
14930 // t1H = LOAD [MI.addr + 4]
14932 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
14933 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
14934 // t2L = OP MI.val.lo, t4L
14935 // t2H = OP MI.val.hi, t4H
14938 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14946 MachineBasicBlock *thisMBB = MBB;
14947 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14948 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14949 MF->insert(I, mainMBB);
14950 MF->insert(I, sinkMBB);
14952 MachineInstrBuilder MIB;
14954 // Transfer the remainder of BB and its successor edges to sinkMBB.
14955 sinkMBB->splice(sinkMBB->begin(), MBB,
14956 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14957 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14961 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14962 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14963 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14965 NewMO.setIsKill(false);
14966 MIB.addOperand(NewMO);
14968 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14969 unsigned flags = (*MMOI)->getFlags();
14970 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14971 MachineMemOperand *MMO =
14972 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14973 (*MMOI)->getSize(),
14974 (*MMOI)->getBaseAlignment(),
14975 (*MMOI)->getTBAAInfo(),
14976 (*MMOI)->getRanges());
14977 MIB.addMemOperand(MMO);
14979 MachineInstr *LowMI = MIB;
14982 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14983 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14984 if (i == X86::AddrDisp) {
14985 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14987 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14989 NewMO.setIsKill(false);
14990 MIB.addOperand(NewMO);
14993 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14995 thisMBB->addSuccessor(mainMBB);
14998 MachineBasicBlock *origMainMBB = mainMBB;
15001 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15002 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15003 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15004 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15006 unsigned Opc = MI->getOpcode();
15009 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15010 case X86::ATOMAND6432:
15011 case X86::ATOMOR6432:
15012 case X86::ATOMXOR6432:
15013 case X86::ATOMADD6432:
15014 case X86::ATOMSUB6432: {
15016 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15017 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15019 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15023 case X86::ATOMNAND6432: {
15024 unsigned HiOpc, NOTOpc;
15025 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15026 unsigned TmpL = MRI.createVirtualRegister(RC);
15027 unsigned TmpH = MRI.createVirtualRegister(RC);
15028 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15030 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15032 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15033 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15036 case X86::ATOMMAX6432:
15037 case X86::ATOMMIN6432:
15038 case X86::ATOMUMAX6432:
15039 case X86::ATOMUMIN6432: {
15041 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15042 unsigned cL = MRI.createVirtualRegister(RC8);
15043 unsigned cH = MRI.createVirtualRegister(RC8);
15044 unsigned cL32 = MRI.createVirtualRegister(RC);
15045 unsigned cH32 = MRI.createVirtualRegister(RC);
15046 unsigned cc = MRI.createVirtualRegister(RC);
15047 // cl := cmp src_lo, lo
15048 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15049 .addReg(SrcLoReg).addReg(t4L);
15050 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15051 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15052 // ch := cmp src_hi, hi
15053 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15054 .addReg(SrcHiReg).addReg(t4H);
15055 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15056 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15057 // cc := if (src_hi == hi) ? cl : ch;
15058 if (Subtarget->hasCMov()) {
15059 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15060 .addReg(cH32).addReg(cL32);
15062 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15063 .addReg(cH32).addReg(cL32)
15064 .addImm(X86::COND_E);
15065 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15067 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15068 if (Subtarget->hasCMov()) {
15069 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15070 .addReg(SrcLoReg).addReg(t4L);
15071 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15072 .addReg(SrcHiReg).addReg(t4H);
15074 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15075 .addReg(SrcLoReg).addReg(t4L)
15076 .addImm(X86::COND_NE);
15077 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15078 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15079 // 2nd CMOV lowering.
15080 mainMBB->addLiveIn(X86::EFLAGS);
15081 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15082 .addReg(SrcHiReg).addReg(t4H)
15083 .addImm(X86::COND_NE);
15084 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15085 // Replace the original PHI node as mainMBB is changed after CMOV
15087 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15088 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15089 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15090 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15091 PhiL->eraseFromParent();
15092 PhiH->eraseFromParent();
15096 case X86::ATOMSWAP6432: {
15098 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15099 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15100 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15105 // Copy EDX:EAX back from HiReg:LoReg
15106 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15107 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15108 // Copy ECX:EBX from t1H:t1L
15109 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15110 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15112 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15113 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15114 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15116 NewMO.setIsKill(false);
15117 MIB.addOperand(NewMO);
15119 MIB.setMemRefs(MMOBegin, MMOEnd);
15121 // Copy EDX:EAX back to t3H:t3L
15122 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15123 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15125 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15127 mainMBB->addSuccessor(origMainMBB);
15128 mainMBB->addSuccessor(sinkMBB);
15131 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15132 TII->get(TargetOpcode::COPY), DstLoReg)
15134 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15135 TII->get(TargetOpcode::COPY), DstHiReg)
15138 MI->eraseFromParent();
15142 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15143 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15144 // in the .td file.
15145 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15146 const TargetInstrInfo *TII) {
15148 switch (MI->getOpcode()) {
15149 default: llvm_unreachable("illegal opcode!");
15150 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15151 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15152 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15153 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15154 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15155 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15156 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15157 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15160 DebugLoc dl = MI->getDebugLoc();
15161 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15163 unsigned NumArgs = MI->getNumOperands();
15164 for (unsigned i = 1; i < NumArgs; ++i) {
15165 MachineOperand &Op = MI->getOperand(i);
15166 if (!(Op.isReg() && Op.isImplicit()))
15167 MIB.addOperand(Op);
15169 if (MI->hasOneMemOperand())
15170 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15172 BuildMI(*BB, MI, dl,
15173 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15174 .addReg(X86::XMM0);
15176 MI->eraseFromParent();
15180 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15181 // defs in an instruction pattern
15182 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15183 const TargetInstrInfo *TII) {
15185 switch (MI->getOpcode()) {
15186 default: llvm_unreachable("illegal opcode!");
15187 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15188 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15189 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15190 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15191 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15192 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15193 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15194 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15197 DebugLoc dl = MI->getDebugLoc();
15198 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15200 unsigned NumArgs = MI->getNumOperands(); // remove the results
15201 for (unsigned i = 1; i < NumArgs; ++i) {
15202 MachineOperand &Op = MI->getOperand(i);
15203 if (!(Op.isReg() && Op.isImplicit()))
15204 MIB.addOperand(Op);
15206 if (MI->hasOneMemOperand())
15207 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15209 BuildMI(*BB, MI, dl,
15210 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15213 MI->eraseFromParent();
15217 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15218 const TargetInstrInfo *TII,
15219 const X86Subtarget* Subtarget) {
15220 DebugLoc dl = MI->getDebugLoc();
15222 // Address into RAX/EAX, other two args into ECX, EDX.
15223 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15224 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15225 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15226 for (int i = 0; i < X86::AddrNumOperands; ++i)
15227 MIB.addOperand(MI->getOperand(i));
15229 unsigned ValOps = X86::AddrNumOperands;
15230 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15231 .addReg(MI->getOperand(ValOps).getReg());
15232 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15233 .addReg(MI->getOperand(ValOps+1).getReg());
15235 // The instruction doesn't actually take any operands though.
15236 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15238 MI->eraseFromParent(); // The pseudo is gone now.
15242 MachineBasicBlock *
15243 X86TargetLowering::EmitVAARG64WithCustomInserter(
15245 MachineBasicBlock *MBB) const {
15246 // Emit va_arg instruction on X86-64.
15248 // Operands to this pseudo-instruction:
15249 // 0 ) Output : destination address (reg)
15250 // 1-5) Input : va_list address (addr, i64mem)
15251 // 6 ) ArgSize : Size (in bytes) of vararg type
15252 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15253 // 8 ) Align : Alignment of type
15254 // 9 ) EFLAGS (implicit-def)
15256 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15257 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15259 unsigned DestReg = MI->getOperand(0).getReg();
15260 MachineOperand &Base = MI->getOperand(1);
15261 MachineOperand &Scale = MI->getOperand(2);
15262 MachineOperand &Index = MI->getOperand(3);
15263 MachineOperand &Disp = MI->getOperand(4);
15264 MachineOperand &Segment = MI->getOperand(5);
15265 unsigned ArgSize = MI->getOperand(6).getImm();
15266 unsigned ArgMode = MI->getOperand(7).getImm();
15267 unsigned Align = MI->getOperand(8).getImm();
15269 // Memory Reference
15270 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15271 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15272 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15274 // Machine Information
15275 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15276 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15277 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15278 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15279 DebugLoc DL = MI->getDebugLoc();
15281 // struct va_list {
15284 // i64 overflow_area (address)
15285 // i64 reg_save_area (address)
15287 // sizeof(va_list) = 24
15288 // alignment(va_list) = 8
15290 unsigned TotalNumIntRegs = 6;
15291 unsigned TotalNumXMMRegs = 8;
15292 bool UseGPOffset = (ArgMode == 1);
15293 bool UseFPOffset = (ArgMode == 2);
15294 unsigned MaxOffset = TotalNumIntRegs * 8 +
15295 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15297 /* Align ArgSize to a multiple of 8 */
15298 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15299 bool NeedsAlign = (Align > 8);
15301 MachineBasicBlock *thisMBB = MBB;
15302 MachineBasicBlock *overflowMBB;
15303 MachineBasicBlock *offsetMBB;
15304 MachineBasicBlock *endMBB;
15306 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15307 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15308 unsigned OffsetReg = 0;
15310 if (!UseGPOffset && !UseFPOffset) {
15311 // If we only pull from the overflow region, we don't create a branch.
15312 // We don't need to alter control flow.
15313 OffsetDestReg = 0; // unused
15314 OverflowDestReg = DestReg;
15317 overflowMBB = thisMBB;
15320 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15321 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15322 // If not, pull from overflow_area. (branch to overflowMBB)
15327 // offsetMBB overflowMBB
15332 // Registers for the PHI in endMBB
15333 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15334 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15336 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15337 MachineFunction *MF = MBB->getParent();
15338 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15339 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15340 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15342 MachineFunction::iterator MBBIter = MBB;
15345 // Insert the new basic blocks
15346 MF->insert(MBBIter, offsetMBB);
15347 MF->insert(MBBIter, overflowMBB);
15348 MF->insert(MBBIter, endMBB);
15350 // Transfer the remainder of MBB and its successor edges to endMBB.
15351 endMBB->splice(endMBB->begin(), thisMBB,
15352 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15353 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15355 // Make offsetMBB and overflowMBB successors of thisMBB
15356 thisMBB->addSuccessor(offsetMBB);
15357 thisMBB->addSuccessor(overflowMBB);
15359 // endMBB is a successor of both offsetMBB and overflowMBB
15360 offsetMBB->addSuccessor(endMBB);
15361 overflowMBB->addSuccessor(endMBB);
15363 // Load the offset value into a register
15364 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15365 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15369 .addDisp(Disp, UseFPOffset ? 4 : 0)
15370 .addOperand(Segment)
15371 .setMemRefs(MMOBegin, MMOEnd);
15373 // Check if there is enough room left to pull this argument.
15374 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15376 .addImm(MaxOffset + 8 - ArgSizeA8);
15378 // Branch to "overflowMBB" if offset >= max
15379 // Fall through to "offsetMBB" otherwise
15380 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15381 .addMBB(overflowMBB);
15384 // In offsetMBB, emit code to use the reg_save_area.
15386 assert(OffsetReg != 0);
15388 // Read the reg_save_area address.
15389 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15390 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15395 .addOperand(Segment)
15396 .setMemRefs(MMOBegin, MMOEnd);
15398 // Zero-extend the offset
15399 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15400 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15403 .addImm(X86::sub_32bit);
15405 // Add the offset to the reg_save_area to get the final address.
15406 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15407 .addReg(OffsetReg64)
15408 .addReg(RegSaveReg);
15410 // Compute the offset for the next argument
15411 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15412 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15414 .addImm(UseFPOffset ? 16 : 8);
15416 // Store it back into the va_list.
15417 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15421 .addDisp(Disp, UseFPOffset ? 4 : 0)
15422 .addOperand(Segment)
15423 .addReg(NextOffsetReg)
15424 .setMemRefs(MMOBegin, MMOEnd);
15427 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15432 // Emit code to use overflow area
15435 // Load the overflow_area address into a register.
15436 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15437 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15442 .addOperand(Segment)
15443 .setMemRefs(MMOBegin, MMOEnd);
15445 // If we need to align it, do so. Otherwise, just copy the address
15446 // to OverflowDestReg.
15448 // Align the overflow address
15449 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15450 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15452 // aligned_addr = (addr + (align-1)) & ~(align-1)
15453 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15454 .addReg(OverflowAddrReg)
15457 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15459 .addImm(~(uint64_t)(Align-1));
15461 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15462 .addReg(OverflowAddrReg);
15465 // Compute the next overflow address after this argument.
15466 // (the overflow address should be kept 8-byte aligned)
15467 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15468 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15469 .addReg(OverflowDestReg)
15470 .addImm(ArgSizeA8);
15472 // Store the new overflow address.
15473 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15478 .addOperand(Segment)
15479 .addReg(NextAddrReg)
15480 .setMemRefs(MMOBegin, MMOEnd);
15482 // If we branched, emit the PHI to the front of endMBB.
15484 BuildMI(*endMBB, endMBB->begin(), DL,
15485 TII->get(X86::PHI), DestReg)
15486 .addReg(OffsetDestReg).addMBB(offsetMBB)
15487 .addReg(OverflowDestReg).addMBB(overflowMBB);
15490 // Erase the pseudo instruction
15491 MI->eraseFromParent();
15496 MachineBasicBlock *
15497 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15499 MachineBasicBlock *MBB) const {
15500 // Emit code to save XMM registers to the stack. The ABI says that the
15501 // number of registers to save is given in %al, so it's theoretically
15502 // possible to do an indirect jump trick to avoid saving all of them,
15503 // however this code takes a simpler approach and just executes all
15504 // of the stores if %al is non-zero. It's less code, and it's probably
15505 // easier on the hardware branch predictor, and stores aren't all that
15506 // expensive anyway.
15508 // Create the new basic blocks. One block contains all the XMM stores,
15509 // and one block is the final destination regardless of whether any
15510 // stores were performed.
15511 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15512 MachineFunction *F = MBB->getParent();
15513 MachineFunction::iterator MBBIter = MBB;
15515 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15516 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15517 F->insert(MBBIter, XMMSaveMBB);
15518 F->insert(MBBIter, EndMBB);
15520 // Transfer the remainder of MBB and its successor edges to EndMBB.
15521 EndMBB->splice(EndMBB->begin(), MBB,
15522 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15523 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15525 // The original block will now fall through to the XMM save block.
15526 MBB->addSuccessor(XMMSaveMBB);
15527 // The XMMSaveMBB will fall through to the end block.
15528 XMMSaveMBB->addSuccessor(EndMBB);
15530 // Now add the instructions.
15531 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15532 DebugLoc DL = MI->getDebugLoc();
15534 unsigned CountReg = MI->getOperand(0).getReg();
15535 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15536 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15538 if (!Subtarget->isTargetWin64()) {
15539 // If %al is 0, branch around the XMM save block.
15540 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15541 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15542 MBB->addSuccessor(EndMBB);
15545 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15546 // that was just emitted, but clearly shouldn't be "saved".
15547 assert((MI->getNumOperands() <= 3 ||
15548 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15549 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15550 && "Expected last argument to be EFLAGS");
15551 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15552 // In the XMM save block, save all the XMM argument registers.
15553 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15554 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15555 MachineMemOperand *MMO =
15556 F->getMachineMemOperand(
15557 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15558 MachineMemOperand::MOStore,
15559 /*Size=*/16, /*Align=*/16);
15560 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15561 .addFrameIndex(RegSaveFrameIndex)
15562 .addImm(/*Scale=*/1)
15563 .addReg(/*IndexReg=*/0)
15564 .addImm(/*Disp=*/Offset)
15565 .addReg(/*Segment=*/0)
15566 .addReg(MI->getOperand(i).getReg())
15567 .addMemOperand(MMO);
15570 MI->eraseFromParent(); // The pseudo instruction is gone now.
15575 // The EFLAGS operand of SelectItr might be missing a kill marker
15576 // because there were multiple uses of EFLAGS, and ISel didn't know
15577 // which to mark. Figure out whether SelectItr should have had a
15578 // kill marker, and set it if it should. Returns the correct kill
15580 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15581 MachineBasicBlock* BB,
15582 const TargetRegisterInfo* TRI) {
15583 // Scan forward through BB for a use/def of EFLAGS.
15584 MachineBasicBlock::iterator miI(std::next(SelectItr));
15585 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15586 const MachineInstr& mi = *miI;
15587 if (mi.readsRegister(X86::EFLAGS))
15589 if (mi.definesRegister(X86::EFLAGS))
15590 break; // Should have kill-flag - update below.
15593 // If we hit the end of the block, check whether EFLAGS is live into a
15595 if (miI == BB->end()) {
15596 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15597 sEnd = BB->succ_end();
15598 sItr != sEnd; ++sItr) {
15599 MachineBasicBlock* succ = *sItr;
15600 if (succ->isLiveIn(X86::EFLAGS))
15605 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15606 // out. SelectMI should have a kill flag on EFLAGS.
15607 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15611 MachineBasicBlock *
15612 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15613 MachineBasicBlock *BB) const {
15614 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15615 DebugLoc DL = MI->getDebugLoc();
15617 // To "insert" a SELECT_CC instruction, we actually have to insert the
15618 // diamond control-flow pattern. The incoming instruction knows the
15619 // destination vreg to set, the condition code register to branch on, the
15620 // true/false values to select between, and a branch opcode to use.
15621 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15622 MachineFunction::iterator It = BB;
15628 // cmpTY ccX, r1, r2
15630 // fallthrough --> copy0MBB
15631 MachineBasicBlock *thisMBB = BB;
15632 MachineFunction *F = BB->getParent();
15633 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15634 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15635 F->insert(It, copy0MBB);
15636 F->insert(It, sinkMBB);
15638 // If the EFLAGS register isn't dead in the terminator, then claim that it's
15639 // live into the sink and copy blocks.
15640 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15641 if (!MI->killsRegister(X86::EFLAGS) &&
15642 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15643 copy0MBB->addLiveIn(X86::EFLAGS);
15644 sinkMBB->addLiveIn(X86::EFLAGS);
15647 // Transfer the remainder of BB and its successor edges to sinkMBB.
15648 sinkMBB->splice(sinkMBB->begin(), BB,
15649 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15650 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15652 // Add the true and fallthrough blocks as its successors.
15653 BB->addSuccessor(copy0MBB);
15654 BB->addSuccessor(sinkMBB);
15656 // Create the conditional branch instruction.
15658 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15659 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15662 // %FalseValue = ...
15663 // # fallthrough to sinkMBB
15664 copy0MBB->addSuccessor(sinkMBB);
15667 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15669 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15670 TII->get(X86::PHI), MI->getOperand(0).getReg())
15671 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15672 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15674 MI->eraseFromParent(); // The pseudo instruction is gone now.
15678 MachineBasicBlock *
15679 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15680 bool Is64Bit) const {
15681 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15682 DebugLoc DL = MI->getDebugLoc();
15683 MachineFunction *MF = BB->getParent();
15684 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15686 assert(getTargetMachine().Options.EnableSegmentedStacks);
15688 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15689 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15692 // ... [Till the alloca]
15693 // If stacklet is not large enough, jump to mallocMBB
15696 // Allocate by subtracting from RSP
15697 // Jump to continueMBB
15700 // Allocate by call to runtime
15704 // [rest of original BB]
15707 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15708 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15709 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15711 MachineRegisterInfo &MRI = MF->getRegInfo();
15712 const TargetRegisterClass *AddrRegClass =
15713 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15715 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15716 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15717 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15718 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15719 sizeVReg = MI->getOperand(1).getReg(),
15720 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15722 MachineFunction::iterator MBBIter = BB;
15725 MF->insert(MBBIter, bumpMBB);
15726 MF->insert(MBBIter, mallocMBB);
15727 MF->insert(MBBIter, continueMBB);
15729 continueMBB->splice(continueMBB->begin(), BB,
15730 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15731 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15733 // Add code to the main basic block to check if the stack limit has been hit,
15734 // and if so, jump to mallocMBB otherwise to bumpMBB.
15735 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15736 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15737 .addReg(tmpSPVReg).addReg(sizeVReg);
15738 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15739 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15740 .addReg(SPLimitVReg);
15741 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15743 // bumpMBB simply decreases the stack pointer, since we know the current
15744 // stacklet has enough space.
15745 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15746 .addReg(SPLimitVReg);
15747 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15748 .addReg(SPLimitVReg);
15749 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15751 // Calls into a routine in libgcc to allocate more space from the heap.
15752 const uint32_t *RegMask =
15753 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15755 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15757 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15758 .addExternalSymbol("__morestack_allocate_stack_space")
15759 .addRegMask(RegMask)
15760 .addReg(X86::RDI, RegState::Implicit)
15761 .addReg(X86::RAX, RegState::ImplicitDefine);
15763 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15765 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15766 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15767 .addExternalSymbol("__morestack_allocate_stack_space")
15768 .addRegMask(RegMask)
15769 .addReg(X86::EAX, RegState::ImplicitDefine);
15773 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15776 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15777 .addReg(Is64Bit ? X86::RAX : X86::EAX);
15778 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15780 // Set up the CFG correctly.
15781 BB->addSuccessor(bumpMBB);
15782 BB->addSuccessor(mallocMBB);
15783 mallocMBB->addSuccessor(continueMBB);
15784 bumpMBB->addSuccessor(continueMBB);
15786 // Take care of the PHI nodes.
15787 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15788 MI->getOperand(0).getReg())
15789 .addReg(mallocPtrVReg).addMBB(mallocMBB)
15790 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15792 // Delete the original pseudo instruction.
15793 MI->eraseFromParent();
15796 return continueMBB;
15799 MachineBasicBlock *
15800 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15801 MachineBasicBlock *BB) const {
15802 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15803 DebugLoc DL = MI->getDebugLoc();
15805 assert(!Subtarget->isTargetMacho());
15807 // The lowering is pretty easy: we're just emitting the call to _alloca. The
15808 // non-trivial part is impdef of ESP.
15810 if (Subtarget->isTargetWin64()) {
15811 if (Subtarget->isTargetCygMing()) {
15812 // ___chkstk(Mingw64):
15813 // Clobbers R10, R11, RAX and EFLAGS.
15815 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15816 .addExternalSymbol("___chkstk")
15817 .addReg(X86::RAX, RegState::Implicit)
15818 .addReg(X86::RSP, RegState::Implicit)
15819 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15820 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15821 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15823 // __chkstk(MSVCRT): does not update stack pointer.
15824 // Clobbers R10, R11 and EFLAGS.
15825 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15826 .addExternalSymbol("__chkstk")
15827 .addReg(X86::RAX, RegState::Implicit)
15828 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15829 // RAX has the offset to be subtracted from RSP.
15830 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15835 const char *StackProbeSymbol =
15836 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15838 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15839 .addExternalSymbol(StackProbeSymbol)
15840 .addReg(X86::EAX, RegState::Implicit)
15841 .addReg(X86::ESP, RegState::Implicit)
15842 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15843 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15844 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15847 MI->eraseFromParent(); // The pseudo instruction is gone now.
15851 MachineBasicBlock *
15852 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15853 MachineBasicBlock *BB) const {
15854 // This is pretty easy. We're taking the value that we received from
15855 // our load from the relocation, sticking it in either RDI (x86-64)
15856 // or EAX and doing an indirect call. The return value will then
15857 // be in the normal return register.
15858 const X86InstrInfo *TII
15859 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15860 DebugLoc DL = MI->getDebugLoc();
15861 MachineFunction *F = BB->getParent();
15863 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15864 assert(MI->getOperand(3).isGlobal() && "This should be a global");
15866 // Get a register mask for the lowered call.
15867 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15868 // proper register mask.
15869 const uint32_t *RegMask =
15870 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15871 if (Subtarget->is64Bit()) {
15872 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15873 TII->get(X86::MOV64rm), X86::RDI)
15875 .addImm(0).addReg(0)
15876 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15877 MI->getOperand(3).getTargetFlags())
15879 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15880 addDirectMem(MIB, X86::RDI);
15881 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15882 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15883 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15884 TII->get(X86::MOV32rm), X86::EAX)
15886 .addImm(0).addReg(0)
15887 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15888 MI->getOperand(3).getTargetFlags())
15890 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15891 addDirectMem(MIB, X86::EAX);
15892 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15894 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15895 TII->get(X86::MOV32rm), X86::EAX)
15896 .addReg(TII->getGlobalBaseReg(F))
15897 .addImm(0).addReg(0)
15898 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15899 MI->getOperand(3).getTargetFlags())
15901 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15902 addDirectMem(MIB, X86::EAX);
15903 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15906 MI->eraseFromParent(); // The pseudo instruction is gone now.
15910 MachineBasicBlock *
15911 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15912 MachineBasicBlock *MBB) const {
15913 DebugLoc DL = MI->getDebugLoc();
15914 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15916 MachineFunction *MF = MBB->getParent();
15917 MachineRegisterInfo &MRI = MF->getRegInfo();
15919 const BasicBlock *BB = MBB->getBasicBlock();
15920 MachineFunction::iterator I = MBB;
15923 // Memory Reference
15924 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15925 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15928 unsigned MemOpndSlot = 0;
15930 unsigned CurOp = 0;
15932 DstReg = MI->getOperand(CurOp++).getReg();
15933 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15934 assert(RC->hasType(MVT::i32) && "Invalid destination!");
15935 unsigned mainDstReg = MRI.createVirtualRegister(RC);
15936 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15938 MemOpndSlot = CurOp;
15940 MVT PVT = getPointerTy();
15941 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15942 "Invalid Pointer Size!");
15944 // For v = setjmp(buf), we generate
15947 // buf[LabelOffset] = restoreMBB
15948 // SjLjSetup restoreMBB
15954 // v = phi(main, restore)
15959 MachineBasicBlock *thisMBB = MBB;
15960 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15961 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15962 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15963 MF->insert(I, mainMBB);
15964 MF->insert(I, sinkMBB);
15965 MF->push_back(restoreMBB);
15967 MachineInstrBuilder MIB;
15969 // Transfer the remainder of BB and its successor edges to sinkMBB.
15970 sinkMBB->splice(sinkMBB->begin(), MBB,
15971 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15972 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15975 unsigned PtrStoreOpc = 0;
15976 unsigned LabelReg = 0;
15977 const int64_t LabelOffset = 1 * PVT.getStoreSize();
15978 Reloc::Model RM = getTargetMachine().getRelocationModel();
15979 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15980 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15982 // Prepare IP either in reg or imm.
15983 if (!UseImmLabel) {
15984 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15985 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15986 LabelReg = MRI.createVirtualRegister(PtrRC);
15987 if (Subtarget->is64Bit()) {
15988 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15992 .addMBB(restoreMBB)
15995 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15996 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15997 .addReg(XII->getGlobalBaseReg(MF))
16000 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16004 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16006 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16007 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16008 if (i == X86::AddrDisp)
16009 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16011 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16014 MIB.addReg(LabelReg);
16016 MIB.addMBB(restoreMBB);
16017 MIB.setMemRefs(MMOBegin, MMOEnd);
16019 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16020 .addMBB(restoreMBB);
16022 const X86RegisterInfo *RegInfo =
16023 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16024 MIB.addRegMask(RegInfo->getNoPreservedMask());
16025 thisMBB->addSuccessor(mainMBB);
16026 thisMBB->addSuccessor(restoreMBB);
16030 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16031 mainMBB->addSuccessor(sinkMBB);
16034 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16035 TII->get(X86::PHI), DstReg)
16036 .addReg(mainDstReg).addMBB(mainMBB)
16037 .addReg(restoreDstReg).addMBB(restoreMBB);
16040 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16041 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16042 restoreMBB->addSuccessor(sinkMBB);
16044 MI->eraseFromParent();
16048 MachineBasicBlock *
16049 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16050 MachineBasicBlock *MBB) const {
16051 DebugLoc DL = MI->getDebugLoc();
16052 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16054 MachineFunction *MF = MBB->getParent();
16055 MachineRegisterInfo &MRI = MF->getRegInfo();
16057 // Memory Reference
16058 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16059 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16061 MVT PVT = getPointerTy();
16062 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16063 "Invalid Pointer Size!");
16065 const TargetRegisterClass *RC =
16066 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16067 unsigned Tmp = MRI.createVirtualRegister(RC);
16068 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16069 const X86RegisterInfo *RegInfo =
16070 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16071 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16072 unsigned SP = RegInfo->getStackRegister();
16074 MachineInstrBuilder MIB;
16076 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16077 const int64_t SPOffset = 2 * PVT.getStoreSize();
16079 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16080 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16083 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16084 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16085 MIB.addOperand(MI->getOperand(i));
16086 MIB.setMemRefs(MMOBegin, MMOEnd);
16088 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16089 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16090 if (i == X86::AddrDisp)
16091 MIB.addDisp(MI->getOperand(i), LabelOffset);
16093 MIB.addOperand(MI->getOperand(i));
16095 MIB.setMemRefs(MMOBegin, MMOEnd);
16097 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16098 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16099 if (i == X86::AddrDisp)
16100 MIB.addDisp(MI->getOperand(i), SPOffset);
16102 MIB.addOperand(MI->getOperand(i));
16104 MIB.setMemRefs(MMOBegin, MMOEnd);
16106 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16108 MI->eraseFromParent();
16112 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16113 // accumulator loops. Writing back to the accumulator allows the coalescer
16114 // to remove extra copies in the loop.
16115 MachineBasicBlock *
16116 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16117 MachineBasicBlock *MBB) const {
16118 MachineOperand &AddendOp = MI->getOperand(3);
16120 // Bail out early if the addend isn't a register - we can't switch these.
16121 if (!AddendOp.isReg())
16124 MachineFunction &MF = *MBB->getParent();
16125 MachineRegisterInfo &MRI = MF.getRegInfo();
16127 // Check whether the addend is defined by a PHI:
16128 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16129 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16130 if (!AddendDef.isPHI())
16133 // Look for the following pattern:
16135 // %addend = phi [%entry, 0], [%loop, %result]
16137 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16141 // %addend = phi [%entry, 0], [%loop, %result]
16143 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16145 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16146 assert(AddendDef.getOperand(i).isReg());
16147 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16148 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16149 if (&PHISrcInst == MI) {
16150 // Found a matching instruction.
16151 unsigned NewFMAOpc = 0;
16152 switch (MI->getOpcode()) {
16153 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16154 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16155 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16156 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16157 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16158 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16159 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16160 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16161 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16162 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16163 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16164 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16165 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16166 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16167 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16168 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16169 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16170 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16171 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16172 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16173 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16174 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16175 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16176 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16177 default: llvm_unreachable("Unrecognized FMA variant.");
16180 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16181 MachineInstrBuilder MIB =
16182 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16183 .addOperand(MI->getOperand(0))
16184 .addOperand(MI->getOperand(3))
16185 .addOperand(MI->getOperand(2))
16186 .addOperand(MI->getOperand(1));
16187 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16188 MI->eraseFromParent();
16195 MachineBasicBlock *
16196 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16197 MachineBasicBlock *BB) const {
16198 switch (MI->getOpcode()) {
16199 default: llvm_unreachable("Unexpected instr type to insert");
16200 case X86::TAILJMPd64:
16201 case X86::TAILJMPr64:
16202 case X86::TAILJMPm64:
16203 llvm_unreachable("TAILJMP64 would not be touched here.");
16204 case X86::TCRETURNdi64:
16205 case X86::TCRETURNri64:
16206 case X86::TCRETURNmi64:
16208 case X86::WIN_ALLOCA:
16209 return EmitLoweredWinAlloca(MI, BB);
16210 case X86::SEG_ALLOCA_32:
16211 return EmitLoweredSegAlloca(MI, BB, false);
16212 case X86::SEG_ALLOCA_64:
16213 return EmitLoweredSegAlloca(MI, BB, true);
16214 case X86::TLSCall_32:
16215 case X86::TLSCall_64:
16216 return EmitLoweredTLSCall(MI, BB);
16217 case X86::CMOV_GR8:
16218 case X86::CMOV_FR32:
16219 case X86::CMOV_FR64:
16220 case X86::CMOV_V4F32:
16221 case X86::CMOV_V2F64:
16222 case X86::CMOV_V2I64:
16223 case X86::CMOV_V8F32:
16224 case X86::CMOV_V4F64:
16225 case X86::CMOV_V4I64:
16226 case X86::CMOV_V16F32:
16227 case X86::CMOV_V8F64:
16228 case X86::CMOV_V8I64:
16229 case X86::CMOV_GR16:
16230 case X86::CMOV_GR32:
16231 case X86::CMOV_RFP32:
16232 case X86::CMOV_RFP64:
16233 case X86::CMOV_RFP80:
16234 return EmitLoweredSelect(MI, BB);
16236 case X86::FP32_TO_INT16_IN_MEM:
16237 case X86::FP32_TO_INT32_IN_MEM:
16238 case X86::FP32_TO_INT64_IN_MEM:
16239 case X86::FP64_TO_INT16_IN_MEM:
16240 case X86::FP64_TO_INT32_IN_MEM:
16241 case X86::FP64_TO_INT64_IN_MEM:
16242 case X86::FP80_TO_INT16_IN_MEM:
16243 case X86::FP80_TO_INT32_IN_MEM:
16244 case X86::FP80_TO_INT64_IN_MEM: {
16245 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16246 DebugLoc DL = MI->getDebugLoc();
16248 // Change the floating point control register to use "round towards zero"
16249 // mode when truncating to an integer value.
16250 MachineFunction *F = BB->getParent();
16251 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16252 addFrameReference(BuildMI(*BB, MI, DL,
16253 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16255 // Load the old value of the high byte of the control word...
16257 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16258 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16261 // Set the high part to be round to zero...
16262 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16265 // Reload the modified control word now...
16266 addFrameReference(BuildMI(*BB, MI, DL,
16267 TII->get(X86::FLDCW16m)), CWFrameIdx);
16269 // Restore the memory image of control word to original value
16270 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16273 // Get the X86 opcode to use.
16275 switch (MI->getOpcode()) {
16276 default: llvm_unreachable("illegal opcode!");
16277 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16278 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16279 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16280 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16281 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16282 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16283 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16284 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16285 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16289 MachineOperand &Op = MI->getOperand(0);
16291 AM.BaseType = X86AddressMode::RegBase;
16292 AM.Base.Reg = Op.getReg();
16294 AM.BaseType = X86AddressMode::FrameIndexBase;
16295 AM.Base.FrameIndex = Op.getIndex();
16297 Op = MI->getOperand(1);
16299 AM.Scale = Op.getImm();
16300 Op = MI->getOperand(2);
16302 AM.IndexReg = Op.getImm();
16303 Op = MI->getOperand(3);
16304 if (Op.isGlobal()) {
16305 AM.GV = Op.getGlobal();
16307 AM.Disp = Op.getImm();
16309 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16310 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16312 // Reload the original control word now.
16313 addFrameReference(BuildMI(*BB, MI, DL,
16314 TII->get(X86::FLDCW16m)), CWFrameIdx);
16316 MI->eraseFromParent(); // The pseudo instruction is gone now.
16319 // String/text processing lowering.
16320 case X86::PCMPISTRM128REG:
16321 case X86::VPCMPISTRM128REG:
16322 case X86::PCMPISTRM128MEM:
16323 case X86::VPCMPISTRM128MEM:
16324 case X86::PCMPESTRM128REG:
16325 case X86::VPCMPESTRM128REG:
16326 case X86::PCMPESTRM128MEM:
16327 case X86::VPCMPESTRM128MEM:
16328 assert(Subtarget->hasSSE42() &&
16329 "Target must have SSE4.2 or AVX features enabled");
16330 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16332 // String/text processing lowering.
16333 case X86::PCMPISTRIREG:
16334 case X86::VPCMPISTRIREG:
16335 case X86::PCMPISTRIMEM:
16336 case X86::VPCMPISTRIMEM:
16337 case X86::PCMPESTRIREG:
16338 case X86::VPCMPESTRIREG:
16339 case X86::PCMPESTRIMEM:
16340 case X86::VPCMPESTRIMEM:
16341 assert(Subtarget->hasSSE42() &&
16342 "Target must have SSE4.2 or AVX features enabled");
16343 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16345 // Thread synchronization.
16347 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16351 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16353 // Atomic Lowering.
16354 case X86::ATOMAND8:
16355 case X86::ATOMAND16:
16356 case X86::ATOMAND32:
16357 case X86::ATOMAND64:
16360 case X86::ATOMOR16:
16361 case X86::ATOMOR32:
16362 case X86::ATOMOR64:
16364 case X86::ATOMXOR16:
16365 case X86::ATOMXOR8:
16366 case X86::ATOMXOR32:
16367 case X86::ATOMXOR64:
16369 case X86::ATOMNAND8:
16370 case X86::ATOMNAND16:
16371 case X86::ATOMNAND32:
16372 case X86::ATOMNAND64:
16374 case X86::ATOMMAX8:
16375 case X86::ATOMMAX16:
16376 case X86::ATOMMAX32:
16377 case X86::ATOMMAX64:
16379 case X86::ATOMMIN8:
16380 case X86::ATOMMIN16:
16381 case X86::ATOMMIN32:
16382 case X86::ATOMMIN64:
16384 case X86::ATOMUMAX8:
16385 case X86::ATOMUMAX16:
16386 case X86::ATOMUMAX32:
16387 case X86::ATOMUMAX64:
16389 case X86::ATOMUMIN8:
16390 case X86::ATOMUMIN16:
16391 case X86::ATOMUMIN32:
16392 case X86::ATOMUMIN64:
16393 return EmitAtomicLoadArith(MI, BB);
16395 // This group does 64-bit operations on a 32-bit host.
16396 case X86::ATOMAND6432:
16397 case X86::ATOMOR6432:
16398 case X86::ATOMXOR6432:
16399 case X86::ATOMNAND6432:
16400 case X86::ATOMADD6432:
16401 case X86::ATOMSUB6432:
16402 case X86::ATOMMAX6432:
16403 case X86::ATOMMIN6432:
16404 case X86::ATOMUMAX6432:
16405 case X86::ATOMUMIN6432:
16406 case X86::ATOMSWAP6432:
16407 return EmitAtomicLoadArith6432(MI, BB);
16409 case X86::VASTART_SAVE_XMM_REGS:
16410 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16412 case X86::VAARG_64:
16413 return EmitVAARG64WithCustomInserter(MI, BB);
16415 case X86::EH_SjLj_SetJmp32:
16416 case X86::EH_SjLj_SetJmp64:
16417 return emitEHSjLjSetJmp(MI, BB);
16419 case X86::EH_SjLj_LongJmp32:
16420 case X86::EH_SjLj_LongJmp64:
16421 return emitEHSjLjLongJmp(MI, BB);
16423 case TargetOpcode::STACKMAP:
16424 case TargetOpcode::PATCHPOINT:
16425 return emitPatchPoint(MI, BB);
16427 case X86::VFMADDPDr213r:
16428 case X86::VFMADDPSr213r:
16429 case X86::VFMADDSDr213r:
16430 case X86::VFMADDSSr213r:
16431 case X86::VFMSUBPDr213r:
16432 case X86::VFMSUBPSr213r:
16433 case X86::VFMSUBSDr213r:
16434 case X86::VFMSUBSSr213r:
16435 case X86::VFNMADDPDr213r:
16436 case X86::VFNMADDPSr213r:
16437 case X86::VFNMADDSDr213r:
16438 case X86::VFNMADDSSr213r:
16439 case X86::VFNMSUBPDr213r:
16440 case X86::VFNMSUBPSr213r:
16441 case X86::VFNMSUBSDr213r:
16442 case X86::VFNMSUBSSr213r:
16443 case X86::VFMADDPDr213rY:
16444 case X86::VFMADDPSr213rY:
16445 case X86::VFMSUBPDr213rY:
16446 case X86::VFMSUBPSr213rY:
16447 case X86::VFNMADDPDr213rY:
16448 case X86::VFNMADDPSr213rY:
16449 case X86::VFNMSUBPDr213rY:
16450 case X86::VFNMSUBPSr213rY:
16451 return emitFMA3Instr(MI, BB);
16455 //===----------------------------------------------------------------------===//
16456 // X86 Optimization Hooks
16457 //===----------------------------------------------------------------------===//
16459 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16462 const SelectionDAG &DAG,
16463 unsigned Depth) const {
16464 unsigned BitWidth = KnownZero.getBitWidth();
16465 unsigned Opc = Op.getOpcode();
16466 assert((Opc >= ISD::BUILTIN_OP_END ||
16467 Opc == ISD::INTRINSIC_WO_CHAIN ||
16468 Opc == ISD::INTRINSIC_W_CHAIN ||
16469 Opc == ISD::INTRINSIC_VOID) &&
16470 "Should use MaskedValueIsZero if you don't know whether Op"
16471 " is a target node!");
16473 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16487 // These nodes' second result is a boolean.
16488 if (Op.getResNo() == 0)
16491 case X86ISD::SETCC:
16492 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16494 case ISD::INTRINSIC_WO_CHAIN: {
16495 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16496 unsigned NumLoBits = 0;
16499 case Intrinsic::x86_sse_movmsk_ps:
16500 case Intrinsic::x86_avx_movmsk_ps_256:
16501 case Intrinsic::x86_sse2_movmsk_pd:
16502 case Intrinsic::x86_avx_movmsk_pd_256:
16503 case Intrinsic::x86_mmx_pmovmskb:
16504 case Intrinsic::x86_sse2_pmovmskb_128:
16505 case Intrinsic::x86_avx2_pmovmskb: {
16506 // High bits of movmskp{s|d}, pmovmskb are known zero.
16508 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16509 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16510 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16511 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16512 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16513 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16514 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16515 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16517 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16526 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16527 unsigned Depth) const {
16528 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16529 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16530 return Op.getValueType().getScalarType().getSizeInBits();
16536 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16537 /// node is a GlobalAddress + offset.
16538 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16539 const GlobalValue* &GA,
16540 int64_t &Offset) const {
16541 if (N->getOpcode() == X86ISD::Wrapper) {
16542 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16543 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16544 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16548 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16551 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16552 /// same as extracting the high 128-bit part of 256-bit vector and then
16553 /// inserting the result into the low part of a new 256-bit vector
16554 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16555 EVT VT = SVOp->getValueType(0);
16556 unsigned NumElems = VT.getVectorNumElements();
16558 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16559 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16560 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16561 SVOp->getMaskElt(j) >= 0)
16567 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16568 /// same as extracting the low 128-bit part of 256-bit vector and then
16569 /// inserting the result into the high part of a new 256-bit vector
16570 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16571 EVT VT = SVOp->getValueType(0);
16572 unsigned NumElems = VT.getVectorNumElements();
16574 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16575 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16576 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16577 SVOp->getMaskElt(j) >= 0)
16583 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16584 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16585 TargetLowering::DAGCombinerInfo &DCI,
16586 const X86Subtarget* Subtarget) {
16588 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16589 SDValue V1 = SVOp->getOperand(0);
16590 SDValue V2 = SVOp->getOperand(1);
16591 EVT VT = SVOp->getValueType(0);
16592 unsigned NumElems = VT.getVectorNumElements();
16594 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16595 V2.getOpcode() == ISD::CONCAT_VECTORS) {
16599 // V UNDEF BUILD_VECTOR UNDEF
16601 // CONCAT_VECTOR CONCAT_VECTOR
16604 // RESULT: V + zero extended
16606 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16607 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16608 V1.getOperand(1).getOpcode() != ISD::UNDEF)
16611 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16614 // To match the shuffle mask, the first half of the mask should
16615 // be exactly the first vector, and all the rest a splat with the
16616 // first element of the second one.
16617 for (unsigned i = 0; i != NumElems/2; ++i)
16618 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16619 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16622 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16623 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16624 if (Ld->hasNUsesOfValue(1, 0)) {
16625 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16626 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16628 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16629 array_lengthof(Ops),
16631 Ld->getPointerInfo(),
16632 Ld->getAlignment(),
16633 false/*isVolatile*/, true/*ReadMem*/,
16634 false/*WriteMem*/);
16636 // Make sure the newly-created LOAD is in the same position as Ld in
16637 // terms of dependency. We create a TokenFactor for Ld and ResNode,
16638 // and update uses of Ld's output chain to use the TokenFactor.
16639 if (Ld->hasAnyUseOfValue(1)) {
16640 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16641 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16642 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16643 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16644 SDValue(ResNode.getNode(), 1));
16647 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16651 // Emit a zeroed vector and insert the desired subvector on its
16653 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16654 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16655 return DCI.CombineTo(N, InsV);
16658 //===--------------------------------------------------------------------===//
16659 // Combine some shuffles into subvector extracts and inserts:
16662 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16663 if (isShuffleHigh128VectorInsertLow(SVOp)) {
16664 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16665 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16666 return DCI.CombineTo(N, InsV);
16669 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16670 if (isShuffleLow128VectorInsertHigh(SVOp)) {
16671 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16672 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16673 return DCI.CombineTo(N, InsV);
16679 /// PerformShuffleCombine - Performs several different shuffle combines.
16680 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16681 TargetLowering::DAGCombinerInfo &DCI,
16682 const X86Subtarget *Subtarget) {
16684 EVT VT = N->getValueType(0);
16686 // Don't create instructions with illegal types after legalize types has run.
16687 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16688 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16691 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16692 if (Subtarget->hasFp256() && VT.is256BitVector() &&
16693 N->getOpcode() == ISD::VECTOR_SHUFFLE)
16694 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16696 // Only handle 128 wide vector from here on.
16697 if (!VT.is128BitVector())
16700 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16701 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16702 // consecutive, non-overlapping, and in the right order.
16703 SmallVector<SDValue, 16> Elts;
16704 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16705 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16707 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16710 /// PerformTruncateCombine - Converts truncate operation to
16711 /// a sequence of vector shuffle operations.
16712 /// It is possible when we truncate 256-bit vector to 128-bit vector
16713 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16714 TargetLowering::DAGCombinerInfo &DCI,
16715 const X86Subtarget *Subtarget) {
16719 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16720 /// specific shuffle of a load can be folded into a single element load.
16721 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16722 /// shuffles have been customed lowered so we need to handle those here.
16723 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16724 TargetLowering::DAGCombinerInfo &DCI) {
16725 if (DCI.isBeforeLegalizeOps())
16728 SDValue InVec = N->getOperand(0);
16729 SDValue EltNo = N->getOperand(1);
16731 if (!isa<ConstantSDNode>(EltNo))
16734 EVT VT = InVec.getValueType();
16736 bool HasShuffleIntoBitcast = false;
16737 if (InVec.getOpcode() == ISD::BITCAST) {
16738 // Don't duplicate a load with other uses.
16739 if (!InVec.hasOneUse())
16741 EVT BCVT = InVec.getOperand(0).getValueType();
16742 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16744 InVec = InVec.getOperand(0);
16745 HasShuffleIntoBitcast = true;
16748 if (!isTargetShuffle(InVec.getOpcode()))
16751 // Don't duplicate a load with other uses.
16752 if (!InVec.hasOneUse())
16755 SmallVector<int, 16> ShuffleMask;
16757 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16761 // Select the input vector, guarding against out of range extract vector.
16762 unsigned NumElems = VT.getVectorNumElements();
16763 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16764 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16765 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16766 : InVec.getOperand(1);
16768 // If inputs to shuffle are the same for both ops, then allow 2 uses
16769 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16771 if (LdNode.getOpcode() == ISD::BITCAST) {
16772 // Don't duplicate a load with other uses.
16773 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16776 AllowedUses = 1; // only allow 1 load use if we have a bitcast
16777 LdNode = LdNode.getOperand(0);
16780 if (!ISD::isNormalLoad(LdNode.getNode()))
16783 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16785 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16788 if (HasShuffleIntoBitcast) {
16789 // If there's a bitcast before the shuffle, check if the load type and
16790 // alignment is valid.
16791 unsigned Align = LN0->getAlignment();
16792 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16793 unsigned NewAlign = TLI.getDataLayout()->
16794 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16796 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16800 // All checks match so transform back to vector_shuffle so that DAG combiner
16801 // can finish the job
16804 // Create shuffle node taking into account the case that its a unary shuffle
16805 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16806 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16807 InVec.getOperand(0), Shuffle,
16809 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16810 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16814 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16815 /// generation and convert it from being a bunch of shuffles and extracts
16816 /// to a simple store and scalar loads to extract the elements.
16817 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16818 TargetLowering::DAGCombinerInfo &DCI) {
16819 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16820 if (NewOp.getNode())
16823 SDValue InputVector = N->getOperand(0);
16825 // Detect whether we are trying to convert from mmx to i32 and the bitcast
16826 // from mmx to v2i32 has a single usage.
16827 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16828 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16829 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16830 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16831 N->getValueType(0),
16832 InputVector.getNode()->getOperand(0));
16834 // Only operate on vectors of 4 elements, where the alternative shuffling
16835 // gets to be more expensive.
16836 if (InputVector.getValueType() != MVT::v4i32)
16839 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16840 // single use which is a sign-extend or zero-extend, and all elements are
16842 SmallVector<SDNode *, 4> Uses;
16843 unsigned ExtractedElements = 0;
16844 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16845 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16846 if (UI.getUse().getResNo() != InputVector.getResNo())
16849 SDNode *Extract = *UI;
16850 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16853 if (Extract->getValueType(0) != MVT::i32)
16855 if (!Extract->hasOneUse())
16857 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16858 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16860 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16863 // Record which element was extracted.
16864 ExtractedElements |=
16865 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16867 Uses.push_back(Extract);
16870 // If not all the elements were used, this may not be worthwhile.
16871 if (ExtractedElements != 15)
16874 // Ok, we've now decided to do the transformation.
16875 SDLoc dl(InputVector);
16877 // Store the value to a temporary stack slot.
16878 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16879 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16880 MachinePointerInfo(), false, false, 0);
16882 // Replace each use (extract) with a load of the appropriate element.
16883 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16884 UE = Uses.end(); UI != UE; ++UI) {
16885 SDNode *Extract = *UI;
16887 // cOMpute the element's address.
16888 SDValue Idx = Extract->getOperand(1);
16890 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16891 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16892 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16893 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16895 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16896 StackPtr, OffsetVal);
16898 // Load the scalar.
16899 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16900 ScalarAddr, MachinePointerInfo(),
16901 false, false, false, 0);
16903 // Replace the exact with the load.
16904 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16907 // The replacement was made in place; don't return anything.
16911 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16912 static std::pair<unsigned, bool>
16913 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16914 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16915 if (!VT.isVector())
16916 return std::make_pair(0, false);
16918 bool NeedSplit = false;
16919 switch (VT.getSimpleVT().SimpleTy) {
16920 default: return std::make_pair(0, false);
16924 if (!Subtarget->hasAVX2())
16926 if (!Subtarget->hasAVX())
16927 return std::make_pair(0, false);
16932 if (!Subtarget->hasSSE2())
16933 return std::make_pair(0, false);
16936 // SSE2 has only a small subset of the operations.
16937 bool hasUnsigned = Subtarget->hasSSE41() ||
16938 (Subtarget->hasSSE2() && VT == MVT::v16i8);
16939 bool hasSigned = Subtarget->hasSSE41() ||
16940 (Subtarget->hasSSE2() && VT == MVT::v8i16);
16942 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16945 // Check for x CC y ? x : y.
16946 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16947 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16952 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16955 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16958 Opc = hasSigned ? X86ISD::SMIN : 0; break;
16961 Opc = hasSigned ? X86ISD::SMAX : 0; break;
16963 // Check for x CC y ? y : x -- a min/max with reversed arms.
16964 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16965 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16970 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16973 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16976 Opc = hasSigned ? X86ISD::SMAX : 0; break;
16979 Opc = hasSigned ? X86ISD::SMIN : 0; break;
16983 return std::make_pair(Opc, NeedSplit);
16986 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16988 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16989 TargetLowering::DAGCombinerInfo &DCI,
16990 const X86Subtarget *Subtarget) {
16992 SDValue Cond = N->getOperand(0);
16993 // Get the LHS/RHS of the select.
16994 SDValue LHS = N->getOperand(1);
16995 SDValue RHS = N->getOperand(2);
16996 EVT VT = LHS.getValueType();
16997 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16999 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17000 // instructions match the semantics of the common C idiom x<y?x:y but not
17001 // x<=y?x:y, because of how they handle negative zero (which can be
17002 // ignored in unsafe-math mode).
17003 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17004 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17005 (Subtarget->hasSSE2() ||
17006 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17007 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17009 unsigned Opcode = 0;
17010 // Check for x CC y ? x : y.
17011 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17012 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17016 // Converting this to a min would handle NaNs incorrectly, and swapping
17017 // the operands would cause it to handle comparisons between positive
17018 // and negative zero incorrectly.
17019 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17020 if (!DAG.getTarget().Options.UnsafeFPMath &&
17021 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17023 std::swap(LHS, RHS);
17025 Opcode = X86ISD::FMIN;
17028 // Converting this to a min would handle comparisons between positive
17029 // and negative zero incorrectly.
17030 if (!DAG.getTarget().Options.UnsafeFPMath &&
17031 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17033 Opcode = X86ISD::FMIN;
17036 // Converting this to a min would handle both negative zeros and NaNs
17037 // incorrectly, but we can swap the operands to fix both.
17038 std::swap(LHS, RHS);
17042 Opcode = X86ISD::FMIN;
17046 // Converting this to a max would handle comparisons between positive
17047 // and negative zero incorrectly.
17048 if (!DAG.getTarget().Options.UnsafeFPMath &&
17049 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17051 Opcode = X86ISD::FMAX;
17054 // Converting this to a max would handle NaNs incorrectly, and swapping
17055 // the operands would cause it to handle comparisons between positive
17056 // and negative zero incorrectly.
17057 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17058 if (!DAG.getTarget().Options.UnsafeFPMath &&
17059 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17061 std::swap(LHS, RHS);
17063 Opcode = X86ISD::FMAX;
17066 // Converting this to a max would handle both negative zeros and NaNs
17067 // incorrectly, but we can swap the operands to fix both.
17068 std::swap(LHS, RHS);
17072 Opcode = X86ISD::FMAX;
17075 // Check for x CC y ? y : x -- a min/max with reversed arms.
17076 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17077 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17081 // Converting this to a min would handle comparisons between positive
17082 // and negative zero incorrectly, and swapping the operands would
17083 // cause it to handle NaNs incorrectly.
17084 if (!DAG.getTarget().Options.UnsafeFPMath &&
17085 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17086 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17088 std::swap(LHS, RHS);
17090 Opcode = X86ISD::FMIN;
17093 // Converting this to a min would handle NaNs incorrectly.
17094 if (!DAG.getTarget().Options.UnsafeFPMath &&
17095 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17097 Opcode = X86ISD::FMIN;
17100 // Converting this to a min would handle both negative zeros and NaNs
17101 // incorrectly, but we can swap the operands to fix both.
17102 std::swap(LHS, RHS);
17106 Opcode = X86ISD::FMIN;
17110 // Converting this to a max would handle NaNs incorrectly.
17111 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17113 Opcode = X86ISD::FMAX;
17116 // Converting this to a max would handle comparisons between positive
17117 // and negative zero incorrectly, and swapping the operands would
17118 // cause it to handle NaNs incorrectly.
17119 if (!DAG.getTarget().Options.UnsafeFPMath &&
17120 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17121 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17123 std::swap(LHS, RHS);
17125 Opcode = X86ISD::FMAX;
17128 // Converting this to a max would handle both negative zeros and NaNs
17129 // incorrectly, but we can swap the operands to fix both.
17130 std::swap(LHS, RHS);
17134 Opcode = X86ISD::FMAX;
17140 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17143 EVT CondVT = Cond.getValueType();
17144 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17145 CondVT.getVectorElementType() == MVT::i1) {
17146 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17147 // lowering on AVX-512. In this case we convert it to
17148 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17149 // The same situation for all 128 and 256-bit vectors of i8 and i16
17150 EVT OpVT = LHS.getValueType();
17151 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17152 (OpVT.getVectorElementType() == MVT::i8 ||
17153 OpVT.getVectorElementType() == MVT::i16)) {
17154 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17155 DCI.AddToWorklist(Cond.getNode());
17156 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17159 // If this is a select between two integer constants, try to do some
17161 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17162 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17163 // Don't do this for crazy integer types.
17164 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17165 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17166 // so that TrueC (the true value) is larger than FalseC.
17167 bool NeedsCondInvert = false;
17169 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17170 // Efficiently invertible.
17171 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17172 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17173 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17174 NeedsCondInvert = true;
17175 std::swap(TrueC, FalseC);
17178 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17179 if (FalseC->getAPIntValue() == 0 &&
17180 TrueC->getAPIntValue().isPowerOf2()) {
17181 if (NeedsCondInvert) // Invert the condition if needed.
17182 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17183 DAG.getConstant(1, Cond.getValueType()));
17185 // Zero extend the condition if needed.
17186 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17188 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17189 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17190 DAG.getConstant(ShAmt, MVT::i8));
17193 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17194 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17195 if (NeedsCondInvert) // Invert the condition if needed.
17196 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17197 DAG.getConstant(1, Cond.getValueType()));
17199 // Zero extend the condition if needed.
17200 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17201 FalseC->getValueType(0), Cond);
17202 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17203 SDValue(FalseC, 0));
17206 // Optimize cases that will turn into an LEA instruction. This requires
17207 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17208 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17209 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17210 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17212 bool isFastMultiplier = false;
17214 switch ((unsigned char)Diff) {
17216 case 1: // result = add base, cond
17217 case 2: // result = lea base( , cond*2)
17218 case 3: // result = lea base(cond, cond*2)
17219 case 4: // result = lea base( , cond*4)
17220 case 5: // result = lea base(cond, cond*4)
17221 case 8: // result = lea base( , cond*8)
17222 case 9: // result = lea base(cond, cond*8)
17223 isFastMultiplier = true;
17228 if (isFastMultiplier) {
17229 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17230 if (NeedsCondInvert) // Invert the condition if needed.
17231 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17232 DAG.getConstant(1, Cond.getValueType()));
17234 // Zero extend the condition if needed.
17235 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17237 // Scale the condition by the difference.
17239 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17240 DAG.getConstant(Diff, Cond.getValueType()));
17242 // Add the base if non-zero.
17243 if (FalseC->getAPIntValue() != 0)
17244 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17245 SDValue(FalseC, 0));
17252 // Canonicalize max and min:
17253 // (x > y) ? x : y -> (x >= y) ? x : y
17254 // (x < y) ? x : y -> (x <= y) ? x : y
17255 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17256 // the need for an extra compare
17257 // against zero. e.g.
17258 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17260 // testl %edi, %edi
17262 // cmovgl %edi, %eax
17266 // cmovsl %eax, %edi
17267 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17268 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17269 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17270 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17275 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17276 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17277 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17278 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17283 // Early exit check
17284 if (!TLI.isTypeLegal(VT))
17287 // Match VSELECTs into subs with unsigned saturation.
17288 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17289 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17290 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17291 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17292 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17294 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17295 // left side invert the predicate to simplify logic below.
17297 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17299 CC = ISD::getSetCCInverse(CC, true);
17300 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17304 if (Other.getNode() && Other->getNumOperands() == 2 &&
17305 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17306 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17307 SDValue CondRHS = Cond->getOperand(1);
17309 // Look for a general sub with unsigned saturation first.
17310 // x >= y ? x-y : 0 --> subus x, y
17311 // x > y ? x-y : 0 --> subus x, y
17312 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17313 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17314 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17316 // If the RHS is a constant we have to reverse the const canonicalization.
17317 // x > C-1 ? x+-C : 0 --> subus x, C
17318 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17319 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17320 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17321 if (CondRHS.getConstantOperandVal(0) == -A-1)
17322 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17323 DAG.getConstant(-A, VT));
17326 // Another special case: If C was a sign bit, the sub has been
17327 // canonicalized into a xor.
17328 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17329 // it's safe to decanonicalize the xor?
17330 // x s< 0 ? x^C : 0 --> subus x, C
17331 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17332 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17333 isSplatVector(OpRHS.getNode())) {
17334 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17336 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17341 // Try to match a min/max vector operation.
17342 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17343 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17344 unsigned Opc = ret.first;
17345 bool NeedSplit = ret.second;
17347 if (Opc && NeedSplit) {
17348 unsigned NumElems = VT.getVectorNumElements();
17349 // Extract the LHS vectors
17350 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17351 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17353 // Extract the RHS vectors
17354 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17355 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17357 // Create min/max for each subvector
17358 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17359 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17361 // Merge the result
17362 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17364 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17367 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17368 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17369 // Check if SETCC has already been promoted
17370 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17371 // Check that condition value type matches vselect operand type
17374 assert(Cond.getValueType().isVector() &&
17375 "vector select expects a vector selector!");
17377 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17378 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17380 if (!TValIsAllOnes && !FValIsAllZeros) {
17381 // Try invert the condition if true value is not all 1s and false value
17383 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17384 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17386 if (TValIsAllZeros || FValIsAllOnes) {
17387 SDValue CC = Cond.getOperand(2);
17388 ISD::CondCode NewCC =
17389 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17390 Cond.getOperand(0).getValueType().isInteger());
17391 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17392 std::swap(LHS, RHS);
17393 TValIsAllOnes = FValIsAllOnes;
17394 FValIsAllZeros = TValIsAllZeros;
17398 if (TValIsAllOnes || FValIsAllZeros) {
17401 if (TValIsAllOnes && FValIsAllZeros)
17403 else if (TValIsAllOnes)
17404 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17405 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17406 else if (FValIsAllZeros)
17407 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17408 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17410 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17414 // Try to fold this VSELECT into a MOVSS/MOVSD
17415 if (N->getOpcode() == ISD::VSELECT &&
17416 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17417 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17418 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17419 bool CanFold = false;
17420 unsigned NumElems = Cond.getNumOperands();
17424 if (isZero(Cond.getOperand(0))) {
17427 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17428 // fold (vselect <0,-1> -> (movsd A, B)
17429 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17430 CanFold = isAllOnes(Cond.getOperand(i));
17431 } else if (isAllOnes(Cond.getOperand(0))) {
17435 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17436 // fold (vselect <-1,0> -> (movsd B, A)
17437 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17438 CanFold = isZero(Cond.getOperand(i));
17442 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17443 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17444 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17447 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17448 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17449 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17450 // (v2i64 (bitcast B)))))
17452 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17453 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17454 // (v2f64 (bitcast B)))))
17456 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17457 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17458 // (v2i64 (bitcast A)))))
17460 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17461 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17462 // (v2f64 (bitcast A)))))
17464 CanFold = (isZero(Cond.getOperand(0)) &&
17465 isZero(Cond.getOperand(1)) &&
17466 isAllOnes(Cond.getOperand(2)) &&
17467 isAllOnes(Cond.getOperand(3)));
17469 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17470 isAllOnes(Cond.getOperand(1)) &&
17471 isZero(Cond.getOperand(2)) &&
17472 isZero(Cond.getOperand(3))) {
17474 std::swap(LHS, RHS);
17478 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17479 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17480 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17481 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17483 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17489 // If we know that this node is legal then we know that it is going to be
17490 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17491 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17492 // to simplify previous instructions.
17493 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17494 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17495 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17497 // Don't optimize vector selects that map to mask-registers.
17501 // Check all uses of that condition operand to check whether it will be
17502 // consumed by non-BLEND instructions, which may depend on all bits are set
17504 for (SDNode::use_iterator I = Cond->use_begin(),
17505 E = Cond->use_end(); I != E; ++I)
17506 if (I->getOpcode() != ISD::VSELECT)
17507 // TODO: Add other opcodes eventually lowered into BLEND.
17510 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17511 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17513 APInt KnownZero, KnownOne;
17514 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17515 DCI.isBeforeLegalizeOps());
17516 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17517 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17518 DCI.CommitTargetLoweringOpt(TLO);
17524 // Check whether a boolean test is testing a boolean value generated by
17525 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17528 // Simplify the following patterns:
17529 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17530 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17531 // to (Op EFLAGS Cond)
17533 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17534 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17535 // to (Op EFLAGS !Cond)
17537 // where Op could be BRCOND or CMOV.
17539 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17540 // Quit if not CMP and SUB with its value result used.
17541 if (Cmp.getOpcode() != X86ISD::CMP &&
17542 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17545 // Quit if not used as a boolean value.
17546 if (CC != X86::COND_E && CC != X86::COND_NE)
17549 // Check CMP operands. One of them should be 0 or 1 and the other should be
17550 // an SetCC or extended from it.
17551 SDValue Op1 = Cmp.getOperand(0);
17552 SDValue Op2 = Cmp.getOperand(1);
17555 const ConstantSDNode* C = 0;
17556 bool needOppositeCond = (CC == X86::COND_E);
17557 bool checkAgainstTrue = false; // Is it a comparison against 1?
17559 if ((C = dyn_cast<ConstantSDNode>(Op1)))
17561 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17563 else // Quit if all operands are not constants.
17566 if (C->getZExtValue() == 1) {
17567 needOppositeCond = !needOppositeCond;
17568 checkAgainstTrue = true;
17569 } else if (C->getZExtValue() != 0)
17570 // Quit if the constant is neither 0 or 1.
17573 bool truncatedToBoolWithAnd = false;
17574 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17575 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17576 SetCC.getOpcode() == ISD::TRUNCATE ||
17577 SetCC.getOpcode() == ISD::AND) {
17578 if (SetCC.getOpcode() == ISD::AND) {
17580 ConstantSDNode *CS;
17581 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17582 CS->getZExtValue() == 1)
17584 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17585 CS->getZExtValue() == 1)
17589 SetCC = SetCC.getOperand(OpIdx);
17590 truncatedToBoolWithAnd = true;
17592 SetCC = SetCC.getOperand(0);
17595 switch (SetCC.getOpcode()) {
17596 case X86ISD::SETCC_CARRY:
17597 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17598 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17599 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17600 // truncated to i1 using 'and'.
17601 if (checkAgainstTrue && !truncatedToBoolWithAnd)
17603 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17604 "Invalid use of SETCC_CARRY!");
17606 case X86ISD::SETCC:
17607 // Set the condition code or opposite one if necessary.
17608 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17609 if (needOppositeCond)
17610 CC = X86::GetOppositeBranchCondition(CC);
17611 return SetCC.getOperand(1);
17612 case X86ISD::CMOV: {
17613 // Check whether false/true value has canonical one, i.e. 0 or 1.
17614 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17615 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17616 // Quit if true value is not a constant.
17619 // Quit if false value is not a constant.
17621 SDValue Op = SetCC.getOperand(0);
17622 // Skip 'zext' or 'trunc' node.
17623 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17624 Op.getOpcode() == ISD::TRUNCATE)
17625 Op = Op.getOperand(0);
17626 // A special case for rdrand/rdseed, where 0 is set if false cond is
17628 if ((Op.getOpcode() != X86ISD::RDRAND &&
17629 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17632 // Quit if false value is not the constant 0 or 1.
17633 bool FValIsFalse = true;
17634 if (FVal && FVal->getZExtValue() != 0) {
17635 if (FVal->getZExtValue() != 1)
17637 // If FVal is 1, opposite cond is needed.
17638 needOppositeCond = !needOppositeCond;
17639 FValIsFalse = false;
17641 // Quit if TVal is not the constant opposite of FVal.
17642 if (FValIsFalse && TVal->getZExtValue() != 1)
17644 if (!FValIsFalse && TVal->getZExtValue() != 0)
17646 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17647 if (needOppositeCond)
17648 CC = X86::GetOppositeBranchCondition(CC);
17649 return SetCC.getOperand(3);
17656 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17657 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17658 TargetLowering::DAGCombinerInfo &DCI,
17659 const X86Subtarget *Subtarget) {
17662 // If the flag operand isn't dead, don't touch this CMOV.
17663 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17666 SDValue FalseOp = N->getOperand(0);
17667 SDValue TrueOp = N->getOperand(1);
17668 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17669 SDValue Cond = N->getOperand(3);
17671 if (CC == X86::COND_E || CC == X86::COND_NE) {
17672 switch (Cond.getOpcode()) {
17676 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17677 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17678 return (CC == X86::COND_E) ? FalseOp : TrueOp;
17684 Flags = checkBoolTestSetCCCombine(Cond, CC);
17685 if (Flags.getNode() &&
17686 // Extra check as FCMOV only supports a subset of X86 cond.
17687 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17688 SDValue Ops[] = { FalseOp, TrueOp,
17689 DAG.getConstant(CC, MVT::i8), Flags };
17690 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17691 Ops, array_lengthof(Ops));
17694 // If this is a select between two integer constants, try to do some
17695 // optimizations. Note that the operands are ordered the opposite of SELECT
17697 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17698 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17699 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17700 // larger than FalseC (the false value).
17701 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17702 CC = X86::GetOppositeBranchCondition(CC);
17703 std::swap(TrueC, FalseC);
17704 std::swap(TrueOp, FalseOp);
17707 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
17708 // This is efficient for any integer data type (including i8/i16) and
17710 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17711 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17712 DAG.getConstant(CC, MVT::i8), Cond);
17714 // Zero extend the condition if needed.
17715 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17717 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17718 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17719 DAG.getConstant(ShAmt, MVT::i8));
17720 if (N->getNumValues() == 2) // Dead flag value?
17721 return DCI.CombineTo(N, Cond, SDValue());
17725 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
17726 // for any integer data type, including i8/i16.
17727 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17728 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17729 DAG.getConstant(CC, MVT::i8), Cond);
17731 // Zero extend the condition if needed.
17732 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17733 FalseC->getValueType(0), Cond);
17734 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17735 SDValue(FalseC, 0));
17737 if (N->getNumValues() == 2) // Dead flag value?
17738 return DCI.CombineTo(N, Cond, SDValue());
17742 // Optimize cases that will turn into an LEA instruction. This requires
17743 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17744 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17745 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17746 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17748 bool isFastMultiplier = false;
17750 switch ((unsigned char)Diff) {
17752 case 1: // result = add base, cond
17753 case 2: // result = lea base( , cond*2)
17754 case 3: // result = lea base(cond, cond*2)
17755 case 4: // result = lea base( , cond*4)
17756 case 5: // result = lea base(cond, cond*4)
17757 case 8: // result = lea base( , cond*8)
17758 case 9: // result = lea base(cond, cond*8)
17759 isFastMultiplier = true;
17764 if (isFastMultiplier) {
17765 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17766 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17767 DAG.getConstant(CC, MVT::i8), Cond);
17768 // Zero extend the condition if needed.
17769 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17771 // Scale the condition by the difference.
17773 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17774 DAG.getConstant(Diff, Cond.getValueType()));
17776 // Add the base if non-zero.
17777 if (FalseC->getAPIntValue() != 0)
17778 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17779 SDValue(FalseC, 0));
17780 if (N->getNumValues() == 2) // Dead flag value?
17781 return DCI.CombineTo(N, Cond, SDValue());
17788 // Handle these cases:
17789 // (select (x != c), e, c) -> select (x != c), e, x),
17790 // (select (x == c), c, e) -> select (x == c), x, e)
17791 // where the c is an integer constant, and the "select" is the combination
17792 // of CMOV and CMP.
17794 // The rationale for this change is that the conditional-move from a constant
17795 // needs two instructions, however, conditional-move from a register needs
17796 // only one instruction.
17798 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17799 // some instruction-combining opportunities. This opt needs to be
17800 // postponed as late as possible.
17802 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17803 // the DCI.xxxx conditions are provided to postpone the optimization as
17804 // late as possible.
17806 ConstantSDNode *CmpAgainst = 0;
17807 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17808 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17809 !isa<ConstantSDNode>(Cond.getOperand(0))) {
17811 if (CC == X86::COND_NE &&
17812 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17813 CC = X86::GetOppositeBranchCondition(CC);
17814 std::swap(TrueOp, FalseOp);
17817 if (CC == X86::COND_E &&
17818 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17819 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17820 DAG.getConstant(CC, MVT::i8), Cond };
17821 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17822 array_lengthof(Ops));
17830 /// PerformMulCombine - Optimize a single multiply with constant into two
17831 /// in order to implement it with two cheaper instructions, e.g.
17832 /// LEA + SHL, LEA + LEA.
17833 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17834 TargetLowering::DAGCombinerInfo &DCI) {
17835 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17838 EVT VT = N->getValueType(0);
17839 if (VT != MVT::i64)
17842 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17845 uint64_t MulAmt = C->getZExtValue();
17846 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17849 uint64_t MulAmt1 = 0;
17850 uint64_t MulAmt2 = 0;
17851 if ((MulAmt % 9) == 0) {
17853 MulAmt2 = MulAmt / 9;
17854 } else if ((MulAmt % 5) == 0) {
17856 MulAmt2 = MulAmt / 5;
17857 } else if ((MulAmt % 3) == 0) {
17859 MulAmt2 = MulAmt / 3;
17862 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17865 if (isPowerOf2_64(MulAmt2) &&
17866 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17867 // If second multiplifer is pow2, issue it first. We want the multiply by
17868 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17870 std::swap(MulAmt1, MulAmt2);
17873 if (isPowerOf2_64(MulAmt1))
17874 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17875 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17877 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17878 DAG.getConstant(MulAmt1, VT));
17880 if (isPowerOf2_64(MulAmt2))
17881 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17882 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17884 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17885 DAG.getConstant(MulAmt2, VT));
17887 // Do not add new nodes to DAG combiner worklist.
17888 DCI.CombineTo(N, NewMul, false);
17893 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17894 SDValue N0 = N->getOperand(0);
17895 SDValue N1 = N->getOperand(1);
17896 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17897 EVT VT = N0.getValueType();
17899 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17900 // since the result of setcc_c is all zero's or all ones.
17901 if (VT.isInteger() && !VT.isVector() &&
17902 N1C && N0.getOpcode() == ISD::AND &&
17903 N0.getOperand(1).getOpcode() == ISD::Constant) {
17904 SDValue N00 = N0.getOperand(0);
17905 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17906 ((N00.getOpcode() == ISD::ANY_EXTEND ||
17907 N00.getOpcode() == ISD::ZERO_EXTEND) &&
17908 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17909 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17910 APInt ShAmt = N1C->getAPIntValue();
17911 Mask = Mask.shl(ShAmt);
17913 return DAG.getNode(ISD::AND, SDLoc(N), VT,
17914 N00, DAG.getConstant(Mask, VT));
17918 // Hardware support for vector shifts is sparse which makes us scalarize the
17919 // vector operations in many cases. Also, on sandybridge ADD is faster than
17921 // (shl V, 1) -> add V,V
17922 if (isSplatVector(N1.getNode())) {
17923 assert(N0.getValueType().isVector() && "Invalid vector shift type");
17924 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17925 // We shift all of the values by one. In many cases we do not have
17926 // hardware support for this operation. This is better expressed as an ADD
17928 if (N1C && (1 == N1C->getZExtValue())) {
17929 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17936 /// \brief Returns a vector of 0s if the node in input is a vector logical
17937 /// shift by a constant amount which is known to be bigger than or equal
17938 /// to the vector element size in bits.
17939 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17940 const X86Subtarget *Subtarget) {
17941 EVT VT = N->getValueType(0);
17943 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17944 (!Subtarget->hasInt256() ||
17945 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17948 SDValue Amt = N->getOperand(1);
17950 if (isSplatVector(Amt.getNode())) {
17951 SDValue SclrAmt = Amt->getOperand(0);
17952 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
17953 APInt ShiftAmt = C->getAPIntValue();
17954 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
17956 // SSE2/AVX2 logical shifts always return a vector of 0s
17957 // if the shift amount is bigger than or equal to
17958 // the element size. The constant shift amount will be
17959 // encoded as a 8-bit immediate.
17960 if (ShiftAmt.trunc(8).uge(MaxAmount))
17961 return getZeroVector(VT, Subtarget, DAG, DL);
17968 /// PerformShiftCombine - Combine shifts.
17969 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
17970 TargetLowering::DAGCombinerInfo &DCI,
17971 const X86Subtarget *Subtarget) {
17972 if (N->getOpcode() == ISD::SHL) {
17973 SDValue V = PerformSHLCombine(N, DAG);
17974 if (V.getNode()) return V;
17977 if (N->getOpcode() != ISD::SRA) {
17978 // Try to fold this logical shift into a zero vector.
17979 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
17980 if (V.getNode()) return V;
17986 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
17987 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
17988 // and friends. Likewise for OR -> CMPNEQSS.
17989 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
17990 TargetLowering::DAGCombinerInfo &DCI,
17991 const X86Subtarget *Subtarget) {
17994 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
17995 // we're requiring SSE2 for both.
17996 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
17997 SDValue N0 = N->getOperand(0);
17998 SDValue N1 = N->getOperand(1);
17999 SDValue CMP0 = N0->getOperand(1);
18000 SDValue CMP1 = N1->getOperand(1);
18003 // The SETCCs should both refer to the same CMP.
18004 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18007 SDValue CMP00 = CMP0->getOperand(0);
18008 SDValue CMP01 = CMP0->getOperand(1);
18009 EVT VT = CMP00.getValueType();
18011 if (VT == MVT::f32 || VT == MVT::f64) {
18012 bool ExpectingFlags = false;
18013 // Check for any users that want flags:
18014 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18015 !ExpectingFlags && UI != UE; ++UI)
18016 switch (UI->getOpcode()) {
18021 ExpectingFlags = true;
18023 case ISD::CopyToReg:
18024 case ISD::SIGN_EXTEND:
18025 case ISD::ZERO_EXTEND:
18026 case ISD::ANY_EXTEND:
18030 if (!ExpectingFlags) {
18031 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18032 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18034 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18035 X86::CondCode tmp = cc0;
18040 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18041 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18042 // FIXME: need symbolic constants for these magic numbers.
18043 // See X86ATTInstPrinter.cpp:printSSECC().
18044 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18045 if (Subtarget->hasAVX512()) {
18046 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18047 CMP01, DAG.getConstant(x86cc, MVT::i8));
18048 if (N->getValueType(0) != MVT::i1)
18049 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18053 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18054 CMP00.getValueType(), CMP00, CMP01,
18055 DAG.getConstant(x86cc, MVT::i8));
18057 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18058 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18060 if (is64BitFP && !Subtarget->is64Bit()) {
18061 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18062 // 64-bit integer, since that's not a legal type. Since
18063 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18064 // bits, but can do this little dance to extract the lowest 32 bits
18065 // and work with those going forward.
18066 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18068 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18070 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18071 Vector32, DAG.getIntPtrConstant(0));
18075 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18076 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18077 DAG.getConstant(1, IntVT));
18078 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18079 return OneBitOfTruth;
18087 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18088 /// so it can be folded inside ANDNP.
18089 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18090 EVT VT = N->getValueType(0);
18092 // Match direct AllOnes for 128 and 256-bit vectors
18093 if (ISD::isBuildVectorAllOnes(N))
18096 // Look through a bit convert.
18097 if (N->getOpcode() == ISD::BITCAST)
18098 N = N->getOperand(0).getNode();
18100 // Sometimes the operand may come from a insert_subvector building a 256-bit
18102 if (VT.is256BitVector() &&
18103 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18104 SDValue V1 = N->getOperand(0);
18105 SDValue V2 = N->getOperand(1);
18107 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18108 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18109 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18110 ISD::isBuildVectorAllOnes(V2.getNode()))
18117 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18118 // register. In most cases we actually compare or select YMM-sized registers
18119 // and mixing the two types creates horrible code. This method optimizes
18120 // some of the transition sequences.
18121 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18122 TargetLowering::DAGCombinerInfo &DCI,
18123 const X86Subtarget *Subtarget) {
18124 EVT VT = N->getValueType(0);
18125 if (!VT.is256BitVector())
18128 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18129 N->getOpcode() == ISD::ZERO_EXTEND ||
18130 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18132 SDValue Narrow = N->getOperand(0);
18133 EVT NarrowVT = Narrow->getValueType(0);
18134 if (!NarrowVT.is128BitVector())
18137 if (Narrow->getOpcode() != ISD::XOR &&
18138 Narrow->getOpcode() != ISD::AND &&
18139 Narrow->getOpcode() != ISD::OR)
18142 SDValue N0 = Narrow->getOperand(0);
18143 SDValue N1 = Narrow->getOperand(1);
18146 // The Left side has to be a trunc.
18147 if (N0.getOpcode() != ISD::TRUNCATE)
18150 // The type of the truncated inputs.
18151 EVT WideVT = N0->getOperand(0)->getValueType(0);
18155 // The right side has to be a 'trunc' or a constant vector.
18156 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18157 bool RHSConst = (isSplatVector(N1.getNode()) &&
18158 isa<ConstantSDNode>(N1->getOperand(0)));
18159 if (!RHSTrunc && !RHSConst)
18162 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18164 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18167 // Set N0 and N1 to hold the inputs to the new wide operation.
18168 N0 = N0->getOperand(0);
18170 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18171 N1->getOperand(0));
18172 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18173 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18174 } else if (RHSTrunc) {
18175 N1 = N1->getOperand(0);
18178 // Generate the wide operation.
18179 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18180 unsigned Opcode = N->getOpcode();
18182 case ISD::ANY_EXTEND:
18184 case ISD::ZERO_EXTEND: {
18185 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18186 APInt Mask = APInt::getAllOnesValue(InBits);
18187 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18188 return DAG.getNode(ISD::AND, DL, VT,
18189 Op, DAG.getConstant(Mask, VT));
18191 case ISD::SIGN_EXTEND:
18192 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18193 Op, DAG.getValueType(NarrowVT));
18195 llvm_unreachable("Unexpected opcode");
18199 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18200 TargetLowering::DAGCombinerInfo &DCI,
18201 const X86Subtarget *Subtarget) {
18202 EVT VT = N->getValueType(0);
18203 if (DCI.isBeforeLegalizeOps())
18206 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18210 // Create BEXTR and BZHI instructions
18211 // BZHI is X & ((1 << Y) - 1)
18212 // BEXTR is ((X >> imm) & (2**size-1))
18213 if (VT == MVT::i32 || VT == MVT::i64) {
18214 SDValue N0 = N->getOperand(0);
18215 SDValue N1 = N->getOperand(1);
18218 if (Subtarget->hasBMI2()) {
18219 // Check for (and (add (shl 1, Y), -1), X)
18220 if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
18221 SDValue N00 = N0.getOperand(0);
18222 if (N00.getOpcode() == ISD::SHL) {
18223 SDValue N001 = N00.getOperand(1);
18224 assert(N001.getValueType() == MVT::i8 && "unexpected type");
18225 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
18226 if (C && C->getZExtValue() == 1)
18227 return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
18231 // Check for (and X, (add (shl 1, Y), -1))
18232 if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
18233 SDValue N10 = N1.getOperand(0);
18234 if (N10.getOpcode() == ISD::SHL) {
18235 SDValue N101 = N10.getOperand(1);
18236 assert(N101.getValueType() == MVT::i8 && "unexpected type");
18237 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
18238 if (C && C->getZExtValue() == 1)
18239 return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
18244 // Check for BEXTR.
18245 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18246 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18247 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18248 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18249 if (MaskNode && ShiftNode) {
18250 uint64_t Mask = MaskNode->getZExtValue();
18251 uint64_t Shift = ShiftNode->getZExtValue();
18252 if (isMask_64(Mask)) {
18253 uint64_t MaskSize = CountPopulation_64(Mask);
18254 if (Shift + MaskSize <= VT.getSizeInBits())
18255 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18256 DAG.getConstant(Shift | (MaskSize << 8), VT));
18264 // Want to form ANDNP nodes:
18265 // 1) In the hopes of then easily combining them with OR and AND nodes
18266 // to form PBLEND/PSIGN.
18267 // 2) To match ANDN packed intrinsics
18268 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18271 SDValue N0 = N->getOperand(0);
18272 SDValue N1 = N->getOperand(1);
18275 // Check LHS for vnot
18276 if (N0.getOpcode() == ISD::XOR &&
18277 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18278 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18279 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18281 // Check RHS for vnot
18282 if (N1.getOpcode() == ISD::XOR &&
18283 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18284 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18285 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18290 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18291 TargetLowering::DAGCombinerInfo &DCI,
18292 const X86Subtarget *Subtarget) {
18293 if (DCI.isBeforeLegalizeOps())
18296 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18300 SDValue N0 = N->getOperand(0);
18301 SDValue N1 = N->getOperand(1);
18302 EVT VT = N->getValueType(0);
18304 // look for psign/blend
18305 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18306 if (!Subtarget->hasSSSE3() ||
18307 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18310 // Canonicalize pandn to RHS
18311 if (N0.getOpcode() == X86ISD::ANDNP)
18313 // or (and (m, y), (pandn m, x))
18314 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18315 SDValue Mask = N1.getOperand(0);
18316 SDValue X = N1.getOperand(1);
18318 if (N0.getOperand(0) == Mask)
18319 Y = N0.getOperand(1);
18320 if (N0.getOperand(1) == Mask)
18321 Y = N0.getOperand(0);
18323 // Check to see if the mask appeared in both the AND and ANDNP and
18327 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18328 // Look through mask bitcast.
18329 if (Mask.getOpcode() == ISD::BITCAST)
18330 Mask = Mask.getOperand(0);
18331 if (X.getOpcode() == ISD::BITCAST)
18332 X = X.getOperand(0);
18333 if (Y.getOpcode() == ISD::BITCAST)
18334 Y = Y.getOperand(0);
18336 EVT MaskVT = Mask.getValueType();
18338 // Validate that the Mask operand is a vector sra node.
18339 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18340 // there is no psrai.b
18341 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18342 unsigned SraAmt = ~0;
18343 if (Mask.getOpcode() == ISD::SRA) {
18344 SDValue Amt = Mask.getOperand(1);
18345 if (isSplatVector(Amt.getNode())) {
18346 SDValue SclrAmt = Amt->getOperand(0);
18347 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18348 SraAmt = C->getZExtValue();
18350 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18351 SDValue SraC = Mask.getOperand(1);
18352 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18354 if ((SraAmt + 1) != EltBits)
18359 // Now we know we at least have a plendvb with the mask val. See if
18360 // we can form a psignb/w/d.
18361 // psign = x.type == y.type == mask.type && y = sub(0, x);
18362 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18363 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18364 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18365 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18366 "Unsupported VT for PSIGN");
18367 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18368 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18370 // PBLENDVB only available on SSE 4.1
18371 if (!Subtarget->hasSSE41())
18374 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18376 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18377 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18378 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18379 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18380 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18384 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18387 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18388 MachineFunction &MF = DAG.getMachineFunction();
18389 bool OptForSize = MF.getFunction()->getAttributes().
18390 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18392 // SHLD/SHRD instructions have lower register pressure, but on some
18393 // platforms they have higher latency than the equivalent
18394 // series of shifts/or that would otherwise be generated.
18395 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18396 // have higher latencies and we are not optimizing for size.
18397 if (!OptForSize && Subtarget->isSHLDSlow())
18400 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18402 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18404 if (!N0.hasOneUse() || !N1.hasOneUse())
18407 SDValue ShAmt0 = N0.getOperand(1);
18408 if (ShAmt0.getValueType() != MVT::i8)
18410 SDValue ShAmt1 = N1.getOperand(1);
18411 if (ShAmt1.getValueType() != MVT::i8)
18413 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18414 ShAmt0 = ShAmt0.getOperand(0);
18415 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18416 ShAmt1 = ShAmt1.getOperand(0);
18419 unsigned Opc = X86ISD::SHLD;
18420 SDValue Op0 = N0.getOperand(0);
18421 SDValue Op1 = N1.getOperand(0);
18422 if (ShAmt0.getOpcode() == ISD::SUB) {
18423 Opc = X86ISD::SHRD;
18424 std::swap(Op0, Op1);
18425 std::swap(ShAmt0, ShAmt1);
18428 unsigned Bits = VT.getSizeInBits();
18429 if (ShAmt1.getOpcode() == ISD::SUB) {
18430 SDValue Sum = ShAmt1.getOperand(0);
18431 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18432 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18433 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18434 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18435 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18436 return DAG.getNode(Opc, DL, VT,
18438 DAG.getNode(ISD::TRUNCATE, DL,
18441 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18442 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18444 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18445 return DAG.getNode(Opc, DL, VT,
18446 N0.getOperand(0), N1.getOperand(0),
18447 DAG.getNode(ISD::TRUNCATE, DL,
18454 // Generate NEG and CMOV for integer abs.
18455 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18456 EVT VT = N->getValueType(0);
18458 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18459 // 8-bit integer abs to NEG and CMOV.
18460 if (VT.isInteger() && VT.getSizeInBits() == 8)
18463 SDValue N0 = N->getOperand(0);
18464 SDValue N1 = N->getOperand(1);
18467 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18468 // and change it to SUB and CMOV.
18469 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18470 N0.getOpcode() == ISD::ADD &&
18471 N0.getOperand(1) == N1 &&
18472 N1.getOpcode() == ISD::SRA &&
18473 N1.getOperand(0) == N0.getOperand(0))
18474 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18475 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18476 // Generate SUB & CMOV.
18477 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18478 DAG.getConstant(0, VT), N0.getOperand(0));
18480 SDValue Ops[] = { N0.getOperand(0), Neg,
18481 DAG.getConstant(X86::COND_GE, MVT::i8),
18482 SDValue(Neg.getNode(), 1) };
18483 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18484 Ops, array_lengthof(Ops));
18489 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18490 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18491 TargetLowering::DAGCombinerInfo &DCI,
18492 const X86Subtarget *Subtarget) {
18493 if (DCI.isBeforeLegalizeOps())
18496 if (Subtarget->hasCMov()) {
18497 SDValue RV = performIntegerAbsCombine(N, DAG);
18505 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18506 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18507 TargetLowering::DAGCombinerInfo &DCI,
18508 const X86Subtarget *Subtarget) {
18509 LoadSDNode *Ld = cast<LoadSDNode>(N);
18510 EVT RegVT = Ld->getValueType(0);
18511 EVT MemVT = Ld->getMemoryVT();
18513 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18514 unsigned RegSz = RegVT.getSizeInBits();
18516 // On Sandybridge unaligned 256bit loads are inefficient.
18517 ISD::LoadExtType Ext = Ld->getExtensionType();
18518 unsigned Alignment = Ld->getAlignment();
18519 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18520 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18521 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18522 unsigned NumElems = RegVT.getVectorNumElements();
18526 SDValue Ptr = Ld->getBasePtr();
18527 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18529 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18531 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18532 Ld->getPointerInfo(), Ld->isVolatile(),
18533 Ld->isNonTemporal(), Ld->isInvariant(),
18535 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18536 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18537 Ld->getPointerInfo(), Ld->isVolatile(),
18538 Ld->isNonTemporal(), Ld->isInvariant(),
18539 std::min(16U, Alignment));
18540 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18542 Load2.getValue(1));
18544 SDValue NewVec = DAG.getUNDEF(RegVT);
18545 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18546 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18547 return DCI.CombineTo(N, NewVec, TF, true);
18550 // If this is a vector EXT Load then attempt to optimize it using a
18551 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18552 // expansion is still better than scalar code.
18553 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18554 // emit a shuffle and a arithmetic shift.
18555 // TODO: It is possible to support ZExt by zeroing the undef values
18556 // during the shuffle phase or after the shuffle.
18557 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18558 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18559 assert(MemVT != RegVT && "Cannot extend to the same type");
18560 assert(MemVT.isVector() && "Must load a vector from memory");
18562 unsigned NumElems = RegVT.getVectorNumElements();
18563 unsigned MemSz = MemVT.getSizeInBits();
18564 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18566 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18569 // All sizes must be a power of two.
18570 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18573 // Attempt to load the original value using scalar loads.
18574 // Find the largest scalar type that divides the total loaded size.
18575 MVT SclrLoadTy = MVT::i8;
18576 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18577 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18578 MVT Tp = (MVT::SimpleValueType)tp;
18579 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18584 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18585 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18587 SclrLoadTy = MVT::f64;
18589 // Calculate the number of scalar loads that we need to perform
18590 // in order to load our vector from memory.
18591 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18592 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18595 unsigned loadRegZize = RegSz;
18596 if (Ext == ISD::SEXTLOAD && RegSz == 256)
18599 // Represent our vector as a sequence of elements which are the
18600 // largest scalar that we can load.
18601 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18602 loadRegZize/SclrLoadTy.getSizeInBits());
18604 // Represent the data using the same element type that is stored in
18605 // memory. In practice, we ''widen'' MemVT.
18607 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18608 loadRegZize/MemVT.getScalarType().getSizeInBits());
18610 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18611 "Invalid vector type");
18613 // We can't shuffle using an illegal type.
18614 if (!TLI.isTypeLegal(WideVecVT))
18617 SmallVector<SDValue, 8> Chains;
18618 SDValue Ptr = Ld->getBasePtr();
18619 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18620 TLI.getPointerTy());
18621 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18623 for (unsigned i = 0; i < NumLoads; ++i) {
18624 // Perform a single load.
18625 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18626 Ptr, Ld->getPointerInfo(),
18627 Ld->isVolatile(), Ld->isNonTemporal(),
18628 Ld->isInvariant(), Ld->getAlignment());
18629 Chains.push_back(ScalarLoad.getValue(1));
18630 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18631 // another round of DAGCombining.
18633 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18635 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18636 ScalarLoad, DAG.getIntPtrConstant(i));
18638 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18641 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18644 // Bitcast the loaded value to a vector of the original element type, in
18645 // the size of the target vector type.
18646 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18647 unsigned SizeRatio = RegSz/MemSz;
18649 if (Ext == ISD::SEXTLOAD) {
18650 // If we have SSE4.1 we can directly emit a VSEXT node.
18651 if (Subtarget->hasSSE41()) {
18652 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18653 return DCI.CombineTo(N, Sext, TF, true);
18656 // Otherwise we'll shuffle the small elements in the high bits of the
18657 // larger type and perform an arithmetic shift. If the shift is not legal
18658 // it's better to scalarize.
18659 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18662 // Redistribute the loaded elements into the different locations.
18663 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18664 for (unsigned i = 0; i != NumElems; ++i)
18665 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18667 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18668 DAG.getUNDEF(WideVecVT),
18671 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18673 // Build the arithmetic shift.
18674 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18675 MemVT.getVectorElementType().getSizeInBits();
18676 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18677 DAG.getConstant(Amt, RegVT));
18679 return DCI.CombineTo(N, Shuff, TF, true);
18682 // Redistribute the loaded elements into the different locations.
18683 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18684 for (unsigned i = 0; i != NumElems; ++i)
18685 ShuffleVec[i*SizeRatio] = i;
18687 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18688 DAG.getUNDEF(WideVecVT),
18691 // Bitcast to the requested type.
18692 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18693 // Replace the original load with the new sequence
18694 // and return the new chain.
18695 return DCI.CombineTo(N, Shuff, TF, true);
18701 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18702 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18703 const X86Subtarget *Subtarget) {
18704 StoreSDNode *St = cast<StoreSDNode>(N);
18705 EVT VT = St->getValue().getValueType();
18706 EVT StVT = St->getMemoryVT();
18708 SDValue StoredVal = St->getOperand(1);
18709 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18711 // If we are saving a concatenation of two XMM registers, perform two stores.
18712 // On Sandy Bridge, 256-bit memory operations are executed by two
18713 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18714 // memory operation.
18715 unsigned Alignment = St->getAlignment();
18716 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18717 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18718 StVT == VT && !IsAligned) {
18719 unsigned NumElems = VT.getVectorNumElements();
18723 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18724 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18726 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18727 SDValue Ptr0 = St->getBasePtr();
18728 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18730 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18731 St->getPointerInfo(), St->isVolatile(),
18732 St->isNonTemporal(), Alignment);
18733 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18734 St->getPointerInfo(), St->isVolatile(),
18735 St->isNonTemporal(),
18736 std::min(16U, Alignment));
18737 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18740 // Optimize trunc store (of multiple scalars) to shuffle and store.
18741 // First, pack all of the elements in one place. Next, store to memory
18742 // in fewer chunks.
18743 if (St->isTruncatingStore() && VT.isVector()) {
18744 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18745 unsigned NumElems = VT.getVectorNumElements();
18746 assert(StVT != VT && "Cannot truncate to the same type");
18747 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18748 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18750 // From, To sizes and ElemCount must be pow of two
18751 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18752 // We are going to use the original vector elt for storing.
18753 // Accumulated smaller vector elements must be a multiple of the store size.
18754 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18756 unsigned SizeRatio = FromSz / ToSz;
18758 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18760 // Create a type on which we perform the shuffle
18761 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18762 StVT.getScalarType(), NumElems*SizeRatio);
18764 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18766 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18767 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18768 for (unsigned i = 0; i != NumElems; ++i)
18769 ShuffleVec[i] = i * SizeRatio;
18771 // Can't shuffle using an illegal type.
18772 if (!TLI.isTypeLegal(WideVecVT))
18775 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18776 DAG.getUNDEF(WideVecVT),
18778 // At this point all of the data is stored at the bottom of the
18779 // register. We now need to save it to mem.
18781 // Find the largest store unit
18782 MVT StoreType = MVT::i8;
18783 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18784 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18785 MVT Tp = (MVT::SimpleValueType)tp;
18786 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18790 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18791 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18792 (64 <= NumElems * ToSz))
18793 StoreType = MVT::f64;
18795 // Bitcast the original vector into a vector of store-size units
18796 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18797 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18798 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18799 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18800 SmallVector<SDValue, 8> Chains;
18801 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18802 TLI.getPointerTy());
18803 SDValue Ptr = St->getBasePtr();
18805 // Perform one or more big stores into memory.
18806 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18807 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18808 StoreType, ShuffWide,
18809 DAG.getIntPtrConstant(i));
18810 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18811 St->getPointerInfo(), St->isVolatile(),
18812 St->isNonTemporal(), St->getAlignment());
18813 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18814 Chains.push_back(Ch);
18817 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18821 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
18822 // the FP state in cases where an emms may be missing.
18823 // A preferable solution to the general problem is to figure out the right
18824 // places to insert EMMS. This qualifies as a quick hack.
18826 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18827 if (VT.getSizeInBits() != 64)
18830 const Function *F = DAG.getMachineFunction().getFunction();
18831 bool NoImplicitFloatOps = F->getAttributes().
18832 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18833 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18834 && Subtarget->hasSSE2();
18835 if ((VT.isVector() ||
18836 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18837 isa<LoadSDNode>(St->getValue()) &&
18838 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18839 St->getChain().hasOneUse() && !St->isVolatile()) {
18840 SDNode* LdVal = St->getValue().getNode();
18841 LoadSDNode *Ld = 0;
18842 int TokenFactorIndex = -1;
18843 SmallVector<SDValue, 8> Ops;
18844 SDNode* ChainVal = St->getChain().getNode();
18845 // Must be a store of a load. We currently handle two cases: the load
18846 // is a direct child, and it's under an intervening TokenFactor. It is
18847 // possible to dig deeper under nested TokenFactors.
18848 if (ChainVal == LdVal)
18849 Ld = cast<LoadSDNode>(St->getChain());
18850 else if (St->getValue().hasOneUse() &&
18851 ChainVal->getOpcode() == ISD::TokenFactor) {
18852 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18853 if (ChainVal->getOperand(i).getNode() == LdVal) {
18854 TokenFactorIndex = i;
18855 Ld = cast<LoadSDNode>(St->getValue());
18857 Ops.push_back(ChainVal->getOperand(i));
18861 if (!Ld || !ISD::isNormalLoad(Ld))
18864 // If this is not the MMX case, i.e. we are just turning i64 load/store
18865 // into f64 load/store, avoid the transformation if there are multiple
18866 // uses of the loaded value.
18867 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18872 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18873 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18875 if (Subtarget->is64Bit() || F64IsLegal) {
18876 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18877 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18878 Ld->getPointerInfo(), Ld->isVolatile(),
18879 Ld->isNonTemporal(), Ld->isInvariant(),
18880 Ld->getAlignment());
18881 SDValue NewChain = NewLd.getValue(1);
18882 if (TokenFactorIndex != -1) {
18883 Ops.push_back(NewChain);
18884 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18887 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18888 St->getPointerInfo(),
18889 St->isVolatile(), St->isNonTemporal(),
18890 St->getAlignment());
18893 // Otherwise, lower to two pairs of 32-bit loads / stores.
18894 SDValue LoAddr = Ld->getBasePtr();
18895 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18896 DAG.getConstant(4, MVT::i32));
18898 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18899 Ld->getPointerInfo(),
18900 Ld->isVolatile(), Ld->isNonTemporal(),
18901 Ld->isInvariant(), Ld->getAlignment());
18902 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18903 Ld->getPointerInfo().getWithOffset(4),
18904 Ld->isVolatile(), Ld->isNonTemporal(),
18906 MinAlign(Ld->getAlignment(), 4));
18908 SDValue NewChain = LoLd.getValue(1);
18909 if (TokenFactorIndex != -1) {
18910 Ops.push_back(LoLd);
18911 Ops.push_back(HiLd);
18912 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18916 LoAddr = St->getBasePtr();
18917 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18918 DAG.getConstant(4, MVT::i32));
18920 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18921 St->getPointerInfo(),
18922 St->isVolatile(), St->isNonTemporal(),
18923 St->getAlignment());
18924 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18925 St->getPointerInfo().getWithOffset(4),
18927 St->isNonTemporal(),
18928 MinAlign(St->getAlignment(), 4));
18929 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18934 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18935 /// and return the operands for the horizontal operation in LHS and RHS. A
18936 /// horizontal operation performs the binary operation on successive elements
18937 /// of its first operand, then on successive elements of its second operand,
18938 /// returning the resulting values in a vector. For example, if
18939 /// A = < float a0, float a1, float a2, float a3 >
18941 /// B = < float b0, float b1, float b2, float b3 >
18942 /// then the result of doing a horizontal operation on A and B is
18943 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18944 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18945 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18946 /// set to A, RHS to B, and the routine returns 'true'.
18947 /// Note that the binary operation should have the property that if one of the
18948 /// operands is UNDEF then the result is UNDEF.
18949 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18950 // Look for the following pattern: if
18951 // A = < float a0, float a1, float a2, float a3 >
18952 // B = < float b0, float b1, float b2, float b3 >
18954 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
18955 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
18956 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
18957 // which is A horizontal-op B.
18959 // At least one of the operands should be a vector shuffle.
18960 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
18961 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
18964 MVT VT = LHS.getSimpleValueType();
18966 assert((VT.is128BitVector() || VT.is256BitVector()) &&
18967 "Unsupported vector type for horizontal add/sub");
18969 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
18970 // operate independently on 128-bit lanes.
18971 unsigned NumElts = VT.getVectorNumElements();
18972 unsigned NumLanes = VT.getSizeInBits()/128;
18973 unsigned NumLaneElts = NumElts / NumLanes;
18974 assert((NumLaneElts % 2 == 0) &&
18975 "Vector type should have an even number of elements in each lane");
18976 unsigned HalfLaneElts = NumLaneElts/2;
18978 // View LHS in the form
18979 // LHS = VECTOR_SHUFFLE A, B, LMask
18980 // If LHS is not a shuffle then pretend it is the shuffle
18981 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
18982 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
18985 SmallVector<int, 16> LMask(NumElts);
18986 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18987 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
18988 A = LHS.getOperand(0);
18989 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
18990 B = LHS.getOperand(1);
18991 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
18992 std::copy(Mask.begin(), Mask.end(), LMask.begin());
18994 if (LHS.getOpcode() != ISD::UNDEF)
18996 for (unsigned i = 0; i != NumElts; ++i)
19000 // Likewise, view RHS in the form
19001 // RHS = VECTOR_SHUFFLE C, D, RMask
19003 SmallVector<int, 16> RMask(NumElts);
19004 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19005 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19006 C = RHS.getOperand(0);
19007 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19008 D = RHS.getOperand(1);
19009 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19010 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19012 if (RHS.getOpcode() != ISD::UNDEF)
19014 for (unsigned i = 0; i != NumElts; ++i)
19018 // Check that the shuffles are both shuffling the same vectors.
19019 if (!(A == C && B == D) && !(A == D && B == C))
19022 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19023 if (!A.getNode() && !B.getNode())
19026 // If A and B occur in reverse order in RHS, then "swap" them (which means
19027 // rewriting the mask).
19029 CommuteVectorShuffleMask(RMask, NumElts);
19031 // At this point LHS and RHS are equivalent to
19032 // LHS = VECTOR_SHUFFLE A, B, LMask
19033 // RHS = VECTOR_SHUFFLE A, B, RMask
19034 // Check that the masks correspond to performing a horizontal operation.
19035 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19036 for (unsigned i = 0; i != NumLaneElts; ++i) {
19037 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19039 // Ignore any UNDEF components.
19040 if (LIdx < 0 || RIdx < 0 ||
19041 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19042 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19045 // Check that successive elements are being operated on. If not, this is
19046 // not a horizontal operation.
19047 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19048 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19049 if (!(LIdx == Index && RIdx == Index + 1) &&
19050 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19055 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19056 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19060 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19061 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19062 const X86Subtarget *Subtarget) {
19063 EVT VT = N->getValueType(0);
19064 SDValue LHS = N->getOperand(0);
19065 SDValue RHS = N->getOperand(1);
19067 // Try to synthesize horizontal adds from adds of shuffles.
19068 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19069 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19070 isHorizontalBinOp(LHS, RHS, true))
19071 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19075 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19076 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19077 const X86Subtarget *Subtarget) {
19078 EVT VT = N->getValueType(0);
19079 SDValue LHS = N->getOperand(0);
19080 SDValue RHS = N->getOperand(1);
19082 // Try to synthesize horizontal subs from subs of shuffles.
19083 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19084 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19085 isHorizontalBinOp(LHS, RHS, false))
19086 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19090 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19091 /// X86ISD::FXOR nodes.
19092 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19093 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19094 // F[X]OR(0.0, x) -> x
19095 // F[X]OR(x, 0.0) -> x
19096 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19097 if (C->getValueAPF().isPosZero())
19098 return N->getOperand(1);
19099 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19100 if (C->getValueAPF().isPosZero())
19101 return N->getOperand(0);
19105 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19106 /// X86ISD::FMAX nodes.
19107 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19108 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19110 // Only perform optimizations if UnsafeMath is used.
19111 if (!DAG.getTarget().Options.UnsafeFPMath)
19114 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19115 // into FMINC and FMAXC, which are Commutative operations.
19116 unsigned NewOp = 0;
19117 switch (N->getOpcode()) {
19118 default: llvm_unreachable("unknown opcode");
19119 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19120 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19123 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19124 N->getOperand(0), N->getOperand(1));
19127 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19128 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19129 // FAND(0.0, x) -> 0.0
19130 // FAND(x, 0.0) -> 0.0
19131 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19132 if (C->getValueAPF().isPosZero())
19133 return N->getOperand(0);
19134 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19135 if (C->getValueAPF().isPosZero())
19136 return N->getOperand(1);
19140 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19141 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19142 // FANDN(x, 0.0) -> 0.0
19143 // FANDN(0.0, x) -> x
19144 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19145 if (C->getValueAPF().isPosZero())
19146 return N->getOperand(1);
19147 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19148 if (C->getValueAPF().isPosZero())
19149 return N->getOperand(1);
19153 static SDValue PerformBTCombine(SDNode *N,
19155 TargetLowering::DAGCombinerInfo &DCI) {
19156 // BT ignores high bits in the bit index operand.
19157 SDValue Op1 = N->getOperand(1);
19158 if (Op1.hasOneUse()) {
19159 unsigned BitWidth = Op1.getValueSizeInBits();
19160 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19161 APInt KnownZero, KnownOne;
19162 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19163 !DCI.isBeforeLegalizeOps());
19164 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19165 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19166 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19167 DCI.CommitTargetLoweringOpt(TLO);
19172 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19173 SDValue Op = N->getOperand(0);
19174 if (Op.getOpcode() == ISD::BITCAST)
19175 Op = Op.getOperand(0);
19176 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19177 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19178 VT.getVectorElementType().getSizeInBits() ==
19179 OpVT.getVectorElementType().getSizeInBits()) {
19180 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19185 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19186 const X86Subtarget *Subtarget) {
19187 EVT VT = N->getValueType(0);
19188 if (!VT.isVector())
19191 SDValue N0 = N->getOperand(0);
19192 SDValue N1 = N->getOperand(1);
19193 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19196 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19197 // both SSE and AVX2 since there is no sign-extended shift right
19198 // operation on a vector with 64-bit elements.
19199 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19200 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19201 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19202 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19203 SDValue N00 = N0.getOperand(0);
19205 // EXTLOAD has a better solution on AVX2,
19206 // it may be replaced with X86ISD::VSEXT node.
19207 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19208 if (!ISD::isNormalLoad(N00.getNode()))
19211 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19212 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19214 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19220 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19221 TargetLowering::DAGCombinerInfo &DCI,
19222 const X86Subtarget *Subtarget) {
19223 if (!DCI.isBeforeLegalizeOps())
19226 if (!Subtarget->hasFp256())
19229 EVT VT = N->getValueType(0);
19230 if (VT.isVector() && VT.getSizeInBits() == 256) {
19231 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19239 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19240 const X86Subtarget* Subtarget) {
19242 EVT VT = N->getValueType(0);
19244 // Let legalize expand this if it isn't a legal type yet.
19245 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19248 EVT ScalarVT = VT.getScalarType();
19249 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19250 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19253 SDValue A = N->getOperand(0);
19254 SDValue B = N->getOperand(1);
19255 SDValue C = N->getOperand(2);
19257 bool NegA = (A.getOpcode() == ISD::FNEG);
19258 bool NegB = (B.getOpcode() == ISD::FNEG);
19259 bool NegC = (C.getOpcode() == ISD::FNEG);
19261 // Negative multiplication when NegA xor NegB
19262 bool NegMul = (NegA != NegB);
19264 A = A.getOperand(0);
19266 B = B.getOperand(0);
19268 C = C.getOperand(0);
19272 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19274 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19276 return DAG.getNode(Opcode, dl, VT, A, B, C);
19279 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19280 TargetLowering::DAGCombinerInfo &DCI,
19281 const X86Subtarget *Subtarget) {
19282 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19283 // (and (i32 x86isd::setcc_carry), 1)
19284 // This eliminates the zext. This transformation is necessary because
19285 // ISD::SETCC is always legalized to i8.
19287 SDValue N0 = N->getOperand(0);
19288 EVT VT = N->getValueType(0);
19290 if (N0.getOpcode() == ISD::AND &&
19292 N0.getOperand(0).hasOneUse()) {
19293 SDValue N00 = N0.getOperand(0);
19294 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19295 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19296 if (!C || C->getZExtValue() != 1)
19298 return DAG.getNode(ISD::AND, dl, VT,
19299 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19300 N00.getOperand(0), N00.getOperand(1)),
19301 DAG.getConstant(1, VT));
19305 if (N0.getOpcode() == ISD::TRUNCATE &&
19307 N0.getOperand(0).hasOneUse()) {
19308 SDValue N00 = N0.getOperand(0);
19309 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19310 return DAG.getNode(ISD::AND, dl, VT,
19311 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19312 N00.getOperand(0), N00.getOperand(1)),
19313 DAG.getConstant(1, VT));
19316 if (VT.is256BitVector()) {
19317 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19325 // Optimize x == -y --> x+y == 0
19326 // x != -y --> x+y != 0
19327 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19328 const X86Subtarget* Subtarget) {
19329 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19330 SDValue LHS = N->getOperand(0);
19331 SDValue RHS = N->getOperand(1);
19332 EVT VT = N->getValueType(0);
19335 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19336 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19337 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19338 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19339 LHS.getValueType(), RHS, LHS.getOperand(1));
19340 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19341 addV, DAG.getConstant(0, addV.getValueType()), CC);
19343 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19344 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19345 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19346 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19347 RHS.getValueType(), LHS, RHS.getOperand(1));
19348 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19349 addV, DAG.getConstant(0, addV.getValueType()), CC);
19352 if (VT.getScalarType() == MVT::i1) {
19353 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19354 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19355 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19356 if (!IsSEXT0 && !IsVZero0)
19358 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19359 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19360 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19362 if (!IsSEXT1 && !IsVZero1)
19365 if (IsSEXT0 && IsVZero1) {
19366 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19367 if (CC == ISD::SETEQ)
19368 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19369 return LHS.getOperand(0);
19371 if (IsSEXT1 && IsVZero0) {
19372 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19373 if (CC == ISD::SETEQ)
19374 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19375 return RHS.getOperand(0);
19382 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19383 // as "sbb reg,reg", since it can be extended without zext and produces
19384 // an all-ones bit which is more useful than 0/1 in some cases.
19385 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19388 return DAG.getNode(ISD::AND, DL, VT,
19389 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19390 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19391 DAG.getConstant(1, VT));
19392 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19393 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19394 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19395 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19398 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19399 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19400 TargetLowering::DAGCombinerInfo &DCI,
19401 const X86Subtarget *Subtarget) {
19403 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19404 SDValue EFLAGS = N->getOperand(1);
19406 if (CC == X86::COND_A) {
19407 // Try to convert COND_A into COND_B in an attempt to facilitate
19408 // materializing "setb reg".
19410 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19411 // cannot take an immediate as its first operand.
19413 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19414 EFLAGS.getValueType().isInteger() &&
19415 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19416 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19417 EFLAGS.getNode()->getVTList(),
19418 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19419 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19420 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19424 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19425 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19427 if (CC == X86::COND_B)
19428 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19432 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19433 if (Flags.getNode()) {
19434 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19435 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19441 // Optimize branch condition evaluation.
19443 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19444 TargetLowering::DAGCombinerInfo &DCI,
19445 const X86Subtarget *Subtarget) {
19447 SDValue Chain = N->getOperand(0);
19448 SDValue Dest = N->getOperand(1);
19449 SDValue EFLAGS = N->getOperand(3);
19450 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19454 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19455 if (Flags.getNode()) {
19456 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19457 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19464 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19465 const X86TargetLowering *XTLI) {
19466 SDValue Op0 = N->getOperand(0);
19467 EVT InVT = Op0->getValueType(0);
19469 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19470 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19472 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19473 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19474 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19477 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19478 // a 32-bit target where SSE doesn't support i64->FP operations.
19479 if (Op0.getOpcode() == ISD::LOAD) {
19480 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19481 EVT VT = Ld->getValueType(0);
19482 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19483 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19484 !XTLI->getSubtarget()->is64Bit() &&
19486 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19487 Ld->getChain(), Op0, DAG);
19488 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19495 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19496 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19497 X86TargetLowering::DAGCombinerInfo &DCI) {
19498 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19499 // the result is either zero or one (depending on the input carry bit).
19500 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19501 if (X86::isZeroNode(N->getOperand(0)) &&
19502 X86::isZeroNode(N->getOperand(1)) &&
19503 // We don't have a good way to replace an EFLAGS use, so only do this when
19505 SDValue(N, 1).use_empty()) {
19507 EVT VT = N->getValueType(0);
19508 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19509 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19510 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19511 DAG.getConstant(X86::COND_B,MVT::i8),
19513 DAG.getConstant(1, VT));
19514 return DCI.CombineTo(N, Res1, CarryOut);
19520 // fold (add Y, (sete X, 0)) -> adc 0, Y
19521 // (add Y, (setne X, 0)) -> sbb -1, Y
19522 // (sub (sete X, 0), Y) -> sbb 0, Y
19523 // (sub (setne X, 0), Y) -> adc -1, Y
19524 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19527 // Look through ZExts.
19528 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19529 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19532 SDValue SetCC = Ext.getOperand(0);
19533 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19536 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19537 if (CC != X86::COND_E && CC != X86::COND_NE)
19540 SDValue Cmp = SetCC.getOperand(1);
19541 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19542 !X86::isZeroNode(Cmp.getOperand(1)) ||
19543 !Cmp.getOperand(0).getValueType().isInteger())
19546 SDValue CmpOp0 = Cmp.getOperand(0);
19547 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19548 DAG.getConstant(1, CmpOp0.getValueType()));
19550 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19551 if (CC == X86::COND_NE)
19552 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19553 DL, OtherVal.getValueType(), OtherVal,
19554 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19555 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19556 DL, OtherVal.getValueType(), OtherVal,
19557 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19560 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19561 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19562 const X86Subtarget *Subtarget) {
19563 EVT VT = N->getValueType(0);
19564 SDValue Op0 = N->getOperand(0);
19565 SDValue Op1 = N->getOperand(1);
19567 // Try to synthesize horizontal adds from adds of shuffles.
19568 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19569 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19570 isHorizontalBinOp(Op0, Op1, true))
19571 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19573 return OptimizeConditionalInDecrement(N, DAG);
19576 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19577 const X86Subtarget *Subtarget) {
19578 SDValue Op0 = N->getOperand(0);
19579 SDValue Op1 = N->getOperand(1);
19581 // X86 can't encode an immediate LHS of a sub. See if we can push the
19582 // negation into a preceding instruction.
19583 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19584 // If the RHS of the sub is a XOR with one use and a constant, invert the
19585 // immediate. Then add one to the LHS of the sub so we can turn
19586 // X-Y -> X+~Y+1, saving one register.
19587 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19588 isa<ConstantSDNode>(Op1.getOperand(1))) {
19589 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19590 EVT VT = Op0.getValueType();
19591 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19593 DAG.getConstant(~XorC, VT));
19594 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19595 DAG.getConstant(C->getAPIntValue()+1, VT));
19599 // Try to synthesize horizontal adds from adds of shuffles.
19600 EVT VT = N->getValueType(0);
19601 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19602 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19603 isHorizontalBinOp(Op0, Op1, true))
19604 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19606 return OptimizeConditionalInDecrement(N, DAG);
19609 /// performVZEXTCombine - Performs build vector combines
19610 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19611 TargetLowering::DAGCombinerInfo &DCI,
19612 const X86Subtarget *Subtarget) {
19613 // (vzext (bitcast (vzext (x)) -> (vzext x)
19614 SDValue In = N->getOperand(0);
19615 while (In.getOpcode() == ISD::BITCAST)
19616 In = In.getOperand(0);
19618 if (In.getOpcode() != X86ISD::VZEXT)
19621 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19625 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19626 DAGCombinerInfo &DCI) const {
19627 SelectionDAG &DAG = DCI.DAG;
19628 switch (N->getOpcode()) {
19630 case ISD::EXTRACT_VECTOR_ELT:
19631 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19633 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19634 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19635 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
19636 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
19637 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
19638 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
19641 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
19642 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
19643 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
19644 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
19645 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
19646 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
19647 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
19648 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
19649 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
19651 case X86ISD::FOR: return PerformFORCombine(N, DAG);
19653 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
19654 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
19655 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
19656 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
19657 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
19658 case ISD::ANY_EXTEND:
19659 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
19660 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
19661 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19662 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19663 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
19664 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19665 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19666 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
19667 case X86ISD::SHUFP: // Handle all target specific shuffles
19668 case X86ISD::PALIGNR:
19669 case X86ISD::UNPCKH:
19670 case X86ISD::UNPCKL:
19671 case X86ISD::MOVHLPS:
19672 case X86ISD::MOVLHPS:
19673 case X86ISD::PSHUFD:
19674 case X86ISD::PSHUFHW:
19675 case X86ISD::PSHUFLW:
19676 case X86ISD::MOVSS:
19677 case X86ISD::MOVSD:
19678 case X86ISD::VPERMILP:
19679 case X86ISD::VPERM2X128:
19680 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19681 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
19687 /// isTypeDesirableForOp - Return true if the target has native support for
19688 /// the specified value type and it is 'desirable' to use the type for the
19689 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19690 /// instruction encodings are longer and some i16 instructions are slow.
19691 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19692 if (!isTypeLegal(VT))
19694 if (VT != MVT::i16)
19701 case ISD::SIGN_EXTEND:
19702 case ISD::ZERO_EXTEND:
19703 case ISD::ANY_EXTEND:
19716 /// IsDesirableToPromoteOp - This method query the target whether it is
19717 /// beneficial for dag combiner to promote the specified node. If true, it
19718 /// should return the desired promotion type by reference.
19719 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19720 EVT VT = Op.getValueType();
19721 if (VT != MVT::i16)
19724 bool Promote = false;
19725 bool Commute = false;
19726 switch (Op.getOpcode()) {
19729 LoadSDNode *LD = cast<LoadSDNode>(Op);
19730 // If the non-extending load has a single use and it's not live out, then it
19731 // might be folded.
19732 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19733 Op.hasOneUse()*/) {
19734 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19735 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19736 // The only case where we'd want to promote LOAD (rather then it being
19737 // promoted as an operand is when it's only use is liveout.
19738 if (UI->getOpcode() != ISD::CopyToReg)
19745 case ISD::SIGN_EXTEND:
19746 case ISD::ZERO_EXTEND:
19747 case ISD::ANY_EXTEND:
19752 SDValue N0 = Op.getOperand(0);
19753 // Look out for (store (shl (load), x)).
19754 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19767 SDValue N0 = Op.getOperand(0);
19768 SDValue N1 = Op.getOperand(1);
19769 if (!Commute && MayFoldLoad(N1))
19771 // Avoid disabling potential load folding opportunities.
19772 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19774 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19784 //===----------------------------------------------------------------------===//
19785 // X86 Inline Assembly Support
19786 //===----------------------------------------------------------------------===//
19789 // Helper to match a string separated by whitespace.
19790 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19791 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19793 for (unsigned i = 0, e = args.size(); i != e; ++i) {
19794 StringRef piece(*args[i]);
19795 if (!s.startswith(piece)) // Check if the piece matches.
19798 s = s.substr(piece.size());
19799 StringRef::size_type pos = s.find_first_not_of(" \t");
19800 if (pos == 0) // We matched a prefix.
19808 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19811 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19813 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19814 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19815 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19816 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19818 if (AsmPieces.size() == 3)
19820 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19827 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19828 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19830 std::string AsmStr = IA->getAsmString();
19832 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19833 if (!Ty || Ty->getBitWidth() % 16 != 0)
19836 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19837 SmallVector<StringRef, 4> AsmPieces;
19838 SplitString(AsmStr, AsmPieces, ";\n");
19840 switch (AsmPieces.size()) {
19841 default: return false;
19843 // FIXME: this should verify that we are targeting a 486 or better. If not,
19844 // we will turn this bswap into something that will be lowered to logical
19845 // ops instead of emitting the bswap asm. For now, we don't support 486 or
19846 // lower so don't worry about this.
19848 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19849 matchAsm(AsmPieces[0], "bswapl", "$0") ||
19850 matchAsm(AsmPieces[0], "bswapq", "$0") ||
19851 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19852 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19853 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19854 // No need to check constraints, nothing other than the equivalent of
19855 // "=r,0" would be valid here.
19856 return IntrinsicLowering::LowerToByteSwap(CI);
19859 // rorw $$8, ${0:w} --> llvm.bswap.i16
19860 if (CI->getType()->isIntegerTy(16) &&
19861 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19862 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19863 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19865 const std::string &ConstraintsStr = IA->getConstraintString();
19866 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19867 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19868 if (clobbersFlagRegisters(AsmPieces))
19869 return IntrinsicLowering::LowerToByteSwap(CI);
19873 if (CI->getType()->isIntegerTy(32) &&
19874 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19875 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19876 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19877 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19879 const std::string &ConstraintsStr = IA->getConstraintString();
19880 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19881 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19882 if (clobbersFlagRegisters(AsmPieces))
19883 return IntrinsicLowering::LowerToByteSwap(CI);
19886 if (CI->getType()->isIntegerTy(64)) {
19887 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19888 if (Constraints.size() >= 2 &&
19889 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19890 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19891 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
19892 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19893 matchAsm(AsmPieces[1], "bswap", "%edx") &&
19894 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19895 return IntrinsicLowering::LowerToByteSwap(CI);
19903 /// getConstraintType - Given a constraint letter, return the type of
19904 /// constraint it is for this target.
19905 X86TargetLowering::ConstraintType
19906 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19907 if (Constraint.size() == 1) {
19908 switch (Constraint[0]) {
19919 return C_RegisterClass;
19943 return TargetLowering::getConstraintType(Constraint);
19946 /// Examine constraint type and operand type and determine a weight value.
19947 /// This object must already have been set up with the operand type
19948 /// and the current alternative constraint selected.
19949 TargetLowering::ConstraintWeight
19950 X86TargetLowering::getSingleConstraintMatchWeight(
19951 AsmOperandInfo &info, const char *constraint) const {
19952 ConstraintWeight weight = CW_Invalid;
19953 Value *CallOperandVal = info.CallOperandVal;
19954 // If we don't have a value, we can't do a match,
19955 // but allow it at the lowest weight.
19956 if (CallOperandVal == NULL)
19958 Type *type = CallOperandVal->getType();
19959 // Look at the constraint type.
19960 switch (*constraint) {
19962 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19973 if (CallOperandVal->getType()->isIntegerTy())
19974 weight = CW_SpecificReg;
19979 if (type->isFloatingPointTy())
19980 weight = CW_SpecificReg;
19983 if (type->isX86_MMXTy() && Subtarget->hasMMX())
19984 weight = CW_SpecificReg;
19988 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
19989 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
19990 weight = CW_Register;
19993 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
19994 if (C->getZExtValue() <= 31)
19995 weight = CW_Constant;
19999 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20000 if (C->getZExtValue() <= 63)
20001 weight = CW_Constant;
20005 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20006 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20007 weight = CW_Constant;
20011 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20012 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20013 weight = CW_Constant;
20017 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20018 if (C->getZExtValue() <= 3)
20019 weight = CW_Constant;
20023 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20024 if (C->getZExtValue() <= 0xff)
20025 weight = CW_Constant;
20030 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20031 weight = CW_Constant;
20035 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20036 if ((C->getSExtValue() >= -0x80000000LL) &&
20037 (C->getSExtValue() <= 0x7fffffffLL))
20038 weight = CW_Constant;
20042 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20043 if (C->getZExtValue() <= 0xffffffff)
20044 weight = CW_Constant;
20051 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20052 /// with another that has more specific requirements based on the type of the
20053 /// corresponding operand.
20054 const char *X86TargetLowering::
20055 LowerXConstraint(EVT ConstraintVT) const {
20056 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20057 // 'f' like normal targets.
20058 if (ConstraintVT.isFloatingPoint()) {
20059 if (Subtarget->hasSSE2())
20061 if (Subtarget->hasSSE1())
20065 return TargetLowering::LowerXConstraint(ConstraintVT);
20068 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20069 /// vector. If it is invalid, don't add anything to Ops.
20070 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20071 std::string &Constraint,
20072 std::vector<SDValue>&Ops,
20073 SelectionDAG &DAG) const {
20074 SDValue Result(0, 0);
20076 // Only support length 1 constraints for now.
20077 if (Constraint.length() > 1) return;
20079 char ConstraintLetter = Constraint[0];
20080 switch (ConstraintLetter) {
20083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20084 if (C->getZExtValue() <= 31) {
20085 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20091 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20092 if (C->getZExtValue() <= 63) {
20093 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20099 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20100 if (isInt<8>(C->getSExtValue())) {
20101 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20107 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20108 if (C->getZExtValue() <= 255) {
20109 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20115 // 32-bit signed value
20116 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20117 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20118 C->getSExtValue())) {
20119 // Widen to 64 bits here to get it sign extended.
20120 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20123 // FIXME gcc accepts some relocatable values here too, but only in certain
20124 // memory models; it's complicated.
20129 // 32-bit unsigned value
20130 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20131 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20132 C->getZExtValue())) {
20133 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20137 // FIXME gcc accepts some relocatable values here too, but only in certain
20138 // memory models; it's complicated.
20142 // Literal immediates are always ok.
20143 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20144 // Widen to 64 bits here to get it sign extended.
20145 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20149 // In any sort of PIC mode addresses need to be computed at runtime by
20150 // adding in a register or some sort of table lookup. These can't
20151 // be used as immediates.
20152 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20155 // If we are in non-pic codegen mode, we allow the address of a global (with
20156 // an optional displacement) to be used with 'i'.
20157 GlobalAddressSDNode *GA = 0;
20158 int64_t Offset = 0;
20160 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20162 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20163 Offset += GA->getOffset();
20165 } else if (Op.getOpcode() == ISD::ADD) {
20166 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20167 Offset += C->getZExtValue();
20168 Op = Op.getOperand(0);
20171 } else if (Op.getOpcode() == ISD::SUB) {
20172 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20173 Offset += -C->getZExtValue();
20174 Op = Op.getOperand(0);
20179 // Otherwise, this isn't something we can handle, reject it.
20183 const GlobalValue *GV = GA->getGlobal();
20184 // If we require an extra load to get this address, as in PIC mode, we
20185 // can't accept it.
20186 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20187 getTargetMachine())))
20190 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20191 GA->getValueType(0), Offset);
20196 if (Result.getNode()) {
20197 Ops.push_back(Result);
20200 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20203 std::pair<unsigned, const TargetRegisterClass*>
20204 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20206 // First, see if this is a constraint that directly corresponds to an LLVM
20208 if (Constraint.size() == 1) {
20209 // GCC Constraint Letters
20210 switch (Constraint[0]) {
20212 // TODO: Slight differences here in allocation order and leaving
20213 // RIP in the class. Do they matter any more here than they do
20214 // in the normal allocation?
20215 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20216 if (Subtarget->is64Bit()) {
20217 if (VT == MVT::i32 || VT == MVT::f32)
20218 return std::make_pair(0U, &X86::GR32RegClass);
20219 if (VT == MVT::i16)
20220 return std::make_pair(0U, &X86::GR16RegClass);
20221 if (VT == MVT::i8 || VT == MVT::i1)
20222 return std::make_pair(0U, &X86::GR8RegClass);
20223 if (VT == MVT::i64 || VT == MVT::f64)
20224 return std::make_pair(0U, &X86::GR64RegClass);
20227 // 32-bit fallthrough
20228 case 'Q': // Q_REGS
20229 if (VT == MVT::i32 || VT == MVT::f32)
20230 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20231 if (VT == MVT::i16)
20232 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20233 if (VT == MVT::i8 || VT == MVT::i1)
20234 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20235 if (VT == MVT::i64)
20236 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20238 case 'r': // GENERAL_REGS
20239 case 'l': // INDEX_REGS
20240 if (VT == MVT::i8 || VT == MVT::i1)
20241 return std::make_pair(0U, &X86::GR8RegClass);
20242 if (VT == MVT::i16)
20243 return std::make_pair(0U, &X86::GR16RegClass);
20244 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20245 return std::make_pair(0U, &X86::GR32RegClass);
20246 return std::make_pair(0U, &X86::GR64RegClass);
20247 case 'R': // LEGACY_REGS
20248 if (VT == MVT::i8 || VT == MVT::i1)
20249 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20250 if (VT == MVT::i16)
20251 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20252 if (VT == MVT::i32 || !Subtarget->is64Bit())
20253 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20254 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20255 case 'f': // FP Stack registers.
20256 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20257 // value to the correct fpstack register class.
20258 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20259 return std::make_pair(0U, &X86::RFP32RegClass);
20260 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20261 return std::make_pair(0U, &X86::RFP64RegClass);
20262 return std::make_pair(0U, &X86::RFP80RegClass);
20263 case 'y': // MMX_REGS if MMX allowed.
20264 if (!Subtarget->hasMMX()) break;
20265 return std::make_pair(0U, &X86::VR64RegClass);
20266 case 'Y': // SSE_REGS if SSE2 allowed
20267 if (!Subtarget->hasSSE2()) break;
20269 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20270 if (!Subtarget->hasSSE1()) break;
20272 switch (VT.SimpleTy) {
20274 // Scalar SSE types.
20277 return std::make_pair(0U, &X86::FR32RegClass);
20280 return std::make_pair(0U, &X86::FR64RegClass);
20288 return std::make_pair(0U, &X86::VR128RegClass);
20296 return std::make_pair(0U, &X86::VR256RegClass);
20301 return std::make_pair(0U, &X86::VR512RegClass);
20307 // Use the default implementation in TargetLowering to convert the register
20308 // constraint into a member of a register class.
20309 std::pair<unsigned, const TargetRegisterClass*> Res;
20310 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20312 // Not found as a standard register?
20313 if (Res.second == 0) {
20314 // Map st(0) -> st(7) -> ST0
20315 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20316 tolower(Constraint[1]) == 's' &&
20317 tolower(Constraint[2]) == 't' &&
20318 Constraint[3] == '(' &&
20319 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20320 Constraint[5] == ')' &&
20321 Constraint[6] == '}') {
20323 Res.first = X86::ST0+Constraint[4]-'0';
20324 Res.second = &X86::RFP80RegClass;
20328 // GCC allows "st(0)" to be called just plain "st".
20329 if (StringRef("{st}").equals_lower(Constraint)) {
20330 Res.first = X86::ST0;
20331 Res.second = &X86::RFP80RegClass;
20336 if (StringRef("{flags}").equals_lower(Constraint)) {
20337 Res.first = X86::EFLAGS;
20338 Res.second = &X86::CCRRegClass;
20342 // 'A' means EAX + EDX.
20343 if (Constraint == "A") {
20344 Res.first = X86::EAX;
20345 Res.second = &X86::GR32_ADRegClass;
20351 // Otherwise, check to see if this is a register class of the wrong value
20352 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20353 // turn into {ax},{dx}.
20354 if (Res.second->hasType(VT))
20355 return Res; // Correct type already, nothing to do.
20357 // All of the single-register GCC register classes map their values onto
20358 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20359 // really want an 8-bit or 32-bit register, map to the appropriate register
20360 // class and return the appropriate register.
20361 if (Res.second == &X86::GR16RegClass) {
20362 if (VT == MVT::i8 || VT == MVT::i1) {
20363 unsigned DestReg = 0;
20364 switch (Res.first) {
20366 case X86::AX: DestReg = X86::AL; break;
20367 case X86::DX: DestReg = X86::DL; break;
20368 case X86::CX: DestReg = X86::CL; break;
20369 case X86::BX: DestReg = X86::BL; break;
20372 Res.first = DestReg;
20373 Res.second = &X86::GR8RegClass;
20375 } else if (VT == MVT::i32 || VT == MVT::f32) {
20376 unsigned DestReg = 0;
20377 switch (Res.first) {
20379 case X86::AX: DestReg = X86::EAX; break;
20380 case X86::DX: DestReg = X86::EDX; break;
20381 case X86::CX: DestReg = X86::ECX; break;
20382 case X86::BX: DestReg = X86::EBX; break;
20383 case X86::SI: DestReg = X86::ESI; break;
20384 case X86::DI: DestReg = X86::EDI; break;
20385 case X86::BP: DestReg = X86::EBP; break;
20386 case X86::SP: DestReg = X86::ESP; break;
20389 Res.first = DestReg;
20390 Res.second = &X86::GR32RegClass;
20392 } else if (VT == MVT::i64 || VT == MVT::f64) {
20393 unsigned DestReg = 0;
20394 switch (Res.first) {
20396 case X86::AX: DestReg = X86::RAX; break;
20397 case X86::DX: DestReg = X86::RDX; break;
20398 case X86::CX: DestReg = X86::RCX; break;
20399 case X86::BX: DestReg = X86::RBX; break;
20400 case X86::SI: DestReg = X86::RSI; break;
20401 case X86::DI: DestReg = X86::RDI; break;
20402 case X86::BP: DestReg = X86::RBP; break;
20403 case X86::SP: DestReg = X86::RSP; break;
20406 Res.first = DestReg;
20407 Res.second = &X86::GR64RegClass;
20410 } else if (Res.second == &X86::FR32RegClass ||
20411 Res.second == &X86::FR64RegClass ||
20412 Res.second == &X86::VR128RegClass ||
20413 Res.second == &X86::VR256RegClass ||
20414 Res.second == &X86::FR32XRegClass ||
20415 Res.second == &X86::FR64XRegClass ||
20416 Res.second == &X86::VR128XRegClass ||
20417 Res.second == &X86::VR256XRegClass ||
20418 Res.second == &X86::VR512RegClass) {
20419 // Handle references to XMM physical registers that got mapped into the
20420 // wrong class. This can happen with constraints like {xmm0} where the
20421 // target independent register mapper will just pick the first match it can
20422 // find, ignoring the required type.
20424 if (VT == MVT::f32 || VT == MVT::i32)
20425 Res.second = &X86::FR32RegClass;
20426 else if (VT == MVT::f64 || VT == MVT::i64)
20427 Res.second = &X86::FR64RegClass;
20428 else if (X86::VR128RegClass.hasType(VT))
20429 Res.second = &X86::VR128RegClass;
20430 else if (X86::VR256RegClass.hasType(VT))
20431 Res.second = &X86::VR256RegClass;
20432 else if (X86::VR512RegClass.hasType(VT))
20433 Res.second = &X86::VR512RegClass;