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"
18 #include "X86CallingConv.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.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->isTargetKnownWindowsMSVC())
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->isTargetKnownWindowsMSVC()) {
254 // Setup Windows compiler runtime calls.
255 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
256 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
257 setLibcallName(RTLIB::SREM_I64, "_allrem");
258 setLibcallName(RTLIB::UREM_I64, "_aullrem");
259 setLibcallName(RTLIB::MUL_I64, "_allmul");
260 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
261 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266 // The _ftol2 runtime function has an unusual calling conv, which
267 // is modeled by a special pseudo-instruction.
268 setLibcallName(RTLIB::FPTOUINT_F64_I64, 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->isTargetWindowsGNU()) {
279 // MS runtime is weird: it exports _setjmp, but longjmp!
280 setUseUnderscoreSetJmp(true);
281 setUseUnderscoreLongJmp(false);
283 setUseUnderscoreSetJmp(true);
284 setUseUnderscoreLongJmp(true);
287 // Set up the register classes.
288 addRegisterClass(MVT::i8, &X86::GR8RegClass);
289 addRegisterClass(MVT::i16, &X86::GR16RegClass);
290 addRegisterClass(MVT::i32, &X86::GR32RegClass);
291 if (Subtarget->is64Bit())
292 addRegisterClass(MVT::i64, &X86::GR64RegClass);
294 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296 // We don't accept any truncstore of integer registers.
297 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
304 // SETOEQ and SETUNE require checking two conditions.
305 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
312 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
314 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
315 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
316 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
318 if (Subtarget->is64Bit()) {
319 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
320 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
321 } else if (!TM.Options.UseSoftFloat) {
322 // We have an algorithm for SSE2->double, and we turn this into a
323 // 64-bit FILD followed by conditional FADD for other targets.
324 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
325 // We have an algorithm for SSE2, and we turn this into a 64-bit
326 // FILD for other targets.
327 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
330 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
332 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
333 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
335 if (!TM.Options.UseSoftFloat) {
336 // SSE has no i16 to fp conversion, only i32
337 if (X86ScalarSSEf32) {
338 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
339 // f32 and f64 cases are Legal, f80 case is not
340 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
342 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
343 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
346 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
347 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
350 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
351 // are Legal, f80 is custom lowered.
352 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
353 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
355 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
357 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
358 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
360 if (X86ScalarSSEf32) {
361 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
362 // f32 and f64 cases are Legal, f80 case is not
363 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
365 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
366 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
369 // Handle FP_TO_UINT by promoting the destination to a larger signed
371 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
372 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
373 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
375 if (Subtarget->is64Bit()) {
376 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
377 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
378 } else if (!TM.Options.UseSoftFloat) {
379 // Since AVX is a superset of SSE3, only check for SSE here.
380 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381 // Expand FP_TO_UINT into a select.
382 // FIXME: We would like to use a Custom expander here eventually to do
383 // the optimal thing for SSE vs. the default expansion in the legalizer.
384 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
386 // With SSE3 we can use fisttpll to convert to a signed i64; without
387 // SSE, we're stuck with a fistpll.
388 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
391 if (isTargetFTOL()) {
392 // Use the _ftol2 runtime function, which has a pseudo-instruction
393 // to handle its weird calling convention.
394 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
397 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398 if (!X86ScalarSSEf64) {
399 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
400 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
401 if (Subtarget->is64Bit()) {
402 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
403 // Without SSE, i64->f64 goes through memory.
404 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
408 // Scalar integer divide and remainder are lowered to use operations that
409 // produce two results, to match the available instructions. This exposes
410 // the two-result form to trivial CSE, which is able to combine x/y and x%y
411 // into a single instruction.
413 // Scalar integer multiply-high is also lowered to use two-result
414 // operations, to match the available instructions. However, plain multiply
415 // (low) operations are left as Legal, as there are single-result
416 // instructions for this in x86. Using the two-result multiply instructions
417 // when both high and low results are needed must be arranged by dagcombine.
418 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
420 setOperationAction(ISD::MULHS, VT, Expand);
421 setOperationAction(ISD::MULHU, VT, Expand);
422 setOperationAction(ISD::SDIV, VT, Expand);
423 setOperationAction(ISD::UDIV, VT, Expand);
424 setOperationAction(ISD::SREM, VT, Expand);
425 setOperationAction(ISD::UREM, VT, Expand);
427 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428 setOperationAction(ISD::ADDC, VT, Custom);
429 setOperationAction(ISD::ADDE, VT, Custom);
430 setOperationAction(ISD::SUBC, VT, Custom);
431 setOperationAction(ISD::SUBE, VT, Custom);
434 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
435 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
436 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
437 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
438 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
439 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
443 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
444 if (Subtarget->is64Bit())
445 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
449 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
450 setOperationAction(ISD::FREM , MVT::f32 , Expand);
451 setOperationAction(ISD::FREM , MVT::f64 , Expand);
452 setOperationAction(ISD::FREM , MVT::f80 , Expand);
453 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
455 // Promote the i8 variants and force them on up to i32 which has a shorter
457 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
458 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
459 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
460 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
461 if (Subtarget->hasBMI()) {
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
464 if (Subtarget->is64Bit())
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
467 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
468 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
469 if (Subtarget->is64Bit())
470 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
473 if (Subtarget->hasLZCNT()) {
474 // When promoting the i8 variants, force them to i32 for a shorter
476 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
477 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
478 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
482 if (Subtarget->is64Bit())
483 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
485 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
486 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
487 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
491 if (Subtarget->is64Bit()) {
492 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
493 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
497 if (Subtarget->hasPOPCNT()) {
498 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
500 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
501 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
502 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
507 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
509 if (!Subtarget->hasMOVBE())
510 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
512 // These should be promoted to a larger select which is supported.
513 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
514 // X86 wants to expand cmov itself.
515 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
516 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
517 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
518 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
519 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
521 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
522 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
524 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
525 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
527 if (Subtarget->is64Bit()) {
528 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
529 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
531 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
532 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
533 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
534 // support continuation, user-level threading, and etc.. As a result, no
535 // other SjLj exception interfaces are implemented and please don't build
536 // your own exception handling based on them.
537 // LLVM/Clang supports zero-cost DWARF exception handling.
538 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
539 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
542 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
543 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
544 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
545 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
546 if (Subtarget->is64Bit())
547 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
548 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
549 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
550 if (Subtarget->is64Bit()) {
551 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
552 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
553 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
554 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
555 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
557 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
558 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
559 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
560 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
561 if (Subtarget->is64Bit()) {
562 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
563 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
564 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
567 if (Subtarget->hasSSE1())
568 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
570 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
572 // Expand certain atomics
573 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
575 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
576 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
577 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
580 if (!Subtarget->is64Bit()) {
581 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
582 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
595 if (Subtarget->hasCmpxchg16b()) {
596 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
599 // FIXME - use subtarget debug flags
600 if (!Subtarget->isTargetDarwin() &&
601 !Subtarget->isTargetELF() &&
602 !Subtarget->isTargetCygMing()) {
603 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
606 if (Subtarget->is64Bit()) {
607 setExceptionPointerRegister(X86::RAX);
608 setExceptionSelectorRegister(X86::RDX);
610 setExceptionPointerRegister(X86::EAX);
611 setExceptionSelectorRegister(X86::EDX);
613 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
614 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
616 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
617 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
619 setOperationAction(ISD::TRAP, MVT::Other, Legal);
620 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
622 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
623 setOperationAction(ISD::VASTART , MVT::Other, Custom);
624 setOperationAction(ISD::VAEND , MVT::Other, Expand);
625 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
626 // TargetInfo::X86_64ABIBuiltinVaList
627 setOperationAction(ISD::VAARG , MVT::Other, Custom);
628 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
630 // TargetInfo::CharPtrBuiltinVaList
631 setOperationAction(ISD::VAARG , MVT::Other, Expand);
632 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
635 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
636 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
638 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::FP_TO_UINT, MVT::v4i32, Legal);
1362 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1363 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1364 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1365 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1366 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1367 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1369 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1372 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1373 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1374 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1375 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1376 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1377 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1378 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1379 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1380 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1381 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1383 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1384 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1386 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1387 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1388 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1390 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1391 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1393 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1395 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1397 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1398 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1399 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1400 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1401 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1403 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1404 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1406 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1407 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1409 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1411 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1412 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1414 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1415 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1417 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1418 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1420 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1421 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1422 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1423 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1424 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1425 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1427 // Custom lower several nodes.
1428 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1429 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1430 MVT VT = (MVT::SimpleValueType)i;
1432 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1433 // Extract subvector is special because the value type
1434 // (result) is 256/128-bit but the source is 512-bit wide.
1435 if (VT.is128BitVector() || VT.is256BitVector())
1436 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1438 if (VT.getVectorElementType() == MVT::i1)
1439 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1441 // Do not attempt to custom lower other non-512-bit vectors
1442 if (!VT.is512BitVector())
1445 if ( EltSize >= 32) {
1446 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1447 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1448 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1449 setOperationAction(ISD::VSELECT, VT, Legal);
1450 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1451 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1452 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1455 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1456 MVT VT = (MVT::SimpleValueType)i;
1458 // Do not attempt to promote non-256-bit vectors
1459 if (!VT.is512BitVector())
1462 setOperationAction(ISD::SELECT, VT, Promote);
1463 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1467 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1468 // of this type with custom code.
1469 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1470 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1471 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1475 // We want to custom lower some of our intrinsics.
1476 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1477 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1478 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1480 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1481 // handle type legalization for these operations here.
1483 // FIXME: We really should do custom legalization for addition and
1484 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1485 // than generic legalization for 64-bit multiplication-with-overflow, though.
1486 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1487 // Add/Sub/Mul with overflow operations are custom lowered.
1489 setOperationAction(ISD::SADDO, VT, Custom);
1490 setOperationAction(ISD::UADDO, VT, Custom);
1491 setOperationAction(ISD::SSUBO, VT, Custom);
1492 setOperationAction(ISD::USUBO, VT, Custom);
1493 setOperationAction(ISD::SMULO, VT, Custom);
1494 setOperationAction(ISD::UMULO, VT, Custom);
1497 // There are no 8-bit 3-address imul/mul instructions
1498 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1499 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1501 if (!Subtarget->is64Bit()) {
1502 // These libcalls are not available in 32-bit.
1503 setLibcallName(RTLIB::SHL_I128, 0);
1504 setLibcallName(RTLIB::SRL_I128, 0);
1505 setLibcallName(RTLIB::SRA_I128, 0);
1508 // Combine sin / cos into one node or libcall if possible.
1509 if (Subtarget->hasSinCos()) {
1510 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1511 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1512 if (Subtarget->isTargetDarwin()) {
1513 // For MacOSX, we don't want to the normal expansion of a libcall to
1514 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1516 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1517 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1521 // We have target-specific dag combine patterns for the following nodes:
1522 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1523 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1524 setTargetDAGCombine(ISD::VSELECT);
1525 setTargetDAGCombine(ISD::SELECT);
1526 setTargetDAGCombine(ISD::SHL);
1527 setTargetDAGCombine(ISD::SRA);
1528 setTargetDAGCombine(ISD::SRL);
1529 setTargetDAGCombine(ISD::OR);
1530 setTargetDAGCombine(ISD::AND);
1531 setTargetDAGCombine(ISD::ADD);
1532 setTargetDAGCombine(ISD::FADD);
1533 setTargetDAGCombine(ISD::FSUB);
1534 setTargetDAGCombine(ISD::FMA);
1535 setTargetDAGCombine(ISD::SUB);
1536 setTargetDAGCombine(ISD::LOAD);
1537 setTargetDAGCombine(ISD::STORE);
1538 setTargetDAGCombine(ISD::ZERO_EXTEND);
1539 setTargetDAGCombine(ISD::ANY_EXTEND);
1540 setTargetDAGCombine(ISD::SIGN_EXTEND);
1541 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1542 setTargetDAGCombine(ISD::TRUNCATE);
1543 setTargetDAGCombine(ISD::SINT_TO_FP);
1544 setTargetDAGCombine(ISD::SETCC);
1545 if (Subtarget->is64Bit())
1546 setTargetDAGCombine(ISD::MUL);
1547 setTargetDAGCombine(ISD::XOR);
1549 computeRegisterProperties();
1551 // On Darwin, -Os means optimize for size without hurting performance,
1552 // do not reduce the limit.
1553 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1554 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1555 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1556 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1557 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1558 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1559 setPrefLoopAlignment(4); // 2^4 bytes.
1561 // Predictable cmov don't hurt on atom because it's in-order.
1562 PredictableSelectIsExpensive = !Subtarget->isAtom();
1564 setPrefFunctionAlignment(4); // 2^4 bytes.
1567 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1569 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1571 if (Subtarget->hasAVX512())
1572 switch(VT.getVectorNumElements()) {
1573 case 8: return MVT::v8i1;
1574 case 16: return MVT::v16i1;
1577 return VT.changeVectorElementTypeToInteger();
1580 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1581 /// the desired ByVal argument alignment.
1582 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1585 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1586 if (VTy->getBitWidth() == 128)
1588 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1589 unsigned EltAlign = 0;
1590 getMaxByValAlign(ATy->getElementType(), EltAlign);
1591 if (EltAlign > MaxAlign)
1592 MaxAlign = EltAlign;
1593 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1594 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1595 unsigned EltAlign = 0;
1596 getMaxByValAlign(STy->getElementType(i), EltAlign);
1597 if (EltAlign > MaxAlign)
1598 MaxAlign = EltAlign;
1605 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1606 /// function arguments in the caller parameter area. For X86, aggregates
1607 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1608 /// are at 4-byte boundaries.
1609 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1610 if (Subtarget->is64Bit()) {
1611 // Max of 8 and alignment of type.
1612 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1619 if (Subtarget->hasSSE1())
1620 getMaxByValAlign(Ty, Align);
1624 /// getOptimalMemOpType - Returns the target specific optimal type for load
1625 /// and store operations as a result of memset, memcpy, and memmove
1626 /// lowering. If DstAlign is zero that means it's safe to destination
1627 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1628 /// means there isn't a need to check it against alignment requirement,
1629 /// probably because the source does not need to be loaded. If 'IsMemset' is
1630 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1631 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1632 /// source is constant so it does not need to be loaded.
1633 /// It returns EVT::Other if the type should be determined using generic
1634 /// target-independent logic.
1636 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1637 unsigned DstAlign, unsigned SrcAlign,
1638 bool IsMemset, bool ZeroMemset,
1640 MachineFunction &MF) const {
1641 const Function *F = MF.getFunction();
1642 if ((!IsMemset || ZeroMemset) &&
1643 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1644 Attribute::NoImplicitFloat)) {
1646 (Subtarget->isUnalignedMemAccessFast() ||
1647 ((DstAlign == 0 || DstAlign >= 16) &&
1648 (SrcAlign == 0 || SrcAlign >= 16)))) {
1650 if (Subtarget->hasInt256())
1652 if (Subtarget->hasFp256())
1655 if (Subtarget->hasSSE2())
1657 if (Subtarget->hasSSE1())
1659 } else if (!MemcpyStrSrc && Size >= 8 &&
1660 !Subtarget->is64Bit() &&
1661 Subtarget->hasSSE2()) {
1662 // Do not use f64 to lower memcpy if source is string constant. It's
1663 // better to use i32 to avoid the loads.
1667 if (Subtarget->is64Bit() && Size >= 8)
1672 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1674 return X86ScalarSSEf32;
1675 else if (VT == MVT::f64)
1676 return X86ScalarSSEf64;
1681 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1685 *Fast = Subtarget->isUnalignedMemAccessFast();
1689 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1690 /// current function. The returned value is a member of the
1691 /// MachineJumpTableInfo::JTEntryKind enum.
1692 unsigned X86TargetLowering::getJumpTableEncoding() const {
1693 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1695 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1696 Subtarget->isPICStyleGOT())
1697 return MachineJumpTableInfo::EK_Custom32;
1699 // Otherwise, use the normal jump table encoding heuristics.
1700 return TargetLowering::getJumpTableEncoding();
1704 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1705 const MachineBasicBlock *MBB,
1706 unsigned uid,MCContext &Ctx) const{
1707 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1708 Subtarget->isPICStyleGOT());
1709 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1711 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1712 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1715 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1717 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1718 SelectionDAG &DAG) const {
1719 if (!Subtarget->is64Bit())
1720 // This doesn't have SDLoc associated with it, but is not really the
1721 // same as a Register.
1722 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1726 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1727 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1729 const MCExpr *X86TargetLowering::
1730 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1731 MCContext &Ctx) const {
1732 // X86-64 uses RIP relative addressing based on the jump table label.
1733 if (Subtarget->isPICStyleRIPRel())
1734 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1736 // Otherwise, the reference is relative to the PIC base.
1737 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1740 // FIXME: Why this routine is here? Move to RegInfo!
1741 std::pair<const TargetRegisterClass*, uint8_t>
1742 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1743 const TargetRegisterClass *RRC = 0;
1745 switch (VT.SimpleTy) {
1747 return TargetLowering::findRepresentativeClass(VT);
1748 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1749 RRC = Subtarget->is64Bit() ?
1750 (const TargetRegisterClass*)&X86::GR64RegClass :
1751 (const TargetRegisterClass*)&X86::GR32RegClass;
1754 RRC = &X86::VR64RegClass;
1756 case MVT::f32: case MVT::f64:
1757 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1758 case MVT::v4f32: case MVT::v2f64:
1759 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1761 RRC = &X86::VR128RegClass;
1764 return std::make_pair(RRC, Cost);
1767 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1768 unsigned &Offset) const {
1769 if (!Subtarget->isTargetLinux())
1772 if (Subtarget->is64Bit()) {
1773 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1775 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1787 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1788 unsigned DestAS) const {
1789 assert(SrcAS != DestAS && "Expected different address spaces!");
1791 return SrcAS < 256 && DestAS < 256;
1794 //===----------------------------------------------------------------------===//
1795 // Return Value Calling Convention Implementation
1796 //===----------------------------------------------------------------------===//
1798 #include "X86GenCallingConv.inc"
1801 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1802 MachineFunction &MF, bool isVarArg,
1803 const SmallVectorImpl<ISD::OutputArg> &Outs,
1804 LLVMContext &Context) const {
1805 SmallVector<CCValAssign, 16> RVLocs;
1806 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1808 return CCInfo.CheckReturn(Outs, RetCC_X86);
1811 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1812 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1817 X86TargetLowering::LowerReturn(SDValue Chain,
1818 CallingConv::ID CallConv, bool isVarArg,
1819 const SmallVectorImpl<ISD::OutputArg> &Outs,
1820 const SmallVectorImpl<SDValue> &OutVals,
1821 SDLoc dl, SelectionDAG &DAG) const {
1822 MachineFunction &MF = DAG.getMachineFunction();
1823 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1825 SmallVector<CCValAssign, 16> RVLocs;
1826 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1827 RVLocs, *DAG.getContext());
1828 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1831 SmallVector<SDValue, 6> RetOps;
1832 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1833 // Operand #1 = Bytes To Pop
1834 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1837 // Copy the result values into the output registers.
1838 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1839 CCValAssign &VA = RVLocs[i];
1840 assert(VA.isRegLoc() && "Can only return in registers!");
1841 SDValue ValToCopy = OutVals[i];
1842 EVT ValVT = ValToCopy.getValueType();
1844 // Promote values to the appropriate types
1845 if (VA.getLocInfo() == CCValAssign::SExt)
1846 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1847 else if (VA.getLocInfo() == CCValAssign::ZExt)
1848 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1849 else if (VA.getLocInfo() == CCValAssign::AExt)
1850 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1851 else if (VA.getLocInfo() == CCValAssign::BCvt)
1852 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1854 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1855 "Unexpected FP-extend for return value.");
1857 // If this is x86-64, and we disabled SSE, we can't return FP values,
1858 // or SSE or MMX vectors.
1859 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1860 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1861 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1862 report_fatal_error("SSE register return with SSE disabled");
1864 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1865 // llvm-gcc has never done it right and no one has noticed, so this
1866 // should be OK for now.
1867 if (ValVT == MVT::f64 &&
1868 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1869 report_fatal_error("SSE2 register return with SSE2 disabled");
1871 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1872 // the RET instruction and handled by the FP Stackifier.
1873 if (VA.getLocReg() == X86::ST0 ||
1874 VA.getLocReg() == X86::ST1) {
1875 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1876 // change the value to the FP stack register class.
1877 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1878 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1879 RetOps.push_back(ValToCopy);
1880 // Don't emit a copytoreg.
1884 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1885 // which is returned in RAX / RDX.
1886 if (Subtarget->is64Bit()) {
1887 if (ValVT == MVT::x86mmx) {
1888 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1889 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1890 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1892 // If we don't have SSE2 available, convert to v4f32 so the generated
1893 // register is legal.
1894 if (!Subtarget->hasSSE2())
1895 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1900 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1901 Flag = Chain.getValue(1);
1902 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1905 // The x86-64 ABIs require that for returning structs by value we copy
1906 // the sret argument into %rax/%eax (depending on ABI) for the return.
1907 // Win32 requires us to put the sret argument to %eax as well.
1908 // We saved the argument into a virtual register in the entry block,
1909 // so now we copy the value out and into %rax/%eax.
1910 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1911 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1912 MachineFunction &MF = DAG.getMachineFunction();
1913 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1914 unsigned Reg = FuncInfo->getSRetReturnReg();
1916 "SRetReturnReg should have been set in LowerFormalArguments().");
1917 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1920 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1921 X86::RAX : X86::EAX;
1922 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1923 Flag = Chain.getValue(1);
1925 // RAX/EAX now acts like a return value.
1926 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1929 RetOps[0] = Chain; // Update chain.
1931 // Add the flag if we have it.
1933 RetOps.push_back(Flag);
1935 return DAG.getNode(X86ISD::RET_FLAG, dl,
1936 MVT::Other, &RetOps[0], RetOps.size());
1939 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1940 if (N->getNumValues() != 1)
1942 if (!N->hasNUsesOfValue(1, 0))
1945 SDValue TCChain = Chain;
1946 SDNode *Copy = *N->use_begin();
1947 if (Copy->getOpcode() == ISD::CopyToReg) {
1948 // If the copy has a glue operand, we conservatively assume it isn't safe to
1949 // perform a tail call.
1950 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1952 TCChain = Copy->getOperand(0);
1953 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1956 bool HasRet = false;
1957 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1959 if (UI->getOpcode() != X86ISD::RET_FLAG)
1972 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1973 ISD::NodeType ExtendKind) const {
1975 // TODO: Is this also valid on 32-bit?
1976 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1977 ReturnMVT = MVT::i8;
1979 ReturnMVT = MVT::i32;
1981 MVT MinVT = getRegisterType(ReturnMVT);
1982 return VT.bitsLT(MinVT) ? MinVT : VT;
1985 /// LowerCallResult - Lower the result values of a call into the
1986 /// appropriate copies out of appropriate physical registers.
1989 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1990 CallingConv::ID CallConv, bool isVarArg,
1991 const SmallVectorImpl<ISD::InputArg> &Ins,
1992 SDLoc dl, SelectionDAG &DAG,
1993 SmallVectorImpl<SDValue> &InVals) const {
1995 // Assign locations to each value returned by this call.
1996 SmallVector<CCValAssign, 16> RVLocs;
1997 bool Is64Bit = Subtarget->is64Bit();
1998 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1999 getTargetMachine(), RVLocs, *DAG.getContext());
2000 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2002 // Copy all of the result registers out of their specified physreg.
2003 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2004 CCValAssign &VA = RVLocs[i];
2005 EVT CopyVT = VA.getValVT();
2007 // If this is x86-64, and we disabled SSE, we can't return FP values
2008 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2009 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2010 report_fatal_error("SSE register return with SSE disabled");
2015 // If this is a call to a function that returns an fp value on the floating
2016 // point stack, we must guarantee the value is popped from the stack, so
2017 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2018 // if the return value is not used. We use the FpPOP_RETVAL instruction
2020 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2021 // If we prefer to use the value in xmm registers, copy it out as f80 and
2022 // use a truncate to move it from fp stack reg to xmm reg.
2023 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2024 SDValue Ops[] = { Chain, InFlag };
2025 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2026 MVT::Other, MVT::Glue, Ops), 1);
2027 Val = Chain.getValue(0);
2029 // Round the f80 to the right size, which also moves it to the appropriate
2031 if (CopyVT != VA.getValVT())
2032 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2033 // This truncation won't change the value.
2034 DAG.getIntPtrConstant(1));
2036 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2037 CopyVT, InFlag).getValue(1);
2038 Val = Chain.getValue(0);
2040 InFlag = Chain.getValue(2);
2041 InVals.push_back(Val);
2047 //===----------------------------------------------------------------------===//
2048 // C & StdCall & Fast Calling Convention implementation
2049 //===----------------------------------------------------------------------===//
2050 // StdCall calling convention seems to be standard for many Windows' API
2051 // routines and around. It differs from C calling convention just a little:
2052 // callee should clean up the stack, not caller. Symbols should be also
2053 // decorated in some fancy way :) It doesn't support any vector arguments.
2054 // For info on fast calling convention see Fast Calling Convention (tail call)
2055 // implementation LowerX86_32FastCCCallTo.
2057 /// CallIsStructReturn - Determines whether a call uses struct return
2059 enum StructReturnType {
2064 static StructReturnType
2065 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2067 return NotStructReturn;
2069 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2070 if (!Flags.isSRet())
2071 return NotStructReturn;
2072 if (Flags.isInReg())
2073 return RegStructReturn;
2074 return StackStructReturn;
2077 /// ArgsAreStructReturn - Determines whether a function uses struct
2078 /// return semantics.
2079 static StructReturnType
2080 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2082 return NotStructReturn;
2084 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2085 if (!Flags.isSRet())
2086 return NotStructReturn;
2087 if (Flags.isInReg())
2088 return RegStructReturn;
2089 return StackStructReturn;
2092 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2093 /// by "Src" to address "Dst" with size and alignment information specified by
2094 /// the specific parameter attribute. The copy will be passed as a byval
2095 /// function parameter.
2097 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2098 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2100 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2102 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2103 /*isVolatile*/false, /*AlwaysInline=*/true,
2104 MachinePointerInfo(), MachinePointerInfo());
2107 /// IsTailCallConvention - Return true if the calling convention is one that
2108 /// supports tail call optimization.
2109 static bool IsTailCallConvention(CallingConv::ID CC) {
2110 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2111 CC == CallingConv::HiPE);
2114 /// \brief Return true if the calling convention is a C calling convention.
2115 static bool IsCCallConvention(CallingConv::ID CC) {
2116 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2117 CC == CallingConv::X86_64_SysV);
2120 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2121 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2125 CallingConv::ID CalleeCC = CS.getCallingConv();
2126 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2132 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2133 /// a tailcall target by changing its ABI.
2134 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2135 bool GuaranteedTailCallOpt) {
2136 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2140 X86TargetLowering::LowerMemArgument(SDValue Chain,
2141 CallingConv::ID CallConv,
2142 const SmallVectorImpl<ISD::InputArg> &Ins,
2143 SDLoc dl, SelectionDAG &DAG,
2144 const CCValAssign &VA,
2145 MachineFrameInfo *MFI,
2147 // Create the nodes corresponding to a load from this parameter slot.
2148 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2149 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2150 getTargetMachine().Options.GuaranteedTailCallOpt);
2151 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2154 // If value is passed by pointer we have address passed instead of the value
2156 if (VA.getLocInfo() == CCValAssign::Indirect)
2157 ValVT = VA.getLocVT();
2159 ValVT = VA.getValVT();
2161 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2162 // changed with more analysis.
2163 // In case of tail call optimization mark all arguments mutable. Since they
2164 // could be overwritten by lowering of arguments in case of a tail call.
2165 if (Flags.isByVal()) {
2166 unsigned Bytes = Flags.getByValSize();
2167 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2168 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2169 return DAG.getFrameIndex(FI, getPointerTy());
2171 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2172 VA.getLocMemOffset(), isImmutable);
2173 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2174 return DAG.getLoad(ValVT, dl, Chain, FIN,
2175 MachinePointerInfo::getFixedStack(FI),
2176 false, false, false, 0);
2181 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2182 CallingConv::ID CallConv,
2184 const SmallVectorImpl<ISD::InputArg> &Ins,
2187 SmallVectorImpl<SDValue> &InVals)
2189 MachineFunction &MF = DAG.getMachineFunction();
2190 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2192 const Function* Fn = MF.getFunction();
2193 if (Fn->hasExternalLinkage() &&
2194 Subtarget->isTargetCygMing() &&
2195 Fn->getName() == "main")
2196 FuncInfo->setForceFramePointer(true);
2198 MachineFrameInfo *MFI = MF.getFrameInfo();
2199 bool Is64Bit = Subtarget->is64Bit();
2200 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2202 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2203 "Var args not supported with calling convention fastcc, ghc or hipe");
2205 // Assign locations to all of the incoming arguments.
2206 SmallVector<CCValAssign, 16> ArgLocs;
2207 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2208 ArgLocs, *DAG.getContext());
2210 // Allocate shadow area for Win64
2212 CCInfo.AllocateStack(32, 8);
2214 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2216 unsigned LastVal = ~0U;
2218 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2219 CCValAssign &VA = ArgLocs[i];
2220 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2222 assert(VA.getValNo() != LastVal &&
2223 "Don't support value assigned to multiple locs yet");
2225 LastVal = VA.getValNo();
2227 if (VA.isRegLoc()) {
2228 EVT RegVT = VA.getLocVT();
2229 const TargetRegisterClass *RC;
2230 if (RegVT == MVT::i32)
2231 RC = &X86::GR32RegClass;
2232 else if (Is64Bit && RegVT == MVT::i64)
2233 RC = &X86::GR64RegClass;
2234 else if (RegVT == MVT::f32)
2235 RC = &X86::FR32RegClass;
2236 else if (RegVT == MVT::f64)
2237 RC = &X86::FR64RegClass;
2238 else if (RegVT.is512BitVector())
2239 RC = &X86::VR512RegClass;
2240 else if (RegVT.is256BitVector())
2241 RC = &X86::VR256RegClass;
2242 else if (RegVT.is128BitVector())
2243 RC = &X86::VR128RegClass;
2244 else if (RegVT == MVT::x86mmx)
2245 RC = &X86::VR64RegClass;
2246 else if (RegVT == MVT::i1)
2247 RC = &X86::VK1RegClass;
2248 else if (RegVT == MVT::v8i1)
2249 RC = &X86::VK8RegClass;
2250 else if (RegVT == MVT::v16i1)
2251 RC = &X86::VK16RegClass;
2253 llvm_unreachable("Unknown argument type!");
2255 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2256 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2258 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2259 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2261 if (VA.getLocInfo() == CCValAssign::SExt)
2262 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2263 DAG.getValueType(VA.getValVT()));
2264 else if (VA.getLocInfo() == CCValAssign::ZExt)
2265 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2266 DAG.getValueType(VA.getValVT()));
2267 else if (VA.getLocInfo() == CCValAssign::BCvt)
2268 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2270 if (VA.isExtInLoc()) {
2271 // Handle MMX values passed in XMM regs.
2272 if (RegVT.isVector())
2273 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2275 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2278 assert(VA.isMemLoc());
2279 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2282 // If value is passed via pointer - do a load.
2283 if (VA.getLocInfo() == CCValAssign::Indirect)
2284 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2285 MachinePointerInfo(), false, false, false, 0);
2287 InVals.push_back(ArgValue);
2290 // The x86-64 ABIs require that for returning structs by value we copy
2291 // the sret argument into %rax/%eax (depending on ABI) for the return.
2292 // Win32 requires us to put the sret argument to %eax as well.
2293 // Save the argument into a virtual register so that we can access it
2294 // from the return points.
2295 if (MF.getFunction()->hasStructRetAttr() &&
2296 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2297 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2298 unsigned Reg = FuncInfo->getSRetReturnReg();
2300 MVT PtrTy = getPointerTy();
2301 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2302 FuncInfo->setSRetReturnReg(Reg);
2304 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2305 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2308 unsigned StackSize = CCInfo.getNextStackOffset();
2309 // Align stack specially for tail calls.
2310 if (FuncIsMadeTailCallSafe(CallConv,
2311 MF.getTarget().Options.GuaranteedTailCallOpt))
2312 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2314 // If the function takes variable number of arguments, make a frame index for
2315 // the start of the first vararg value... for expansion of llvm.va_start.
2317 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2318 CallConv != CallingConv::X86_ThisCall)) {
2319 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2322 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2324 // FIXME: We should really autogenerate these arrays
2325 static const MCPhysReg GPR64ArgRegsWin64[] = {
2326 X86::RCX, X86::RDX, X86::R8, X86::R9
2328 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2329 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2331 static const MCPhysReg XMMArgRegs64Bit[] = {
2332 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2333 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2335 const MCPhysReg *GPR64ArgRegs;
2336 unsigned NumXMMRegs = 0;
2339 // The XMM registers which might contain var arg parameters are shadowed
2340 // in their paired GPR. So we only need to save the GPR to their home
2342 TotalNumIntRegs = 4;
2343 GPR64ArgRegs = GPR64ArgRegsWin64;
2345 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2346 GPR64ArgRegs = GPR64ArgRegs64Bit;
2348 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2351 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2354 bool NoImplicitFloatOps = Fn->getAttributes().
2355 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2356 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2357 "SSE register cannot be used when SSE is disabled!");
2358 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2359 NoImplicitFloatOps) &&
2360 "SSE register cannot be used when SSE is disabled!");
2361 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2362 !Subtarget->hasSSE1())
2363 // Kernel mode asks for SSE to be disabled, so don't push them
2365 TotalNumXMMRegs = 0;
2368 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2369 // Get to the caller-allocated home save location. Add 8 to account
2370 // for the return address.
2371 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2372 FuncInfo->setRegSaveFrameIndex(
2373 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2374 // Fixup to set vararg frame on shadow area (4 x i64).
2376 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2378 // For X86-64, if there are vararg parameters that are passed via
2379 // registers, then we must store them to their spots on the stack so
2380 // they may be loaded by deferencing the result of va_next.
2381 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2382 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2383 FuncInfo->setRegSaveFrameIndex(
2384 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2388 // Store the integer parameter registers.
2389 SmallVector<SDValue, 8> MemOps;
2390 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2392 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2393 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2394 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2395 DAG.getIntPtrConstant(Offset));
2396 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2397 &X86::GR64RegClass);
2398 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2400 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2401 MachinePointerInfo::getFixedStack(
2402 FuncInfo->getRegSaveFrameIndex(), Offset),
2404 MemOps.push_back(Store);
2408 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2409 // Now store the XMM (fp + vector) parameter registers.
2410 SmallVector<SDValue, 11> SaveXMMOps;
2411 SaveXMMOps.push_back(Chain);
2413 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2414 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2415 SaveXMMOps.push_back(ALVal);
2417 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2418 FuncInfo->getRegSaveFrameIndex()));
2419 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2420 FuncInfo->getVarArgsFPOffset()));
2422 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2423 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2424 &X86::VR128RegClass);
2425 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2426 SaveXMMOps.push_back(Val);
2428 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2430 &SaveXMMOps[0], SaveXMMOps.size()));
2433 if (!MemOps.empty())
2434 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2435 &MemOps[0], MemOps.size());
2439 // Some CCs need callee pop.
2440 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2441 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2442 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2444 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2445 // If this is an sret function, the return should pop the hidden pointer.
2446 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2447 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2448 argsAreStructReturn(Ins) == StackStructReturn)
2449 FuncInfo->setBytesToPopOnReturn(4);
2453 // RegSaveFrameIndex is X86-64 only.
2454 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2455 if (CallConv == CallingConv::X86_FastCall ||
2456 CallConv == CallingConv::X86_ThisCall)
2457 // fastcc functions can't have varargs.
2458 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2461 FuncInfo->setArgumentStackSize(StackSize);
2467 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2468 SDValue StackPtr, SDValue Arg,
2469 SDLoc dl, SelectionDAG &DAG,
2470 const CCValAssign &VA,
2471 ISD::ArgFlagsTy Flags) const {
2472 unsigned LocMemOffset = VA.getLocMemOffset();
2473 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2474 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2475 if (Flags.isByVal())
2476 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2478 return DAG.getStore(Chain, dl, Arg, PtrOff,
2479 MachinePointerInfo::getStack(LocMemOffset),
2483 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2484 /// optimization is performed and it is required.
2486 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2487 SDValue &OutRetAddr, SDValue Chain,
2488 bool IsTailCall, bool Is64Bit,
2489 int FPDiff, SDLoc dl) const {
2490 // Adjust the Return address stack slot.
2491 EVT VT = getPointerTy();
2492 OutRetAddr = getReturnAddressFrameIndex(DAG);
2494 // Load the "old" Return address.
2495 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2496 false, false, false, 0);
2497 return SDValue(OutRetAddr.getNode(), 1);
2500 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2501 /// optimization is performed and it is required (FPDiff!=0).
2503 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2504 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2505 unsigned SlotSize, int FPDiff, SDLoc dl) {
2506 // Store the return address to the appropriate stack slot.
2507 if (!FPDiff) return Chain;
2508 // Calculate the new stack slot for the return address.
2509 int NewReturnAddrFI =
2510 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2512 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2513 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2514 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2520 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2521 SmallVectorImpl<SDValue> &InVals) const {
2522 SelectionDAG &DAG = CLI.DAG;
2524 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2525 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2526 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2527 SDValue Chain = CLI.Chain;
2528 SDValue Callee = CLI.Callee;
2529 CallingConv::ID CallConv = CLI.CallConv;
2530 bool &isTailCall = CLI.IsTailCall;
2531 bool isVarArg = CLI.IsVarArg;
2533 MachineFunction &MF = DAG.getMachineFunction();
2534 bool Is64Bit = Subtarget->is64Bit();
2535 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2536 StructReturnType SR = callIsStructReturn(Outs);
2537 bool IsSibcall = false;
2539 if (MF.getTarget().Options.DisableTailCalls)
2543 // Check if it's really possible to do a tail call.
2544 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2545 isVarArg, SR != NotStructReturn,
2546 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2547 Outs, OutVals, Ins, DAG);
2549 // Sibcalls are automatically detected tailcalls which do not require
2551 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2558 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2559 "Var args not supported with calling convention fastcc, ghc or hipe");
2561 // Analyze operands of the call, assigning locations to each operand.
2562 SmallVector<CCValAssign, 16> ArgLocs;
2563 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2564 ArgLocs, *DAG.getContext());
2566 // Allocate shadow area for Win64
2568 CCInfo.AllocateStack(32, 8);
2570 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2572 // Get a count of how many bytes are to be pushed on the stack.
2573 unsigned NumBytes = CCInfo.getNextStackOffset();
2575 // This is a sibcall. The memory operands are available in caller's
2576 // own caller's stack.
2578 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2579 IsTailCallConvention(CallConv))
2580 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2583 if (isTailCall && !IsSibcall) {
2584 // Lower arguments at fp - stackoffset + fpdiff.
2585 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2586 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2588 FPDiff = NumBytesCallerPushed - NumBytes;
2590 // Set the delta of movement of the returnaddr stackslot.
2591 // But only set if delta is greater than previous delta.
2592 if (FPDiff < X86Info->getTCReturnAddrDelta())
2593 X86Info->setTCReturnAddrDelta(FPDiff);
2596 unsigned NumBytesToPush = NumBytes;
2597 unsigned NumBytesToPop = NumBytes;
2599 // If we have an inalloca argument, all stack space has already been allocated
2600 // for us and be right at the top of the stack. We don't support multiple
2601 // arguments passed in memory when using inalloca.
2602 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2604 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2605 "an inalloca argument must be the only memory argument");
2609 Chain = DAG.getCALLSEQ_START(
2610 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2612 SDValue RetAddrFrIdx;
2613 // Load return address for tail calls.
2614 if (isTailCall && FPDiff)
2615 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2616 Is64Bit, FPDiff, dl);
2618 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2619 SmallVector<SDValue, 8> MemOpChains;
2622 // Walk the register/memloc assignments, inserting copies/loads. In the case
2623 // of tail call optimization arguments are handle later.
2624 const X86RegisterInfo *RegInfo =
2625 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2626 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2627 // Skip inalloca arguments, they have already been written.
2628 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2629 if (Flags.isInAlloca())
2632 CCValAssign &VA = ArgLocs[i];
2633 EVT RegVT = VA.getLocVT();
2634 SDValue Arg = OutVals[i];
2635 bool isByVal = Flags.isByVal();
2637 // Promote the value if needed.
2638 switch (VA.getLocInfo()) {
2639 default: llvm_unreachable("Unknown loc info!");
2640 case CCValAssign::Full: break;
2641 case CCValAssign::SExt:
2642 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2644 case CCValAssign::ZExt:
2645 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2647 case CCValAssign::AExt:
2648 if (RegVT.is128BitVector()) {
2649 // Special case: passing MMX values in XMM registers.
2650 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2651 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2652 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2654 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2656 case CCValAssign::BCvt:
2657 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2659 case CCValAssign::Indirect: {
2660 // Store the argument.
2661 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2662 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2663 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2664 MachinePointerInfo::getFixedStack(FI),
2671 if (VA.isRegLoc()) {
2672 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2673 if (isVarArg && IsWin64) {
2674 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2675 // shadow reg if callee is a varargs function.
2676 unsigned ShadowReg = 0;
2677 switch (VA.getLocReg()) {
2678 case X86::XMM0: ShadowReg = X86::RCX; break;
2679 case X86::XMM1: ShadowReg = X86::RDX; break;
2680 case X86::XMM2: ShadowReg = X86::R8; break;
2681 case X86::XMM3: ShadowReg = X86::R9; break;
2684 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2686 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2687 assert(VA.isMemLoc());
2688 if (StackPtr.getNode() == 0)
2689 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2691 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2692 dl, DAG, VA, Flags));
2696 if (!MemOpChains.empty())
2697 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2698 &MemOpChains[0], MemOpChains.size());
2700 if (Subtarget->isPICStyleGOT()) {
2701 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2704 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2705 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2707 // If we are tail calling and generating PIC/GOT style code load the
2708 // address of the callee into ECX. The value in ecx is used as target of
2709 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2710 // for tail calls on PIC/GOT architectures. Normally we would just put the
2711 // address of GOT into ebx and then call target@PLT. But for tail calls
2712 // ebx would be restored (since ebx is callee saved) before jumping to the
2715 // Note: The actual moving to ECX is done further down.
2716 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2717 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2718 !G->getGlobal()->hasProtectedVisibility())
2719 Callee = LowerGlobalAddress(Callee, DAG);
2720 else if (isa<ExternalSymbolSDNode>(Callee))
2721 Callee = LowerExternalSymbol(Callee, DAG);
2725 if (Is64Bit && isVarArg && !IsWin64) {
2726 // From AMD64 ABI document:
2727 // For calls that may call functions that use varargs or stdargs
2728 // (prototype-less calls or calls to functions containing ellipsis (...) in
2729 // the declaration) %al is used as hidden argument to specify the number
2730 // of SSE registers used. The contents of %al do not need to match exactly
2731 // the number of registers, but must be an ubound on the number of SSE
2732 // registers used and is in the range 0 - 8 inclusive.
2734 // Count the number of XMM registers allocated.
2735 static const MCPhysReg XMMArgRegs[] = {
2736 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2737 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2739 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2740 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2741 && "SSE registers cannot be used when SSE is disabled");
2743 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2744 DAG.getConstant(NumXMMRegs, MVT::i8)));
2747 // For tail calls lower the arguments to the 'real' stack slot.
2749 // Force all the incoming stack arguments to be loaded from the stack
2750 // before any new outgoing arguments are stored to the stack, because the
2751 // outgoing stack slots may alias the incoming argument stack slots, and
2752 // the alias isn't otherwise explicit. This is slightly more conservative
2753 // than necessary, because it means that each store effectively depends
2754 // on every argument instead of just those arguments it would clobber.
2755 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2757 SmallVector<SDValue, 8> MemOpChains2;
2760 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2761 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2762 CCValAssign &VA = ArgLocs[i];
2765 assert(VA.isMemLoc());
2766 SDValue Arg = OutVals[i];
2767 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2768 // Create frame index.
2769 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2770 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2771 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2772 FIN = DAG.getFrameIndex(FI, getPointerTy());
2774 if (Flags.isByVal()) {
2775 // Copy relative to framepointer.
2776 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2777 if (StackPtr.getNode() == 0)
2778 StackPtr = DAG.getCopyFromReg(Chain, dl,
2779 RegInfo->getStackRegister(),
2781 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2783 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2787 // Store relative to framepointer.
2788 MemOpChains2.push_back(
2789 DAG.getStore(ArgChain, dl, Arg, FIN,
2790 MachinePointerInfo::getFixedStack(FI),
2796 if (!MemOpChains2.empty())
2797 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2798 &MemOpChains2[0], MemOpChains2.size());
2800 // Store the return address to the appropriate stack slot.
2801 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2802 getPointerTy(), RegInfo->getSlotSize(),
2806 // Build a sequence of copy-to-reg nodes chained together with token chain
2807 // and flag operands which copy the outgoing args into registers.
2809 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2810 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2811 RegsToPass[i].second, InFlag);
2812 InFlag = Chain.getValue(1);
2815 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2816 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2817 // In the 64-bit large code model, we have to make all calls
2818 // through a register, since the call instruction's 32-bit
2819 // pc-relative offset may not be large enough to hold the whole
2821 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2822 // If the callee is a GlobalAddress node (quite common, every direct call
2823 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2826 // We should use extra load for direct calls to dllimported functions in
2828 const GlobalValue *GV = G->getGlobal();
2829 if (!GV->hasDLLImportStorageClass()) {
2830 unsigned char OpFlags = 0;
2831 bool ExtraLoad = false;
2832 unsigned WrapperKind = ISD::DELETED_NODE;
2834 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2835 // external symbols most go through the PLT in PIC mode. If the symbol
2836 // has hidden or protected visibility, or if it is static or local, then
2837 // we don't need to use the PLT - we can directly call it.
2838 if (Subtarget->isTargetELF() &&
2839 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2840 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2841 OpFlags = X86II::MO_PLT;
2842 } else if (Subtarget->isPICStyleStubAny() &&
2843 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2844 (!Subtarget->getTargetTriple().isMacOSX() ||
2845 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2846 // PC-relative references to external symbols should go through $stub,
2847 // unless we're building with the leopard linker or later, which
2848 // automatically synthesizes these stubs.
2849 OpFlags = X86II::MO_DARWIN_STUB;
2850 } else if (Subtarget->isPICStyleRIPRel() &&
2851 isa<Function>(GV) &&
2852 cast<Function>(GV)->getAttributes().
2853 hasAttribute(AttributeSet::FunctionIndex,
2854 Attribute::NonLazyBind)) {
2855 // If the function is marked as non-lazy, generate an indirect call
2856 // which loads from the GOT directly. This avoids runtime overhead
2857 // at the cost of eager binding (and one extra byte of encoding).
2858 OpFlags = X86II::MO_GOTPCREL;
2859 WrapperKind = X86ISD::WrapperRIP;
2863 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2864 G->getOffset(), OpFlags);
2866 // Add a wrapper if needed.
2867 if (WrapperKind != ISD::DELETED_NODE)
2868 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2869 // Add extra indirection if needed.
2871 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2872 MachinePointerInfo::getGOT(),
2873 false, false, false, 0);
2875 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2876 unsigned char OpFlags = 0;
2878 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2879 // external symbols should go through the PLT.
2880 if (Subtarget->isTargetELF() &&
2881 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2882 OpFlags = X86II::MO_PLT;
2883 } else if (Subtarget->isPICStyleStubAny() &&
2884 (!Subtarget->getTargetTriple().isMacOSX() ||
2885 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2886 // PC-relative references to external symbols should go through $stub,
2887 // unless we're building with the leopard linker or later, which
2888 // automatically synthesizes these stubs.
2889 OpFlags = X86II::MO_DARWIN_STUB;
2892 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2896 // Returns a chain & a flag for retval copy to use.
2897 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2898 SmallVector<SDValue, 8> Ops;
2900 if (!IsSibcall && isTailCall) {
2901 Chain = DAG.getCALLSEQ_END(Chain,
2902 DAG.getIntPtrConstant(NumBytesToPop, true),
2903 DAG.getIntPtrConstant(0, true), InFlag, dl);
2904 InFlag = Chain.getValue(1);
2907 Ops.push_back(Chain);
2908 Ops.push_back(Callee);
2911 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2913 // Add argument registers to the end of the list so that they are known live
2915 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2916 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2917 RegsToPass[i].second.getValueType()));
2919 // Add a register mask operand representing the call-preserved registers.
2920 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2921 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2922 assert(Mask && "Missing call preserved mask for calling convention");
2923 Ops.push_back(DAG.getRegisterMask(Mask));
2925 if (InFlag.getNode())
2926 Ops.push_back(InFlag);
2930 //// If this is the first return lowered for this function, add the regs
2931 //// to the liveout set for the function.
2932 // This isn't right, although it's probably harmless on x86; liveouts
2933 // should be computed from returns not tail calls. Consider a void
2934 // function making a tail call to a function returning int.
2935 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2938 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2939 InFlag = Chain.getValue(1);
2941 // Create the CALLSEQ_END node.
2942 unsigned NumBytesForCalleeToPop;
2943 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2944 getTargetMachine().Options.GuaranteedTailCallOpt))
2945 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2946 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2947 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2948 SR == StackStructReturn)
2949 // If this is a call to a struct-return function, the callee
2950 // pops the hidden struct pointer, so we have to push it back.
2951 // This is common for Darwin/X86, Linux & Mingw32 targets.
2952 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2953 NumBytesForCalleeToPop = 4;
2955 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2957 // Returns a flag for retval copy to use.
2959 Chain = DAG.getCALLSEQ_END(Chain,
2960 DAG.getIntPtrConstant(NumBytesToPop, true),
2961 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2964 InFlag = Chain.getValue(1);
2967 // Handle result values, copying them out of physregs into vregs that we
2969 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2970 Ins, dl, DAG, InVals);
2973 //===----------------------------------------------------------------------===//
2974 // Fast Calling Convention (tail call) implementation
2975 //===----------------------------------------------------------------------===//
2977 // Like std call, callee cleans arguments, convention except that ECX is
2978 // reserved for storing the tail called function address. Only 2 registers are
2979 // free for argument passing (inreg). Tail call optimization is performed
2981 // * tailcallopt is enabled
2982 // * caller/callee are fastcc
2983 // On X86_64 architecture with GOT-style position independent code only local
2984 // (within module) calls are supported at the moment.
2985 // To keep the stack aligned according to platform abi the function
2986 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2987 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2988 // If a tail called function callee has more arguments than the caller the
2989 // caller needs to make sure that there is room to move the RETADDR to. This is
2990 // achieved by reserving an area the size of the argument delta right after the
2991 // original REtADDR, but before the saved framepointer or the spilled registers
2992 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3004 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3005 /// for a 16 byte align requirement.
3007 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3008 SelectionDAG& DAG) const {
3009 MachineFunction &MF = DAG.getMachineFunction();
3010 const TargetMachine &TM = MF.getTarget();
3011 const X86RegisterInfo *RegInfo =
3012 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3013 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3014 unsigned StackAlignment = TFI.getStackAlignment();
3015 uint64_t AlignMask = StackAlignment - 1;
3016 int64_t Offset = StackSize;
3017 unsigned SlotSize = RegInfo->getSlotSize();
3018 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3019 // Number smaller than 12 so just add the difference.
3020 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3022 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3023 Offset = ((~AlignMask) & Offset) + StackAlignment +
3024 (StackAlignment-SlotSize);
3029 /// MatchingStackOffset - Return true if the given stack call argument is
3030 /// already available in the same position (relatively) of the caller's
3031 /// incoming argument stack.
3033 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3034 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3035 const X86InstrInfo *TII) {
3036 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3038 if (Arg.getOpcode() == ISD::CopyFromReg) {
3039 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3040 if (!TargetRegisterInfo::isVirtualRegister(VR))
3042 MachineInstr *Def = MRI->getVRegDef(VR);
3045 if (!Flags.isByVal()) {
3046 if (!TII->isLoadFromStackSlot(Def, FI))
3049 unsigned Opcode = Def->getOpcode();
3050 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3051 Def->getOperand(1).isFI()) {
3052 FI = Def->getOperand(1).getIndex();
3053 Bytes = Flags.getByValSize();
3057 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3058 if (Flags.isByVal())
3059 // ByVal argument is passed in as a pointer but it's now being
3060 // dereferenced. e.g.
3061 // define @foo(%struct.X* %A) {
3062 // tail call @bar(%struct.X* byval %A)
3065 SDValue Ptr = Ld->getBasePtr();
3066 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3069 FI = FINode->getIndex();
3070 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3071 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3072 FI = FINode->getIndex();
3073 Bytes = Flags.getByValSize();
3077 assert(FI != INT_MAX);
3078 if (!MFI->isFixedObjectIndex(FI))
3080 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3083 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3084 /// for tail call optimization. Targets which want to do tail call
3085 /// optimization should implement this function.
3087 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3088 CallingConv::ID CalleeCC,
3090 bool isCalleeStructRet,
3091 bool isCallerStructRet,
3093 const SmallVectorImpl<ISD::OutputArg> &Outs,
3094 const SmallVectorImpl<SDValue> &OutVals,
3095 const SmallVectorImpl<ISD::InputArg> &Ins,
3096 SelectionDAG &DAG) const {
3097 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3100 // If -tailcallopt is specified, make fastcc functions tail-callable.
3101 const MachineFunction &MF = DAG.getMachineFunction();
3102 const Function *CallerF = MF.getFunction();
3104 // If the function return type is x86_fp80 and the callee return type is not,
3105 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3106 // perform a tailcall optimization here.
3107 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3110 CallingConv::ID CallerCC = CallerF->getCallingConv();
3111 bool CCMatch = CallerCC == CalleeCC;
3112 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3113 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3115 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3116 if (IsTailCallConvention(CalleeCC) && CCMatch)
3121 // Look for obvious safe cases to perform tail call optimization that do not
3122 // require ABI changes. This is what gcc calls sibcall.
3124 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3125 // emit a special epilogue.
3126 const X86RegisterInfo *RegInfo =
3127 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3128 if (RegInfo->needsStackRealignment(MF))
3131 // Also avoid sibcall optimization if either caller or callee uses struct
3132 // return semantics.
3133 if (isCalleeStructRet || isCallerStructRet)
3136 // An stdcall/thiscall caller is expected to clean up its arguments; the
3137 // callee isn't going to do that.
3138 // FIXME: this is more restrictive than needed. We could produce a tailcall
3139 // when the stack adjustment matches. For example, with a thiscall that takes
3140 // only one argument.
3141 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3142 CallerCC == CallingConv::X86_ThisCall))
3145 // Do not sibcall optimize vararg calls unless all arguments are passed via
3147 if (isVarArg && !Outs.empty()) {
3149 // Optimizing for varargs on Win64 is unlikely to be safe without
3150 // additional testing.
3151 if (IsCalleeWin64 || IsCallerWin64)
3154 SmallVector<CCValAssign, 16> ArgLocs;
3155 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3156 getTargetMachine(), ArgLocs, *DAG.getContext());
3158 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3159 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3160 if (!ArgLocs[i].isRegLoc())
3164 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3165 // stack. Therefore, if it's not used by the call it is not safe to optimize
3166 // this into a sibcall.
3167 bool Unused = false;
3168 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3175 SmallVector<CCValAssign, 16> RVLocs;
3176 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3177 getTargetMachine(), RVLocs, *DAG.getContext());
3178 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3179 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3180 CCValAssign &VA = RVLocs[i];
3181 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3186 // If the calling conventions do not match, then we'd better make sure the
3187 // results are returned in the same way as what the caller expects.
3189 SmallVector<CCValAssign, 16> RVLocs1;
3190 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3191 getTargetMachine(), RVLocs1, *DAG.getContext());
3192 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3194 SmallVector<CCValAssign, 16> RVLocs2;
3195 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3196 getTargetMachine(), RVLocs2, *DAG.getContext());
3197 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3199 if (RVLocs1.size() != RVLocs2.size())
3201 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3202 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3204 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3206 if (RVLocs1[i].isRegLoc()) {
3207 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3210 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3216 // If the callee takes no arguments then go on to check the results of the
3218 if (!Outs.empty()) {
3219 // Check if stack adjustment is needed. For now, do not do this if any
3220 // argument is passed on the stack.
3221 SmallVector<CCValAssign, 16> ArgLocs;
3222 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3223 getTargetMachine(), ArgLocs, *DAG.getContext());
3225 // Allocate shadow area for Win64
3227 CCInfo.AllocateStack(32, 8);
3229 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3230 if (CCInfo.getNextStackOffset()) {
3231 MachineFunction &MF = DAG.getMachineFunction();
3232 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3235 // Check if the arguments are already laid out in the right way as
3236 // the caller's fixed stack objects.
3237 MachineFrameInfo *MFI = MF.getFrameInfo();
3238 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3239 const X86InstrInfo *TII =
3240 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3241 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3242 CCValAssign &VA = ArgLocs[i];
3243 SDValue Arg = OutVals[i];
3244 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3245 if (VA.getLocInfo() == CCValAssign::Indirect)
3247 if (!VA.isRegLoc()) {
3248 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3255 // If the tailcall address may be in a register, then make sure it's
3256 // possible to register allocate for it. In 32-bit, the call address can
3257 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3258 // callee-saved registers are restored. These happen to be the same
3259 // registers used to pass 'inreg' arguments so watch out for those.
3260 if (!Subtarget->is64Bit() &&
3261 ((!isa<GlobalAddressSDNode>(Callee) &&
3262 !isa<ExternalSymbolSDNode>(Callee)) ||
3263 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3264 unsigned NumInRegs = 0;
3265 // In PIC we need an extra register to formulate the address computation
3267 unsigned MaxInRegs =
3268 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3270 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3271 CCValAssign &VA = ArgLocs[i];
3274 unsigned Reg = VA.getLocReg();
3277 case X86::EAX: case X86::EDX: case X86::ECX:
3278 if (++NumInRegs == MaxInRegs)
3290 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3291 const TargetLibraryInfo *libInfo) const {
3292 return X86::createFastISel(funcInfo, libInfo);
3295 //===----------------------------------------------------------------------===//
3296 // Other Lowering Hooks
3297 //===----------------------------------------------------------------------===//
3299 static bool MayFoldLoad(SDValue Op) {
3300 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3303 static bool MayFoldIntoStore(SDValue Op) {
3304 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3307 static bool isTargetShuffle(unsigned Opcode) {
3309 default: return false;
3310 case X86ISD::PSHUFD:
3311 case X86ISD::PSHUFHW:
3312 case X86ISD::PSHUFLW:
3314 case X86ISD::PALIGNR:
3315 case X86ISD::MOVLHPS:
3316 case X86ISD::MOVLHPD:
3317 case X86ISD::MOVHLPS:
3318 case X86ISD::MOVLPS:
3319 case X86ISD::MOVLPD:
3320 case X86ISD::MOVSHDUP:
3321 case X86ISD::MOVSLDUP:
3322 case X86ISD::MOVDDUP:
3325 case X86ISD::UNPCKL:
3326 case X86ISD::UNPCKH:
3327 case X86ISD::VPERMILP:
3328 case X86ISD::VPERM2X128:
3329 case X86ISD::VPERMI:
3334 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3335 SDValue V1, SelectionDAG &DAG) {
3337 default: llvm_unreachable("Unknown x86 shuffle node");
3338 case X86ISD::MOVSHDUP:
3339 case X86ISD::MOVSLDUP:
3340 case X86ISD::MOVDDUP:
3341 return DAG.getNode(Opc, dl, VT, V1);
3345 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3346 SDValue V1, unsigned TargetMask,
3347 SelectionDAG &DAG) {
3349 default: llvm_unreachable("Unknown x86 shuffle node");
3350 case X86ISD::PSHUFD:
3351 case X86ISD::PSHUFHW:
3352 case X86ISD::PSHUFLW:
3353 case X86ISD::VPERMILP:
3354 case X86ISD::VPERMI:
3355 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3359 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3360 SDValue V1, SDValue V2, unsigned TargetMask,
3361 SelectionDAG &DAG) {
3363 default: llvm_unreachable("Unknown x86 shuffle node");
3364 case X86ISD::PALIGNR:
3366 case X86ISD::VPERM2X128:
3367 return DAG.getNode(Opc, dl, VT, V1, V2,
3368 DAG.getConstant(TargetMask, MVT::i8));
3372 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3373 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3375 default: llvm_unreachable("Unknown x86 shuffle node");
3376 case X86ISD::MOVLHPS:
3377 case X86ISD::MOVLHPD:
3378 case X86ISD::MOVHLPS:
3379 case X86ISD::MOVLPS:
3380 case X86ISD::MOVLPD:
3383 case X86ISD::UNPCKL:
3384 case X86ISD::UNPCKH:
3385 return DAG.getNode(Opc, dl, VT, V1, V2);
3389 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3390 MachineFunction &MF = DAG.getMachineFunction();
3391 const X86RegisterInfo *RegInfo =
3392 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3393 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3394 int ReturnAddrIndex = FuncInfo->getRAIndex();
3396 if (ReturnAddrIndex == 0) {
3397 // Set up a frame object for the return address.
3398 unsigned SlotSize = RegInfo->getSlotSize();
3399 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3402 FuncInfo->setRAIndex(ReturnAddrIndex);
3405 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3408 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3409 bool hasSymbolicDisplacement) {
3410 // Offset should fit into 32 bit immediate field.
3411 if (!isInt<32>(Offset))
3414 // If we don't have a symbolic displacement - we don't have any extra
3416 if (!hasSymbolicDisplacement)
3419 // FIXME: Some tweaks might be needed for medium code model.
3420 if (M != CodeModel::Small && M != CodeModel::Kernel)
3423 // For small code model we assume that latest object is 16MB before end of 31
3424 // bits boundary. We may also accept pretty large negative constants knowing
3425 // that all objects are in the positive half of address space.
3426 if (M == CodeModel::Small && Offset < 16*1024*1024)
3429 // For kernel code model we know that all object resist in the negative half
3430 // of 32bits address space. We may not accept negative offsets, since they may
3431 // be just off and we may accept pretty large positive ones.
3432 if (M == CodeModel::Kernel && Offset > 0)
3438 /// isCalleePop - Determines whether the callee is required to pop its
3439 /// own arguments. Callee pop is necessary to support tail calls.
3440 bool X86::isCalleePop(CallingConv::ID CallingConv,
3441 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3445 switch (CallingConv) {
3448 case CallingConv::X86_StdCall:
3450 case CallingConv::X86_FastCall:
3452 case CallingConv::X86_ThisCall:
3454 case CallingConv::Fast:
3456 case CallingConv::GHC:
3458 case CallingConv::HiPE:
3463 /// \brief Return true if the condition is an unsigned comparison operation.
3464 static bool isX86CCUnsigned(unsigned X86CC) {
3466 default: llvm_unreachable("Invalid integer condition!");
3467 case X86::COND_E: return true;
3468 case X86::COND_G: return false;
3469 case X86::COND_GE: return false;
3470 case X86::COND_L: return false;
3471 case X86::COND_LE: return false;
3472 case X86::COND_NE: return true;
3473 case X86::COND_B: return true;
3474 case X86::COND_A: return true;
3475 case X86::COND_BE: return true;
3476 case X86::COND_AE: return true;
3478 llvm_unreachable("covered switch fell through?!");
3481 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3482 /// specific condition code, returning the condition code and the LHS/RHS of the
3483 /// comparison to make.
3484 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3485 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3487 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3488 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3489 // X > -1 -> X == 0, jump !sign.
3490 RHS = DAG.getConstant(0, RHS.getValueType());
3491 return X86::COND_NS;
3493 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3494 // X < 0 -> X == 0, jump on sign.
3497 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3499 RHS = DAG.getConstant(0, RHS.getValueType());
3500 return X86::COND_LE;
3504 switch (SetCCOpcode) {
3505 default: llvm_unreachable("Invalid integer condition!");
3506 case ISD::SETEQ: return X86::COND_E;
3507 case ISD::SETGT: return X86::COND_G;
3508 case ISD::SETGE: return X86::COND_GE;
3509 case ISD::SETLT: return X86::COND_L;
3510 case ISD::SETLE: return X86::COND_LE;
3511 case ISD::SETNE: return X86::COND_NE;
3512 case ISD::SETULT: return X86::COND_B;
3513 case ISD::SETUGT: return X86::COND_A;
3514 case ISD::SETULE: return X86::COND_BE;
3515 case ISD::SETUGE: return X86::COND_AE;
3519 // First determine if it is required or is profitable to flip the operands.
3521 // If LHS is a foldable load, but RHS is not, flip the condition.
3522 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3523 !ISD::isNON_EXTLoad(RHS.getNode())) {
3524 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3525 std::swap(LHS, RHS);
3528 switch (SetCCOpcode) {
3534 std::swap(LHS, RHS);
3538 // On a floating point condition, the flags are set as follows:
3540 // 0 | 0 | 0 | X > Y
3541 // 0 | 0 | 1 | X < Y
3542 // 1 | 0 | 0 | X == Y
3543 // 1 | 1 | 1 | unordered
3544 switch (SetCCOpcode) {
3545 default: llvm_unreachable("Condcode should be pre-legalized away");
3547 case ISD::SETEQ: return X86::COND_E;
3548 case ISD::SETOLT: // flipped
3550 case ISD::SETGT: return X86::COND_A;
3551 case ISD::SETOLE: // flipped
3553 case ISD::SETGE: return X86::COND_AE;
3554 case ISD::SETUGT: // flipped
3556 case ISD::SETLT: return X86::COND_B;
3557 case ISD::SETUGE: // flipped
3559 case ISD::SETLE: return X86::COND_BE;
3561 case ISD::SETNE: return X86::COND_NE;
3562 case ISD::SETUO: return X86::COND_P;
3563 case ISD::SETO: return X86::COND_NP;
3565 case ISD::SETUNE: return X86::COND_INVALID;
3569 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3570 /// code. Current x86 isa includes the following FP cmov instructions:
3571 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3572 static bool hasFPCMov(unsigned X86CC) {
3588 /// isFPImmLegal - Returns true if the target can instruction select the
3589 /// specified FP immediate natively. If false, the legalizer will
3590 /// materialize the FP immediate as a load from a constant pool.
3591 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3592 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3593 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3599 /// \brief Returns true if it is beneficial to convert a load of a constant
3600 /// to just the constant itself.
3601 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3603 assert(Ty->isIntegerTy());
3605 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3606 if (BitSize == 0 || BitSize > 64)
3611 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3612 /// the specified range (L, H].
3613 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3614 return (Val < 0) || (Val >= Low && Val < Hi);
3617 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3618 /// specified value.
3619 static bool isUndefOrEqual(int Val, int CmpVal) {
3620 return (Val < 0 || Val == CmpVal);
3623 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3624 /// from position Pos and ending in Pos+Size, falls within the specified
3625 /// sequential range (L, L+Pos]. or is undef.
3626 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3627 unsigned Pos, unsigned Size, int Low) {
3628 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3629 if (!isUndefOrEqual(Mask[i], Low))
3634 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3635 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3636 /// the second operand.
3637 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3638 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3639 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3640 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3641 return (Mask[0] < 2 && Mask[1] < 2);
3645 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3646 /// is suitable for input to PSHUFHW.
3647 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3648 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3651 // Lower quadword copied in order or undef.
3652 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3655 // Upper quadword shuffled.
3656 for (unsigned i = 4; i != 8; ++i)
3657 if (!isUndefOrInRange(Mask[i], 4, 8))
3660 if (VT == MVT::v16i16) {
3661 // Lower quadword copied in order or undef.
3662 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3665 // Upper quadword shuffled.
3666 for (unsigned i = 12; i != 16; ++i)
3667 if (!isUndefOrInRange(Mask[i], 12, 16))
3674 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3675 /// is suitable for input to PSHUFLW.
3676 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3677 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3680 // Upper quadword copied in order.
3681 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3684 // Lower quadword shuffled.
3685 for (unsigned i = 0; i != 4; ++i)
3686 if (!isUndefOrInRange(Mask[i], 0, 4))
3689 if (VT == MVT::v16i16) {
3690 // Upper quadword copied in order.
3691 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3694 // Lower quadword shuffled.
3695 for (unsigned i = 8; i != 12; ++i)
3696 if (!isUndefOrInRange(Mask[i], 8, 12))
3703 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3704 /// is suitable for input to PALIGNR.
3705 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3706 const X86Subtarget *Subtarget) {
3707 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3708 (VT.is256BitVector() && !Subtarget->hasInt256()))
3711 unsigned NumElts = VT.getVectorNumElements();
3712 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3713 unsigned NumLaneElts = NumElts/NumLanes;
3715 // Do not handle 64-bit element shuffles with palignr.
3716 if (NumLaneElts == 2)
3719 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3721 for (i = 0; i != NumLaneElts; ++i) {
3726 // Lane is all undef, go to next lane
3727 if (i == NumLaneElts)
3730 int Start = Mask[i+l];
3732 // Make sure its in this lane in one of the sources
3733 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3734 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3737 // If not lane 0, then we must match lane 0
3738 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3741 // Correct second source to be contiguous with first source
3742 if (Start >= (int)NumElts)
3743 Start -= NumElts - NumLaneElts;
3745 // Make sure we're shifting in the right direction.
3746 if (Start <= (int)(i+l))
3751 // Check the rest of the elements to see if they are consecutive.
3752 for (++i; i != NumLaneElts; ++i) {
3753 int Idx = Mask[i+l];
3755 // Make sure its in this lane
3756 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3757 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3760 // If not lane 0, then we must match lane 0
3761 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3764 if (Idx >= (int)NumElts)
3765 Idx -= NumElts - NumLaneElts;
3767 if (!isUndefOrEqual(Idx, Start+i))
3776 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3777 /// the two vector operands have swapped position.
3778 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3779 unsigned NumElems) {
3780 for (unsigned i = 0; i != NumElems; ++i) {
3784 else if (idx < (int)NumElems)
3785 Mask[i] = idx + NumElems;
3787 Mask[i] = idx - NumElems;
3791 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3792 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3793 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3794 /// reverse of what x86 shuffles want.
3795 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3797 unsigned NumElems = VT.getVectorNumElements();
3798 unsigned NumLanes = VT.getSizeInBits()/128;
3799 unsigned NumLaneElems = NumElems/NumLanes;
3801 if (NumLaneElems != 2 && NumLaneElems != 4)
3804 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3805 bool symetricMaskRequired =
3806 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3808 // VSHUFPSY divides the resulting vector into 4 chunks.
3809 // The sources are also splitted into 4 chunks, and each destination
3810 // chunk must come from a different source chunk.
3812 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3813 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3815 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3816 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3818 // VSHUFPDY divides the resulting vector into 4 chunks.
3819 // The sources are also splitted into 4 chunks, and each destination
3820 // chunk must come from a different source chunk.
3822 // SRC1 => X3 X2 X1 X0
3823 // SRC2 => Y3 Y2 Y1 Y0
3825 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3827 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3828 unsigned HalfLaneElems = NumLaneElems/2;
3829 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3830 for (unsigned i = 0; i != NumLaneElems; ++i) {
3831 int Idx = Mask[i+l];
3832 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3833 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3835 // For VSHUFPSY, the mask of the second half must be the same as the
3836 // first but with the appropriate offsets. This works in the same way as
3837 // VPERMILPS works with masks.
3838 if (!symetricMaskRequired || Idx < 0)
3840 if (MaskVal[i] < 0) {
3841 MaskVal[i] = Idx - l;
3844 if ((signed)(Idx - l) != MaskVal[i])
3852 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3853 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3854 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3855 if (!VT.is128BitVector())
3858 unsigned NumElems = VT.getVectorNumElements();
3863 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3864 return isUndefOrEqual(Mask[0], 6) &&
3865 isUndefOrEqual(Mask[1], 7) &&
3866 isUndefOrEqual(Mask[2], 2) &&
3867 isUndefOrEqual(Mask[3], 3);
3870 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3871 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3873 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3874 if (!VT.is128BitVector())
3877 unsigned NumElems = VT.getVectorNumElements();
3882 return isUndefOrEqual(Mask[0], 2) &&
3883 isUndefOrEqual(Mask[1], 3) &&
3884 isUndefOrEqual(Mask[2], 2) &&
3885 isUndefOrEqual(Mask[3], 3);
3888 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3889 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3890 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3891 if (!VT.is128BitVector())
3894 unsigned NumElems = VT.getVectorNumElements();
3896 if (NumElems != 2 && NumElems != 4)
3899 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3900 if (!isUndefOrEqual(Mask[i], i + NumElems))
3903 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3904 if (!isUndefOrEqual(Mask[i], i))
3910 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3912 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3913 if (!VT.is128BitVector())
3916 unsigned NumElems = VT.getVectorNumElements();
3918 if (NumElems != 2 && NumElems != 4)
3921 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3922 if (!isUndefOrEqual(Mask[i], i))
3925 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3926 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3933 // Some special combinations that can be optimized.
3936 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3937 SelectionDAG &DAG) {
3938 MVT VT = SVOp->getSimpleValueType(0);
3941 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3944 ArrayRef<int> Mask = SVOp->getMask();
3946 // These are the special masks that may be optimized.
3947 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3948 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3949 bool MatchEvenMask = true;
3950 bool MatchOddMask = true;
3951 for (int i=0; i<8; ++i) {
3952 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3953 MatchEvenMask = false;
3954 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3955 MatchOddMask = false;
3958 if (!MatchEvenMask && !MatchOddMask)
3961 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3963 SDValue Op0 = SVOp->getOperand(0);
3964 SDValue Op1 = SVOp->getOperand(1);
3966 if (MatchEvenMask) {
3967 // Shift the second operand right to 32 bits.
3968 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3969 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3971 // Shift the first operand left to 32 bits.
3972 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3973 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3975 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3976 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3979 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3980 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3981 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3982 bool HasInt256, bool V2IsSplat = false) {
3984 assert(VT.getSizeInBits() >= 128 &&
3985 "Unsupported vector type for unpckl");
3987 // AVX defines UNPCK* to operate independently on 128-bit lanes.
3989 unsigned NumOf256BitLanes;
3990 unsigned NumElts = VT.getVectorNumElements();
3991 if (VT.is256BitVector()) {
3992 if (NumElts != 4 && NumElts != 8 &&
3993 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3996 NumOf256BitLanes = 1;
3997 } else if (VT.is512BitVector()) {
3998 assert(VT.getScalarType().getSizeInBits() >= 32 &&
3999 "Unsupported vector type for unpckh");
4001 NumOf256BitLanes = 2;
4004 NumOf256BitLanes = 1;
4007 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4008 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4010 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4011 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4012 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4013 int BitI = Mask[l256*NumEltsInStride+l+i];
4014 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4015 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4017 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4019 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4027 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4028 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4029 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4030 bool HasInt256, bool V2IsSplat = false) {
4031 assert(VT.getSizeInBits() >= 128 &&
4032 "Unsupported vector type for unpckh");
4034 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4036 unsigned NumOf256BitLanes;
4037 unsigned NumElts = VT.getVectorNumElements();
4038 if (VT.is256BitVector()) {
4039 if (NumElts != 4 && NumElts != 8 &&
4040 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4043 NumOf256BitLanes = 1;
4044 } else if (VT.is512BitVector()) {
4045 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4046 "Unsupported vector type for unpckh");
4048 NumOf256BitLanes = 2;
4051 NumOf256BitLanes = 1;
4054 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4055 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4057 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4058 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4059 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4060 int BitI = Mask[l256*NumEltsInStride+l+i];
4061 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4062 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4064 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4066 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4074 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4075 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4077 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4078 unsigned NumElts = VT.getVectorNumElements();
4079 bool Is256BitVec = VT.is256BitVector();
4081 if (VT.is512BitVector())
4083 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4084 "Unsupported vector type for unpckh");
4086 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4087 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4090 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4091 // FIXME: Need a better way to get rid of this, there's no latency difference
4092 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4093 // the former later. We should also remove the "_undef" special mask.
4094 if (NumElts == 4 && Is256BitVec)
4097 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4098 // independently on 128-bit lanes.
4099 unsigned NumLanes = VT.getSizeInBits()/128;
4100 unsigned NumLaneElts = NumElts/NumLanes;
4102 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4103 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4104 int BitI = Mask[l+i];
4105 int BitI1 = Mask[l+i+1];
4107 if (!isUndefOrEqual(BitI, j))
4109 if (!isUndefOrEqual(BitI1, j))
4117 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4118 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4120 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4121 unsigned NumElts = VT.getVectorNumElements();
4123 if (VT.is512BitVector())
4126 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4127 "Unsupported vector type for unpckh");
4129 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4130 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4133 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4134 // independently on 128-bit lanes.
4135 unsigned NumLanes = VT.getSizeInBits()/128;
4136 unsigned NumLaneElts = NumElts/NumLanes;
4138 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4139 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4140 int BitI = Mask[l+i];
4141 int BitI1 = Mask[l+i+1];
4142 if (!isUndefOrEqual(BitI, j))
4144 if (!isUndefOrEqual(BitI1, j))
4151 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4152 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4153 /// MOVSD, and MOVD, i.e. setting the lowest element.
4154 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4155 if (VT.getVectorElementType().getSizeInBits() < 32)
4157 if (!VT.is128BitVector())
4160 unsigned NumElts = VT.getVectorNumElements();
4162 if (!isUndefOrEqual(Mask[0], NumElts))
4165 for (unsigned i = 1; i != NumElts; ++i)
4166 if (!isUndefOrEqual(Mask[i], i))
4172 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4173 /// as permutations between 128-bit chunks or halves. As an example: this
4175 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4176 /// The first half comes from the second half of V1 and the second half from the
4177 /// the second half of V2.
4178 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4179 if (!HasFp256 || !VT.is256BitVector())
4182 // The shuffle result is divided into half A and half B. In total the two
4183 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4184 // B must come from C, D, E or F.
4185 unsigned HalfSize = VT.getVectorNumElements()/2;
4186 bool MatchA = false, MatchB = false;
4188 // Check if A comes from one of C, D, E, F.
4189 for (unsigned Half = 0; Half != 4; ++Half) {
4190 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4196 // Check if B comes from one of C, D, E, F.
4197 for (unsigned Half = 0; Half != 4; ++Half) {
4198 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4204 return MatchA && MatchB;
4207 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4208 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4209 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4210 MVT VT = SVOp->getSimpleValueType(0);
4212 unsigned HalfSize = VT.getVectorNumElements()/2;
4214 unsigned FstHalf = 0, SndHalf = 0;
4215 for (unsigned i = 0; i < HalfSize; ++i) {
4216 if (SVOp->getMaskElt(i) > 0) {
4217 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4221 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4222 if (SVOp->getMaskElt(i) > 0) {
4223 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4228 return (FstHalf | (SndHalf << 4));
4231 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4232 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4233 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4237 unsigned NumElts = VT.getVectorNumElements();
4239 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4240 for (unsigned i = 0; i != NumElts; ++i) {
4243 Imm8 |= Mask[i] << (i*2);
4248 unsigned LaneSize = 4;
4249 SmallVector<int, 4> MaskVal(LaneSize, -1);
4251 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4252 for (unsigned i = 0; i != LaneSize; ++i) {
4253 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4257 if (MaskVal[i] < 0) {
4258 MaskVal[i] = Mask[i+l] - l;
4259 Imm8 |= MaskVal[i] << (i*2);
4262 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4269 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4270 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4271 /// Note that VPERMIL mask matching is different depending whether theunderlying
4272 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4273 /// to the same elements of the low, but to the higher half of the source.
4274 /// In VPERMILPD the two lanes could be shuffled independently of each other
4275 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4276 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4277 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4278 if (VT.getSizeInBits() < 256 || EltSize < 32)
4280 bool symetricMaskRequired = (EltSize == 32);
4281 unsigned NumElts = VT.getVectorNumElements();
4283 unsigned NumLanes = VT.getSizeInBits()/128;
4284 unsigned LaneSize = NumElts/NumLanes;
4285 // 2 or 4 elements in one lane
4287 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4288 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4289 for (unsigned i = 0; i != LaneSize; ++i) {
4290 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4292 if (symetricMaskRequired) {
4293 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4294 ExpectedMaskVal[i] = Mask[i+l] - l;
4297 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4305 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4306 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4307 /// element of vector 2 and the other elements to come from vector 1 in order.
4308 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4309 bool V2IsSplat = false, bool V2IsUndef = false) {
4310 if (!VT.is128BitVector())
4313 unsigned NumOps = VT.getVectorNumElements();
4314 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4317 if (!isUndefOrEqual(Mask[0], 0))
4320 for (unsigned i = 1; i != NumOps; ++i)
4321 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4322 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4323 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4329 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4330 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4331 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4332 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4333 const X86Subtarget *Subtarget) {
4334 if (!Subtarget->hasSSE3())
4337 unsigned NumElems = VT.getVectorNumElements();
4339 if ((VT.is128BitVector() && NumElems != 4) ||
4340 (VT.is256BitVector() && NumElems != 8) ||
4341 (VT.is512BitVector() && NumElems != 16))
4344 // "i+1" is the value the indexed mask element must have
4345 for (unsigned i = 0; i != NumElems; i += 2)
4346 if (!isUndefOrEqual(Mask[i], i+1) ||
4347 !isUndefOrEqual(Mask[i+1], i+1))
4353 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4354 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4355 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4356 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4357 const X86Subtarget *Subtarget) {
4358 if (!Subtarget->hasSSE3())
4361 unsigned NumElems = VT.getVectorNumElements();
4363 if ((VT.is128BitVector() && NumElems != 4) ||
4364 (VT.is256BitVector() && NumElems != 8) ||
4365 (VT.is512BitVector() && NumElems != 16))
4368 // "i" is the value the indexed mask element must have
4369 for (unsigned i = 0; i != NumElems; i += 2)
4370 if (!isUndefOrEqual(Mask[i], i) ||
4371 !isUndefOrEqual(Mask[i+1], i))
4377 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4378 /// specifies a shuffle of elements that is suitable for input to 256-bit
4379 /// version of MOVDDUP.
4380 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4381 if (!HasFp256 || !VT.is256BitVector())
4384 unsigned NumElts = VT.getVectorNumElements();
4388 for (unsigned i = 0; i != NumElts/2; ++i)
4389 if (!isUndefOrEqual(Mask[i], 0))
4391 for (unsigned i = NumElts/2; i != NumElts; ++i)
4392 if (!isUndefOrEqual(Mask[i], NumElts/2))
4397 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4398 /// specifies a shuffle of elements that is suitable for input to 128-bit
4399 /// version of MOVDDUP.
4400 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4401 if (!VT.is128BitVector())
4404 unsigned e = VT.getVectorNumElements() / 2;
4405 for (unsigned i = 0; i != e; ++i)
4406 if (!isUndefOrEqual(Mask[i], i))
4408 for (unsigned i = 0; i != e; ++i)
4409 if (!isUndefOrEqual(Mask[e+i], i))
4414 /// isVEXTRACTIndex - Return true if the specified
4415 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4416 /// suitable for instruction that extract 128 or 256 bit vectors
4417 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4418 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4419 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4422 // The index should be aligned on a vecWidth-bit boundary.
4424 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4426 MVT VT = N->getSimpleValueType(0);
4427 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4428 bool Result = (Index * ElSize) % vecWidth == 0;
4433 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4434 /// operand specifies a subvector insert that is suitable for input to
4435 /// insertion of 128 or 256-bit subvectors
4436 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4437 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4438 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4440 // The index should be aligned on a vecWidth-bit boundary.
4442 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4444 MVT VT = N->getSimpleValueType(0);
4445 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4446 bool Result = (Index * ElSize) % vecWidth == 0;
4451 bool X86::isVINSERT128Index(SDNode *N) {
4452 return isVINSERTIndex(N, 128);
4455 bool X86::isVINSERT256Index(SDNode *N) {
4456 return isVINSERTIndex(N, 256);
4459 bool X86::isVEXTRACT128Index(SDNode *N) {
4460 return isVEXTRACTIndex(N, 128);
4463 bool X86::isVEXTRACT256Index(SDNode *N) {
4464 return isVEXTRACTIndex(N, 256);
4467 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4468 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4469 /// Handles 128-bit and 256-bit.
4470 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4471 MVT VT = N->getSimpleValueType(0);
4473 assert((VT.getSizeInBits() >= 128) &&
4474 "Unsupported vector type for PSHUF/SHUFP");
4476 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4477 // independently on 128-bit lanes.
4478 unsigned NumElts = VT.getVectorNumElements();
4479 unsigned NumLanes = VT.getSizeInBits()/128;
4480 unsigned NumLaneElts = NumElts/NumLanes;
4482 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4483 "Only supports 2, 4 or 8 elements per lane");
4485 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4487 for (unsigned i = 0; i != NumElts; ++i) {
4488 int Elt = N->getMaskElt(i);
4489 if (Elt < 0) continue;
4490 Elt &= NumLaneElts - 1;
4491 unsigned ShAmt = (i << Shift) % 8;
4492 Mask |= Elt << ShAmt;
4498 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4499 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4500 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4501 MVT VT = N->getSimpleValueType(0);
4503 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4504 "Unsupported vector type for PSHUFHW");
4506 unsigned NumElts = VT.getVectorNumElements();
4509 for (unsigned l = 0; l != NumElts; l += 8) {
4510 // 8 nodes per lane, but we only care about the last 4.
4511 for (unsigned i = 0; i < 4; ++i) {
4512 int Elt = N->getMaskElt(l+i+4);
4513 if (Elt < 0) continue;
4514 Elt &= 0x3; // only 2-bits.
4515 Mask |= Elt << (i * 2);
4522 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4523 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4524 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4525 MVT VT = N->getSimpleValueType(0);
4527 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4528 "Unsupported vector type for PSHUFHW");
4530 unsigned NumElts = VT.getVectorNumElements();
4533 for (unsigned l = 0; l != NumElts; l += 8) {
4534 // 8 nodes per lane, but we only care about the first 4.
4535 for (unsigned i = 0; i < 4; ++i) {
4536 int Elt = N->getMaskElt(l+i);
4537 if (Elt < 0) continue;
4538 Elt &= 0x3; // only 2-bits
4539 Mask |= Elt << (i * 2);
4546 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4547 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4548 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4549 MVT VT = SVOp->getSimpleValueType(0);
4550 unsigned EltSize = VT.is512BitVector() ? 1 :
4551 VT.getVectorElementType().getSizeInBits() >> 3;
4553 unsigned NumElts = VT.getVectorNumElements();
4554 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4555 unsigned NumLaneElts = NumElts/NumLanes;
4559 for (i = 0; i != NumElts; ++i) {
4560 Val = SVOp->getMaskElt(i);
4564 if (Val >= (int)NumElts)
4565 Val -= NumElts - NumLaneElts;
4567 assert(Val - i > 0 && "PALIGNR imm should be positive");
4568 return (Val - i) * EltSize;
4571 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4572 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4573 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4574 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4577 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4579 MVT VecVT = N->getOperand(0).getSimpleValueType();
4580 MVT ElVT = VecVT.getVectorElementType();
4582 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4583 return Index / NumElemsPerChunk;
4586 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4587 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4588 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4589 llvm_unreachable("Illegal insert subvector for VINSERT");
4592 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4594 MVT VecVT = N->getSimpleValueType(0);
4595 MVT ElVT = VecVT.getVectorElementType();
4597 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4598 return Index / NumElemsPerChunk;
4601 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4602 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4603 /// and VINSERTI128 instructions.
4604 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4605 return getExtractVEXTRACTImmediate(N, 128);
4608 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4609 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4610 /// and VINSERTI64x4 instructions.
4611 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4612 return getExtractVEXTRACTImmediate(N, 256);
4615 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4616 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4617 /// and VINSERTI128 instructions.
4618 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4619 return getInsertVINSERTImmediate(N, 128);
4622 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4623 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4624 /// and VINSERTI64x4 instructions.
4625 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4626 return getInsertVINSERTImmediate(N, 256);
4629 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4631 bool X86::isZeroNode(SDValue Elt) {
4632 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4633 return CN->isNullValue();
4634 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4635 return CFP->getValueAPF().isPosZero();
4639 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4640 /// their permute mask.
4641 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4642 SelectionDAG &DAG) {
4643 MVT VT = SVOp->getSimpleValueType(0);
4644 unsigned NumElems = VT.getVectorNumElements();
4645 SmallVector<int, 8> MaskVec;
4647 for (unsigned i = 0; i != NumElems; ++i) {
4648 int Idx = SVOp->getMaskElt(i);
4650 if (Idx < (int)NumElems)
4655 MaskVec.push_back(Idx);
4657 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4658 SVOp->getOperand(0), &MaskVec[0]);
4661 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4662 /// match movhlps. The lower half elements should come from upper half of
4663 /// V1 (and in order), and the upper half elements should come from the upper
4664 /// half of V2 (and in order).
4665 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4666 if (!VT.is128BitVector())
4668 if (VT.getVectorNumElements() != 4)
4670 for (unsigned i = 0, e = 2; i != e; ++i)
4671 if (!isUndefOrEqual(Mask[i], i+2))
4673 for (unsigned i = 2; i != 4; ++i)
4674 if (!isUndefOrEqual(Mask[i], i+4))
4679 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4680 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4682 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4683 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4685 N = N->getOperand(0).getNode();
4686 if (!ISD::isNON_EXTLoad(N))
4689 *LD = cast<LoadSDNode>(N);
4693 // Test whether the given value is a vector value which will be legalized
4695 static bool WillBeConstantPoolLoad(SDNode *N) {
4696 if (N->getOpcode() != ISD::BUILD_VECTOR)
4699 // Check for any non-constant elements.
4700 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4701 switch (N->getOperand(i).getNode()->getOpcode()) {
4703 case ISD::ConstantFP:
4710 // Vectors of all-zeros and all-ones are materialized with special
4711 // instructions rather than being loaded.
4712 return !ISD::isBuildVectorAllZeros(N) &&
4713 !ISD::isBuildVectorAllOnes(N);
4716 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4717 /// match movlp{s|d}. The lower half elements should come from lower half of
4718 /// V1 (and in order), and the upper half elements should come from the upper
4719 /// half of V2 (and in order). And since V1 will become the source of the
4720 /// MOVLP, it must be either a vector load or a scalar load to vector.
4721 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4722 ArrayRef<int> Mask, MVT VT) {
4723 if (!VT.is128BitVector())
4726 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4728 // Is V2 is a vector load, don't do this transformation. We will try to use
4729 // load folding shufps op.
4730 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4733 unsigned NumElems = VT.getVectorNumElements();
4735 if (NumElems != 2 && NumElems != 4)
4737 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4738 if (!isUndefOrEqual(Mask[i], i))
4740 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4741 if (!isUndefOrEqual(Mask[i], i+NumElems))
4746 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4748 static bool isSplatVector(SDNode *N) {
4749 if (N->getOpcode() != ISD::BUILD_VECTOR)
4752 SDValue SplatValue = N->getOperand(0);
4753 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4754 if (N->getOperand(i) != SplatValue)
4759 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4760 /// to an zero vector.
4761 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4762 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4763 SDValue V1 = N->getOperand(0);
4764 SDValue V2 = N->getOperand(1);
4765 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4766 for (unsigned i = 0; i != NumElems; ++i) {
4767 int Idx = N->getMaskElt(i);
4768 if (Idx >= (int)NumElems) {
4769 unsigned Opc = V2.getOpcode();
4770 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4772 if (Opc != ISD::BUILD_VECTOR ||
4773 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4775 } else if (Idx >= 0) {
4776 unsigned Opc = V1.getOpcode();
4777 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4779 if (Opc != ISD::BUILD_VECTOR ||
4780 !X86::isZeroNode(V1.getOperand(Idx)))
4787 /// getZeroVector - Returns a vector of specified type with all zero elements.
4789 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4790 SelectionDAG &DAG, SDLoc dl) {
4791 assert(VT.isVector() && "Expected a vector type");
4793 // Always build SSE zero vectors as <4 x i32> bitcasted
4794 // to their dest type. This ensures they get CSE'd.
4796 if (VT.is128BitVector()) { // SSE
4797 if (Subtarget->hasSSE2()) { // SSE2
4798 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4799 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4801 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4802 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4804 } else if (VT.is256BitVector()) { // AVX
4805 if (Subtarget->hasInt256()) { // AVX2
4806 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4807 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4808 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4809 array_lengthof(Ops));
4811 // 256-bit logic and arithmetic instructions in AVX are all
4812 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4813 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4814 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4815 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4816 array_lengthof(Ops));
4818 } else if (VT.is512BitVector()) { // AVX-512
4819 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4820 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4821 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4822 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4823 } else if (VT.getScalarType() == MVT::i1) {
4824 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4825 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4826 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4827 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4828 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4829 Ops, VT.getVectorNumElements());
4831 llvm_unreachable("Unexpected vector type");
4833 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4836 /// getOnesVector - Returns a vector of specified type with all bits set.
4837 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4838 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4839 /// Then bitcast to their original type, ensuring they get CSE'd.
4840 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4842 assert(VT.isVector() && "Expected a vector type");
4844 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4846 if (VT.is256BitVector()) {
4847 if (HasInt256) { // AVX2
4848 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4849 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4850 array_lengthof(Ops));
4852 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4853 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4855 } else if (VT.is128BitVector()) {
4856 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4858 llvm_unreachable("Unexpected vector type");
4860 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4863 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4864 /// that point to V2 points to its first element.
4865 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4866 for (unsigned i = 0; i != NumElems; ++i) {
4867 if (Mask[i] > (int)NumElems) {
4873 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4874 /// operation of specified width.
4875 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4877 unsigned NumElems = VT.getVectorNumElements();
4878 SmallVector<int, 8> Mask;
4879 Mask.push_back(NumElems);
4880 for (unsigned i = 1; i != NumElems; ++i)
4882 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4885 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4886 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4888 unsigned NumElems = VT.getVectorNumElements();
4889 SmallVector<int, 8> Mask;
4890 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4892 Mask.push_back(i + NumElems);
4894 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4897 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4898 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4900 unsigned NumElems = VT.getVectorNumElements();
4901 SmallVector<int, 8> Mask;
4902 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4903 Mask.push_back(i + Half);
4904 Mask.push_back(i + NumElems + Half);
4906 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4909 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4910 // a generic shuffle instruction because the target has no such instructions.
4911 // Generate shuffles which repeat i16 and i8 several times until they can be
4912 // represented by v4f32 and then be manipulated by target suported shuffles.
4913 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4914 MVT VT = V.getSimpleValueType();
4915 int NumElems = VT.getVectorNumElements();
4918 while (NumElems > 4) {
4919 if (EltNo < NumElems/2) {
4920 V = getUnpackl(DAG, dl, VT, V, V);
4922 V = getUnpackh(DAG, dl, VT, V, V);
4923 EltNo -= NumElems/2;
4930 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4931 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4932 MVT VT = V.getSimpleValueType();
4935 if (VT.is128BitVector()) {
4936 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4937 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4938 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4940 } else if (VT.is256BitVector()) {
4941 // To use VPERMILPS to splat scalars, the second half of indicies must
4942 // refer to the higher part, which is a duplication of the lower one,
4943 // because VPERMILPS can only handle in-lane permutations.
4944 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4945 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4947 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4948 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4951 llvm_unreachable("Vector size not supported");
4953 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4956 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4957 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4958 MVT SrcVT = SV->getSimpleValueType(0);
4959 SDValue V1 = SV->getOperand(0);
4962 int EltNo = SV->getSplatIndex();
4963 int NumElems = SrcVT.getVectorNumElements();
4964 bool Is256BitVec = SrcVT.is256BitVector();
4966 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4967 "Unknown how to promote splat for type");
4969 // Extract the 128-bit part containing the splat element and update
4970 // the splat element index when it refers to the higher register.
4972 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4973 if (EltNo >= NumElems/2)
4974 EltNo -= NumElems/2;
4977 // All i16 and i8 vector types can't be used directly by a generic shuffle
4978 // instruction because the target has no such instruction. Generate shuffles
4979 // which repeat i16 and i8 several times until they fit in i32, and then can
4980 // be manipulated by target suported shuffles.
4981 MVT EltVT = SrcVT.getVectorElementType();
4982 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4983 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4985 // Recreate the 256-bit vector and place the same 128-bit vector
4986 // into the low and high part. This is necessary because we want
4987 // to use VPERM* to shuffle the vectors
4989 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4992 return getLegalSplat(DAG, V1, EltNo);
4995 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4996 /// vector of zero or undef vector. This produces a shuffle where the low
4997 /// element of V2 is swizzled into the zero/undef vector, landing at element
4998 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4999 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5001 const X86Subtarget *Subtarget,
5002 SelectionDAG &DAG) {
5003 MVT VT = V2.getSimpleValueType();
5005 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5006 unsigned NumElems = VT.getVectorNumElements();
5007 SmallVector<int, 16> MaskVec;
5008 for (unsigned i = 0; i != NumElems; ++i)
5009 // If this is the insertion idx, put the low elt of V2 here.
5010 MaskVec.push_back(i == Idx ? NumElems : i);
5011 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5014 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5015 /// target specific opcode. Returns true if the Mask could be calculated.
5016 /// Sets IsUnary to true if only uses one source.
5017 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5018 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5019 unsigned NumElems = VT.getVectorNumElements();
5023 switch(N->getOpcode()) {
5025 ImmN = N->getOperand(N->getNumOperands()-1);
5026 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5028 case X86ISD::UNPCKH:
5029 DecodeUNPCKHMask(VT, Mask);
5031 case X86ISD::UNPCKL:
5032 DecodeUNPCKLMask(VT, Mask);
5034 case X86ISD::MOVHLPS:
5035 DecodeMOVHLPSMask(NumElems, Mask);
5037 case X86ISD::MOVLHPS:
5038 DecodeMOVLHPSMask(NumElems, Mask);
5040 case X86ISD::PALIGNR:
5041 ImmN = N->getOperand(N->getNumOperands()-1);
5042 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5044 case X86ISD::PSHUFD:
5045 case X86ISD::VPERMILP:
5046 ImmN = N->getOperand(N->getNumOperands()-1);
5047 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5050 case X86ISD::PSHUFHW:
5051 ImmN = N->getOperand(N->getNumOperands()-1);
5052 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5055 case X86ISD::PSHUFLW:
5056 ImmN = N->getOperand(N->getNumOperands()-1);
5057 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5060 case X86ISD::VPERMI:
5061 ImmN = N->getOperand(N->getNumOperands()-1);
5062 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5066 case X86ISD::MOVSD: {
5067 // The index 0 always comes from the first element of the second source,
5068 // this is why MOVSS and MOVSD are used in the first place. The other
5069 // elements come from the other positions of the first source vector
5070 Mask.push_back(NumElems);
5071 for (unsigned i = 1; i != NumElems; ++i) {
5076 case X86ISD::VPERM2X128:
5077 ImmN = N->getOperand(N->getNumOperands()-1);
5078 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5079 if (Mask.empty()) return false;
5081 case X86ISD::MOVDDUP:
5082 case X86ISD::MOVLHPD:
5083 case X86ISD::MOVLPD:
5084 case X86ISD::MOVLPS:
5085 case X86ISD::MOVSHDUP:
5086 case X86ISD::MOVSLDUP:
5087 // Not yet implemented
5089 default: llvm_unreachable("unknown target shuffle node");
5095 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5096 /// element of the result of the vector shuffle.
5097 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5100 return SDValue(); // Limit search depth.
5102 SDValue V = SDValue(N, 0);
5103 EVT VT = V.getValueType();
5104 unsigned Opcode = V.getOpcode();
5106 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5107 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5108 int Elt = SV->getMaskElt(Index);
5111 return DAG.getUNDEF(VT.getVectorElementType());
5113 unsigned NumElems = VT.getVectorNumElements();
5114 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5115 : SV->getOperand(1);
5116 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5119 // Recurse into target specific vector shuffles to find scalars.
5120 if (isTargetShuffle(Opcode)) {
5121 MVT ShufVT = V.getSimpleValueType();
5122 unsigned NumElems = ShufVT.getVectorNumElements();
5123 SmallVector<int, 16> ShuffleMask;
5126 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5129 int Elt = ShuffleMask[Index];
5131 return DAG.getUNDEF(ShufVT.getVectorElementType());
5133 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5135 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5139 // Actual nodes that may contain scalar elements
5140 if (Opcode == ISD::BITCAST) {
5141 V = V.getOperand(0);
5142 EVT SrcVT = V.getValueType();
5143 unsigned NumElems = VT.getVectorNumElements();
5145 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5149 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5150 return (Index == 0) ? V.getOperand(0)
5151 : DAG.getUNDEF(VT.getVectorElementType());
5153 if (V.getOpcode() == ISD::BUILD_VECTOR)
5154 return V.getOperand(Index);
5159 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5160 /// shuffle operation which come from a consecutively from a zero. The
5161 /// search can start in two different directions, from left or right.
5162 /// We count undefs as zeros until PreferredNum is reached.
5163 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5164 unsigned NumElems, bool ZerosFromLeft,
5166 unsigned PreferredNum = -1U) {
5167 unsigned NumZeros = 0;
5168 for (unsigned i = 0; i != NumElems; ++i) {
5169 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5170 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5174 if (X86::isZeroNode(Elt))
5176 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5177 NumZeros = std::min(NumZeros + 1, PreferredNum);
5185 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5186 /// correspond consecutively to elements from one of the vector operands,
5187 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5189 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5190 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5191 unsigned NumElems, unsigned &OpNum) {
5192 bool SeenV1 = false;
5193 bool SeenV2 = false;
5195 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5196 int Idx = SVOp->getMaskElt(i);
5197 // Ignore undef indicies
5201 if (Idx < (int)NumElems)
5206 // Only accept consecutive elements from the same vector
5207 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5211 OpNum = SeenV1 ? 0 : 1;
5215 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5216 /// logical left shift of a vector.
5217 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5218 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5220 SVOp->getSimpleValueType(0).getVectorNumElements();
5221 unsigned NumZeros = getNumOfConsecutiveZeros(
5222 SVOp, NumElems, false /* check zeros from right */, DAG,
5223 SVOp->getMaskElt(0));
5229 // Considering the elements in the mask that are not consecutive zeros,
5230 // check if they consecutively come from only one of the source vectors.
5232 // V1 = {X, A, B, C} 0
5234 // vector_shuffle V1, V2 <1, 2, 3, X>
5236 if (!isShuffleMaskConsecutive(SVOp,
5237 0, // Mask Start Index
5238 NumElems-NumZeros, // Mask End Index(exclusive)
5239 NumZeros, // Where to start looking in the src vector
5240 NumElems, // Number of elements in vector
5241 OpSrc)) // Which source operand ?
5246 ShVal = SVOp->getOperand(OpSrc);
5250 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5251 /// logical left shift of a vector.
5252 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5253 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5255 SVOp->getSimpleValueType(0).getVectorNumElements();
5256 unsigned NumZeros = getNumOfConsecutiveZeros(
5257 SVOp, NumElems, true /* check zeros from left */, DAG,
5258 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5264 // Considering the elements in the mask that are not consecutive zeros,
5265 // check if they consecutively come from only one of the source vectors.
5267 // 0 { A, B, X, X } = V2
5269 // vector_shuffle V1, V2 <X, X, 4, 5>
5271 if (!isShuffleMaskConsecutive(SVOp,
5272 NumZeros, // Mask Start Index
5273 NumElems, // Mask End Index(exclusive)
5274 0, // Where to start looking in the src vector
5275 NumElems, // Number of elements in vector
5276 OpSrc)) // Which source operand ?
5281 ShVal = SVOp->getOperand(OpSrc);
5285 /// isVectorShift - Returns true if the shuffle can be implemented as a
5286 /// logical left or right shift of a vector.
5287 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5288 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5289 // Although the logic below support any bitwidth size, there are no
5290 // shift instructions which handle more than 128-bit vectors.
5291 if (!SVOp->getSimpleValueType(0).is128BitVector())
5294 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5295 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5301 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5303 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5304 unsigned NumNonZero, unsigned NumZero,
5306 const X86Subtarget* Subtarget,
5307 const TargetLowering &TLI) {
5314 for (unsigned i = 0; i < 16; ++i) {
5315 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5316 if (ThisIsNonZero && First) {
5318 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5320 V = DAG.getUNDEF(MVT::v8i16);
5325 SDValue ThisElt(0, 0), LastElt(0, 0);
5326 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5327 if (LastIsNonZero) {
5328 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5329 MVT::i16, Op.getOperand(i-1));
5331 if (ThisIsNonZero) {
5332 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5333 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5334 ThisElt, DAG.getConstant(8, MVT::i8));
5336 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5340 if (ThisElt.getNode())
5341 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5342 DAG.getIntPtrConstant(i/2));
5346 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5349 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5351 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5352 unsigned NumNonZero, unsigned NumZero,
5354 const X86Subtarget* Subtarget,
5355 const TargetLowering &TLI) {
5362 for (unsigned i = 0; i < 8; ++i) {
5363 bool isNonZero = (NonZeros & (1 << i)) != 0;
5367 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5369 V = DAG.getUNDEF(MVT::v8i16);
5372 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5373 MVT::v8i16, V, Op.getOperand(i),
5374 DAG.getIntPtrConstant(i));
5381 /// getVShift - Return a vector logical shift node.
5383 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5384 unsigned NumBits, SelectionDAG &DAG,
5385 const TargetLowering &TLI, SDLoc dl) {
5386 assert(VT.is128BitVector() && "Unknown type for VShift");
5387 EVT ShVT = MVT::v2i64;
5388 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5389 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5390 return DAG.getNode(ISD::BITCAST, dl, VT,
5391 DAG.getNode(Opc, dl, ShVT, SrcOp,
5392 DAG.getConstant(NumBits,
5393 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5397 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5399 // Check if the scalar load can be widened into a vector load. And if
5400 // the address is "base + cst" see if the cst can be "absorbed" into
5401 // the shuffle mask.
5402 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5403 SDValue Ptr = LD->getBasePtr();
5404 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5406 EVT PVT = LD->getValueType(0);
5407 if (PVT != MVT::i32 && PVT != MVT::f32)
5412 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5413 FI = FINode->getIndex();
5415 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5416 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5417 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5418 Offset = Ptr.getConstantOperandVal(1);
5419 Ptr = Ptr.getOperand(0);
5424 // FIXME: 256-bit vector instructions don't require a strict alignment,
5425 // improve this code to support it better.
5426 unsigned RequiredAlign = VT.getSizeInBits()/8;
5427 SDValue Chain = LD->getChain();
5428 // Make sure the stack object alignment is at least 16 or 32.
5429 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5430 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5431 if (MFI->isFixedObjectIndex(FI)) {
5432 // Can't change the alignment. FIXME: It's possible to compute
5433 // the exact stack offset and reference FI + adjust offset instead.
5434 // If someone *really* cares about this. That's the way to implement it.
5437 MFI->setObjectAlignment(FI, RequiredAlign);
5441 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5442 // Ptr + (Offset & ~15).
5445 if ((Offset % RequiredAlign) & 3)
5447 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5449 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5450 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5452 int EltNo = (Offset - StartOffset) >> 2;
5453 unsigned NumElems = VT.getVectorNumElements();
5455 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5456 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5457 LD->getPointerInfo().getWithOffset(StartOffset),
5458 false, false, false, 0);
5460 SmallVector<int, 8> Mask;
5461 for (unsigned i = 0; i != NumElems; ++i)
5462 Mask.push_back(EltNo);
5464 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5470 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5471 /// vector of type 'VT', see if the elements can be replaced by a single large
5472 /// load which has the same value as a build_vector whose operands are 'elts'.
5474 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5476 /// FIXME: we'd also like to handle the case where the last elements are zero
5477 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5478 /// There's even a handy isZeroNode for that purpose.
5479 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5480 SDLoc &DL, SelectionDAG &DAG,
5481 bool isAfterLegalize) {
5482 EVT EltVT = VT.getVectorElementType();
5483 unsigned NumElems = Elts.size();
5485 LoadSDNode *LDBase = NULL;
5486 unsigned LastLoadedElt = -1U;
5488 // For each element in the initializer, see if we've found a load or an undef.
5489 // If we don't find an initial load element, or later load elements are
5490 // non-consecutive, bail out.
5491 for (unsigned i = 0; i < NumElems; ++i) {
5492 SDValue Elt = Elts[i];
5494 if (!Elt.getNode() ||
5495 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5498 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5500 LDBase = cast<LoadSDNode>(Elt.getNode());
5504 if (Elt.getOpcode() == ISD::UNDEF)
5507 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5508 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5513 // If we have found an entire vector of loads and undefs, then return a large
5514 // load of the entire vector width starting at the base pointer. If we found
5515 // consecutive loads for the low half, generate a vzext_load node.
5516 if (LastLoadedElt == NumElems - 1) {
5518 if (isAfterLegalize &&
5519 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5522 SDValue NewLd = SDValue();
5524 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5525 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5526 LDBase->getPointerInfo(),
5527 LDBase->isVolatile(), LDBase->isNonTemporal(),
5528 LDBase->isInvariant(), 0);
5529 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5530 LDBase->getPointerInfo(),
5531 LDBase->isVolatile(), LDBase->isNonTemporal(),
5532 LDBase->isInvariant(), LDBase->getAlignment());
5534 if (LDBase->hasAnyUseOfValue(1)) {
5535 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5537 SDValue(NewLd.getNode(), 1));
5538 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5539 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5540 SDValue(NewLd.getNode(), 1));
5545 if (NumElems == 4 && LastLoadedElt == 1 &&
5546 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5547 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5548 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5550 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5551 array_lengthof(Ops), MVT::i64,
5552 LDBase->getPointerInfo(),
5553 LDBase->getAlignment(),
5554 false/*isVolatile*/, true/*ReadMem*/,
5557 // Make sure the newly-created LOAD is in the same position as LDBase in
5558 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5559 // update uses of LDBase's output chain to use the TokenFactor.
5560 if (LDBase->hasAnyUseOfValue(1)) {
5561 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5562 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5563 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5564 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5565 SDValue(ResNode.getNode(), 1));
5568 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5573 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5574 /// to generate a splat value for the following cases:
5575 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5576 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5577 /// a scalar load, or a constant.
5578 /// The VBROADCAST node is returned when a pattern is found,
5579 /// or SDValue() otherwise.
5580 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5581 SelectionDAG &DAG) {
5582 if (!Subtarget->hasFp256())
5585 MVT VT = Op.getSimpleValueType();
5588 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5589 "Unsupported vector type for broadcast.");
5594 switch (Op.getOpcode()) {
5596 // Unknown pattern found.
5599 case ISD::BUILD_VECTOR: {
5600 // The BUILD_VECTOR node must be a splat.
5601 if (!isSplatVector(Op.getNode()))
5604 Ld = Op.getOperand(0);
5605 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5606 Ld.getOpcode() == ISD::ConstantFP);
5608 // The suspected load node has several users. Make sure that all
5609 // of its users are from the BUILD_VECTOR node.
5610 // Constants may have multiple users.
5611 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5616 case ISD::VECTOR_SHUFFLE: {
5617 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5619 // Shuffles must have a splat mask where the first element is
5621 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5624 SDValue Sc = Op.getOperand(0);
5625 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5626 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5628 if (!Subtarget->hasInt256())
5631 // Use the register form of the broadcast instruction available on AVX2.
5632 if (VT.getSizeInBits() >= 256)
5633 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5634 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5637 Ld = Sc.getOperand(0);
5638 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5639 Ld.getOpcode() == ISD::ConstantFP);
5641 // The scalar_to_vector node and the suspected
5642 // load node must have exactly one user.
5643 // Constants may have multiple users.
5645 // AVX-512 has register version of the broadcast
5646 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5647 Ld.getValueType().getSizeInBits() >= 32;
5648 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5655 bool IsGE256 = (VT.getSizeInBits() >= 256);
5657 // Handle the broadcasting a single constant scalar from the constant pool
5658 // into a vector. On Sandybridge it is still better to load a constant vector
5659 // from the constant pool and not to broadcast it from a scalar.
5660 if (ConstSplatVal && Subtarget->hasInt256()) {
5661 EVT CVT = Ld.getValueType();
5662 assert(!CVT.isVector() && "Must not broadcast a vector type");
5663 unsigned ScalarSize = CVT.getSizeInBits();
5665 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5666 const Constant *C = 0;
5667 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5668 C = CI->getConstantIntValue();
5669 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5670 C = CF->getConstantFPValue();
5672 assert(C && "Invalid constant type");
5674 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5675 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5676 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5677 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5678 MachinePointerInfo::getConstantPool(),
5679 false, false, false, Alignment);
5681 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5685 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5686 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5688 // Handle AVX2 in-register broadcasts.
5689 if (!IsLoad && Subtarget->hasInt256() &&
5690 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5691 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5693 // The scalar source must be a normal load.
5697 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5698 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5700 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5701 // double since there is no vbroadcastsd xmm
5702 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5703 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5704 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5707 // Unsupported broadcast.
5711 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5712 MVT VT = Op.getSimpleValueType();
5714 // Skip if insert_vec_elt is not supported.
5715 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5716 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5720 unsigned NumElems = Op.getNumOperands();
5724 SmallVector<unsigned, 4> InsertIndices;
5725 SmallVector<int, 8> Mask(NumElems, -1);
5727 for (unsigned i = 0; i != NumElems; ++i) {
5728 unsigned Opc = Op.getOperand(i).getOpcode();
5730 if (Opc == ISD::UNDEF)
5733 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5734 // Quit if more than 1 elements need inserting.
5735 if (InsertIndices.size() > 1)
5738 InsertIndices.push_back(i);
5742 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5743 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5745 // Quit if extracted from vector of different type.
5746 if (ExtractedFromVec.getValueType() != VT)
5749 // Quit if non-constant index.
5750 if (!isa<ConstantSDNode>(ExtIdx))
5753 if (VecIn1.getNode() == 0)
5754 VecIn1 = ExtractedFromVec;
5755 else if (VecIn1 != ExtractedFromVec) {
5756 if (VecIn2.getNode() == 0)
5757 VecIn2 = ExtractedFromVec;
5758 else if (VecIn2 != ExtractedFromVec)
5759 // Quit if more than 2 vectors to shuffle
5763 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5765 if (ExtractedFromVec == VecIn1)
5767 else if (ExtractedFromVec == VecIn2)
5768 Mask[i] = Idx + NumElems;
5771 if (VecIn1.getNode() == 0)
5774 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5775 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5776 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5777 unsigned Idx = InsertIndices[i];
5778 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5779 DAG.getIntPtrConstant(Idx));
5785 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5787 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5789 MVT VT = Op.getSimpleValueType();
5790 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5791 "Unexpected type in LowerBUILD_VECTORvXi1!");
5794 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5795 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5796 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5797 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5798 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5799 Ops, VT.getVectorNumElements());
5802 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5803 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5804 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5805 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5806 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5807 Ops, VT.getVectorNumElements());
5810 bool AllContants = true;
5811 uint64_t Immediate = 0;
5812 int NonConstIdx = -1;
5813 bool IsSplat = true;
5814 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5815 SDValue In = Op.getOperand(idx);
5816 if (In.getOpcode() == ISD::UNDEF)
5818 if (!isa<ConstantSDNode>(In)) {
5819 AllContants = false;
5822 else if (cast<ConstantSDNode>(In)->getZExtValue())
5823 Immediate |= (1ULL << idx);
5824 if (In != Op.getOperand(0))
5829 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5830 DAG.getConstant(Immediate, MVT::i16));
5831 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5832 DAG.getIntPtrConstant(0));
5835 if (!IsSplat && (NonConstIdx != 0))
5836 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5837 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5840 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5841 DAG.getConstant(-1, SelectVT),
5842 DAG.getConstant(0, SelectVT));
5844 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5845 DAG.getConstant((Immediate | 1), SelectVT),
5846 DAG.getConstant(Immediate, SelectVT));
5847 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5851 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5854 MVT VT = Op.getSimpleValueType();
5855 MVT ExtVT = VT.getVectorElementType();
5856 unsigned NumElems = Op.getNumOperands();
5858 // Generate vectors for predicate vectors.
5859 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5860 return LowerBUILD_VECTORvXi1(Op, DAG);
5862 // Vectors containing all zeros can be matched by pxor and xorps later
5863 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5864 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5865 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5866 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5869 return getZeroVector(VT, Subtarget, DAG, dl);
5872 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5873 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5874 // vpcmpeqd on 256-bit vectors.
5875 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5876 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5879 if (!VT.is512BitVector())
5880 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5883 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5884 if (Broadcast.getNode())
5887 unsigned EVTBits = ExtVT.getSizeInBits();
5889 unsigned NumZero = 0;
5890 unsigned NumNonZero = 0;
5891 unsigned NonZeros = 0;
5892 bool IsAllConstants = true;
5893 SmallSet<SDValue, 8> Values;
5894 for (unsigned i = 0; i < NumElems; ++i) {
5895 SDValue Elt = Op.getOperand(i);
5896 if (Elt.getOpcode() == ISD::UNDEF)
5899 if (Elt.getOpcode() != ISD::Constant &&
5900 Elt.getOpcode() != ISD::ConstantFP)
5901 IsAllConstants = false;
5902 if (X86::isZeroNode(Elt))
5905 NonZeros |= (1 << i);
5910 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5911 if (NumNonZero == 0)
5912 return DAG.getUNDEF(VT);
5914 // Special case for single non-zero, non-undef, element.
5915 if (NumNonZero == 1) {
5916 unsigned Idx = countTrailingZeros(NonZeros);
5917 SDValue Item = Op.getOperand(Idx);
5919 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5920 // the value are obviously zero, truncate the value to i32 and do the
5921 // insertion that way. Only do this if the value is non-constant or if the
5922 // value is a constant being inserted into element 0. It is cheaper to do
5923 // a constant pool load than it is to do a movd + shuffle.
5924 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5925 (!IsAllConstants || Idx == 0)) {
5926 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5928 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5929 EVT VecVT = MVT::v4i32;
5930 unsigned VecElts = 4;
5932 // Truncate the value (which may itself be a constant) to i32, and
5933 // convert it to a vector with movd (S2V+shuffle to zero extend).
5934 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5935 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5936 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5938 // Now we have our 32-bit value zero extended in the low element of
5939 // a vector. If Idx != 0, swizzle it into place.
5941 SmallVector<int, 4> Mask;
5942 Mask.push_back(Idx);
5943 for (unsigned i = 1; i != VecElts; ++i)
5945 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5948 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5952 // If we have a constant or non-constant insertion into the low element of
5953 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5954 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5955 // depending on what the source datatype is.
5958 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5960 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5961 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5962 if (VT.is256BitVector() || VT.is512BitVector()) {
5963 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5964 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5965 Item, DAG.getIntPtrConstant(0));
5967 assert(VT.is128BitVector() && "Expected an SSE value type!");
5968 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5969 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5970 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5973 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5974 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5975 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5976 if (VT.is256BitVector()) {
5977 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5978 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5980 assert(VT.is128BitVector() && "Expected an SSE value type!");
5981 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5983 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5987 // Is it a vector logical left shift?
5988 if (NumElems == 2 && Idx == 1 &&
5989 X86::isZeroNode(Op.getOperand(0)) &&
5990 !X86::isZeroNode(Op.getOperand(1))) {
5991 unsigned NumBits = VT.getSizeInBits();
5992 return getVShift(true, VT,
5993 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5994 VT, Op.getOperand(1)),
5995 NumBits/2, DAG, *this, dl);
5998 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6001 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6002 // is a non-constant being inserted into an element other than the low one,
6003 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6004 // movd/movss) to move this into the low element, then shuffle it into
6006 if (EVTBits == 32) {
6007 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6009 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6010 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6011 SmallVector<int, 8> MaskVec;
6012 for (unsigned i = 0; i != NumElems; ++i)
6013 MaskVec.push_back(i == Idx ? 0 : 1);
6014 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6018 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6019 if (Values.size() == 1) {
6020 if (EVTBits == 32) {
6021 // Instead of a shuffle like this:
6022 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6023 // Check if it's possible to issue this instead.
6024 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6025 unsigned Idx = countTrailingZeros(NonZeros);
6026 SDValue Item = Op.getOperand(Idx);
6027 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6028 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6033 // A vector full of immediates; various special cases are already
6034 // handled, so this is best done with a single constant-pool load.
6038 // For AVX-length vectors, build the individual 128-bit pieces and use
6039 // shuffles to put them in place.
6040 if (VT.is256BitVector() || VT.is512BitVector()) {
6041 SmallVector<SDValue, 64> V;
6042 for (unsigned i = 0; i != NumElems; ++i)
6043 V.push_back(Op.getOperand(i));
6045 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6047 // Build both the lower and upper subvector.
6048 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6049 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6052 // Recreate the wider vector with the lower and upper part.
6053 if (VT.is256BitVector())
6054 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6055 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6058 // Let legalizer expand 2-wide build_vectors.
6059 if (EVTBits == 64) {
6060 if (NumNonZero == 1) {
6061 // One half is zero or undef.
6062 unsigned Idx = countTrailingZeros(NonZeros);
6063 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6064 Op.getOperand(Idx));
6065 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6070 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6071 if (EVTBits == 8 && NumElems == 16) {
6072 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6074 if (V.getNode()) return V;
6077 if (EVTBits == 16 && NumElems == 8) {
6078 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6080 if (V.getNode()) return V;
6083 // If element VT is == 32 bits, turn it into a number of shuffles.
6084 SmallVector<SDValue, 8> V(NumElems);
6085 if (NumElems == 4 && NumZero > 0) {
6086 for (unsigned i = 0; i < 4; ++i) {
6087 bool isZero = !(NonZeros & (1 << i));
6089 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6091 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6094 for (unsigned i = 0; i < 2; ++i) {
6095 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6098 V[i] = V[i*2]; // Must be a zero vector.
6101 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6104 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6107 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6112 bool Reverse1 = (NonZeros & 0x3) == 2;
6113 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6117 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6118 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6120 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6123 if (Values.size() > 1 && VT.is128BitVector()) {
6124 // Check for a build vector of consecutive loads.
6125 for (unsigned i = 0; i < NumElems; ++i)
6126 V[i] = Op.getOperand(i);
6128 // Check for elements which are consecutive loads.
6129 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6133 // Check for a build vector from mostly shuffle plus few inserting.
6134 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6138 // For SSE 4.1, use insertps to put the high elements into the low element.
6139 if (getSubtarget()->hasSSE41()) {
6141 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6142 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6144 Result = DAG.getUNDEF(VT);
6146 for (unsigned i = 1; i < NumElems; ++i) {
6147 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6148 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6149 Op.getOperand(i), DAG.getIntPtrConstant(i));
6154 // Otherwise, expand into a number of unpckl*, start by extending each of
6155 // our (non-undef) elements to the full vector width with the element in the
6156 // bottom slot of the vector (which generates no code for SSE).
6157 for (unsigned i = 0; i < NumElems; ++i) {
6158 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6159 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6161 V[i] = DAG.getUNDEF(VT);
6164 // Next, we iteratively mix elements, e.g. for v4f32:
6165 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6166 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6167 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6168 unsigned EltStride = NumElems >> 1;
6169 while (EltStride != 0) {
6170 for (unsigned i = 0; i < EltStride; ++i) {
6171 // If V[i+EltStride] is undef and this is the first round of mixing,
6172 // then it is safe to just drop this shuffle: V[i] is already in the
6173 // right place, the one element (since it's the first round) being
6174 // inserted as undef can be dropped. This isn't safe for successive
6175 // rounds because they will permute elements within both vectors.
6176 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6177 EltStride == NumElems/2)
6180 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6189 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6190 // to create 256-bit vectors from two other 128-bit ones.
6191 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6193 MVT ResVT = Op.getSimpleValueType();
6195 assert((ResVT.is256BitVector() ||
6196 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6198 SDValue V1 = Op.getOperand(0);
6199 SDValue V2 = Op.getOperand(1);
6200 unsigned NumElems = ResVT.getVectorNumElements();
6201 if(ResVT.is256BitVector())
6202 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6204 if (Op.getNumOperands() == 4) {
6205 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6206 ResVT.getVectorNumElements()/2);
6207 SDValue V3 = Op.getOperand(2);
6208 SDValue V4 = Op.getOperand(3);
6209 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6210 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6212 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6215 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6216 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6217 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6218 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6219 Op.getNumOperands() == 4)));
6221 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6222 // from two other 128-bit ones.
6224 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6225 return LowerAVXCONCAT_VECTORS(Op, DAG);
6228 // Try to lower a shuffle node into a simple blend instruction.
6230 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6231 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6232 SDValue V1 = SVOp->getOperand(0);
6233 SDValue V2 = SVOp->getOperand(1);
6235 MVT VT = SVOp->getSimpleValueType(0);
6236 MVT EltVT = VT.getVectorElementType();
6237 unsigned NumElems = VT.getVectorNumElements();
6239 // There is no blend with immediate in AVX-512.
6240 if (VT.is512BitVector())
6243 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6245 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6248 // Check the mask for BLEND and build the value.
6249 unsigned MaskValue = 0;
6250 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6251 unsigned NumLanes = (NumElems-1)/8 + 1;
6252 unsigned NumElemsInLane = NumElems / NumLanes;
6254 // Blend for v16i16 should be symetric for the both lanes.
6255 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6257 int SndLaneEltIdx = (NumLanes == 2) ?
6258 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6259 int EltIdx = SVOp->getMaskElt(i);
6261 if ((EltIdx < 0 || EltIdx == (int)i) &&
6262 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6265 if (((unsigned)EltIdx == (i + NumElems)) &&
6266 (SndLaneEltIdx < 0 ||
6267 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6268 MaskValue |= (1<<i);
6273 // Convert i32 vectors to floating point if it is not AVX2.
6274 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6276 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6277 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6279 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6280 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6283 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6284 DAG.getConstant(MaskValue, MVT::i32));
6285 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6288 /// In vector type \p VT, return true if the element at index \p InputIdx
6289 /// falls on a different 128-bit lane than \p OutputIdx.
6290 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6291 unsigned OutputIdx) {
6292 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6293 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6296 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6297 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6298 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6299 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6301 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6302 SelectionDAG &DAG) {
6303 MVT VT = V1.getSimpleValueType();
6304 assert(VT.is128BitVector() || VT.is256BitVector());
6306 MVT EltVT = VT.getVectorElementType();
6307 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6308 unsigned NumElts = VT.getVectorNumElements();
6310 SmallVector<SDValue, 32> PshufbMask;
6311 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6312 int InputIdx = MaskVals[OutputIdx];
6313 unsigned InputByteIdx;
6315 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6316 InputByteIdx = 0x80;
6318 // Cross lane is not allowed.
6319 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6321 InputByteIdx = InputIdx * EltSizeInBytes;
6322 // Index is an byte offset within the 128-bit lane.
6323 InputByteIdx &= 0xf;
6326 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6327 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6328 if (InputByteIdx != 0x80)
6333 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6335 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6336 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6337 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6338 PshufbMask.data(), PshufbMask.size()));
6341 // v8i16 shuffles - Prefer shuffles in the following order:
6342 // 1. [all] pshuflw, pshufhw, optional move
6343 // 2. [ssse3] 1 x pshufb
6344 // 3. [ssse3] 2 x pshufb + 1 x por
6345 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6347 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6348 SelectionDAG &DAG) {
6349 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6350 SDValue V1 = SVOp->getOperand(0);
6351 SDValue V2 = SVOp->getOperand(1);
6353 SmallVector<int, 8> MaskVals;
6355 // Determine if more than 1 of the words in each of the low and high quadwords
6356 // of the result come from the same quadword of one of the two inputs. Undef
6357 // mask values count as coming from any quadword, for better codegen.
6359 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6360 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6361 unsigned LoQuad[] = { 0, 0, 0, 0 };
6362 unsigned HiQuad[] = { 0, 0, 0, 0 };
6363 // Indices of quads used.
6364 std::bitset<4> InputQuads;
6365 for (unsigned i = 0; i < 8; ++i) {
6366 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6367 int EltIdx = SVOp->getMaskElt(i);
6368 MaskVals.push_back(EltIdx);
6377 InputQuads.set(EltIdx / 4);
6380 int BestLoQuad = -1;
6381 unsigned MaxQuad = 1;
6382 for (unsigned i = 0; i < 4; ++i) {
6383 if (LoQuad[i] > MaxQuad) {
6385 MaxQuad = LoQuad[i];
6389 int BestHiQuad = -1;
6391 for (unsigned i = 0; i < 4; ++i) {
6392 if (HiQuad[i] > MaxQuad) {
6394 MaxQuad = HiQuad[i];
6398 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6399 // of the two input vectors, shuffle them into one input vector so only a
6400 // single pshufb instruction is necessary. If there are more than 2 input
6401 // quads, disable the next transformation since it does not help SSSE3.
6402 bool V1Used = InputQuads[0] || InputQuads[1];
6403 bool V2Used = InputQuads[2] || InputQuads[3];
6404 if (Subtarget->hasSSSE3()) {
6405 if (InputQuads.count() == 2 && V1Used && V2Used) {
6406 BestLoQuad = InputQuads[0] ? 0 : 1;
6407 BestHiQuad = InputQuads[2] ? 2 : 3;
6409 if (InputQuads.count() > 2) {
6415 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6416 // the shuffle mask. If a quad is scored as -1, that means that it contains
6417 // words from all 4 input quadwords.
6419 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6421 BestLoQuad < 0 ? 0 : BestLoQuad,
6422 BestHiQuad < 0 ? 1 : BestHiQuad
6424 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6425 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6426 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6427 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6429 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6430 // source words for the shuffle, to aid later transformations.
6431 bool AllWordsInNewV = true;
6432 bool InOrder[2] = { true, true };
6433 for (unsigned i = 0; i != 8; ++i) {
6434 int idx = MaskVals[i];
6436 InOrder[i/4] = false;
6437 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6439 AllWordsInNewV = false;
6443 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6444 if (AllWordsInNewV) {
6445 for (int i = 0; i != 8; ++i) {
6446 int idx = MaskVals[i];
6449 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6450 if ((idx != i) && idx < 4)
6452 if ((idx != i) && idx > 3)
6461 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6462 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6463 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6464 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6465 unsigned TargetMask = 0;
6466 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6467 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6468 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6469 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6470 getShufflePSHUFLWImmediate(SVOp);
6471 V1 = NewV.getOperand(0);
6472 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6476 // Promote splats to a larger type which usually leads to more efficient code.
6477 // FIXME: Is this true if pshufb is available?
6478 if (SVOp->isSplat())
6479 return PromoteSplat(SVOp, DAG);
6481 // If we have SSSE3, and all words of the result are from 1 input vector,
6482 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6483 // is present, fall back to case 4.
6484 if (Subtarget->hasSSSE3()) {
6485 SmallVector<SDValue,16> pshufbMask;
6487 // If we have elements from both input vectors, set the high bit of the
6488 // shuffle mask element to zero out elements that come from V2 in the V1
6489 // mask, and elements that come from V1 in the V2 mask, so that the two
6490 // results can be OR'd together.
6491 bool TwoInputs = V1Used && V2Used;
6492 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6494 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6496 // Calculate the shuffle mask for the second input, shuffle it, and
6497 // OR it with the first shuffled input.
6498 CommuteVectorShuffleMask(MaskVals, 8);
6499 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6500 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6501 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6504 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6505 // and update MaskVals with new element order.
6506 std::bitset<8> InOrder;
6507 if (BestLoQuad >= 0) {
6508 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6509 for (int i = 0; i != 4; ++i) {
6510 int idx = MaskVals[i];
6513 } else if ((idx / 4) == BestLoQuad) {
6518 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6521 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6522 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6523 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6525 getShufflePSHUFLWImmediate(SVOp), DAG);
6529 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6530 // and update MaskVals with the new element order.
6531 if (BestHiQuad >= 0) {
6532 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6533 for (unsigned i = 4; i != 8; ++i) {
6534 int idx = MaskVals[i];
6537 } else if ((idx / 4) == BestHiQuad) {
6538 MaskV[i] = (idx & 3) + 4;
6542 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6545 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6546 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6547 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6549 getShufflePSHUFHWImmediate(SVOp), DAG);
6553 // In case BestHi & BestLo were both -1, which means each quadword has a word
6554 // from each of the four input quadwords, calculate the InOrder bitvector now
6555 // before falling through to the insert/extract cleanup.
6556 if (BestLoQuad == -1 && BestHiQuad == -1) {
6558 for (int i = 0; i != 8; ++i)
6559 if (MaskVals[i] < 0 || MaskVals[i] == i)
6563 // The other elements are put in the right place using pextrw and pinsrw.
6564 for (unsigned i = 0; i != 8; ++i) {
6567 int EltIdx = MaskVals[i];
6570 SDValue ExtOp = (EltIdx < 8) ?
6571 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6572 DAG.getIntPtrConstant(EltIdx)) :
6573 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6574 DAG.getIntPtrConstant(EltIdx - 8));
6575 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6576 DAG.getIntPtrConstant(i));
6581 /// \brief v16i16 shuffles
6583 /// FIXME: We only support generation of a single pshufb currently. We can
6584 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6585 /// well (e.g 2 x pshufb + 1 x por).
6587 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6588 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6589 SDValue V1 = SVOp->getOperand(0);
6590 SDValue V2 = SVOp->getOperand(1);
6593 if (V2.getOpcode() != ISD::UNDEF)
6596 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6597 return getPSHUFB(MaskVals, V1, dl, DAG);
6600 // v16i8 shuffles - Prefer shuffles in the following order:
6601 // 1. [ssse3] 1 x pshufb
6602 // 2. [ssse3] 2 x pshufb + 1 x por
6603 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6604 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6605 const X86Subtarget* Subtarget,
6606 SelectionDAG &DAG) {
6607 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6608 SDValue V1 = SVOp->getOperand(0);
6609 SDValue V2 = SVOp->getOperand(1);
6611 ArrayRef<int> MaskVals = SVOp->getMask();
6613 // Promote splats to a larger type which usually leads to more efficient code.
6614 // FIXME: Is this true if pshufb is available?
6615 if (SVOp->isSplat())
6616 return PromoteSplat(SVOp, DAG);
6618 // If we have SSSE3, case 1 is generated when all result bytes come from
6619 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6620 // present, fall back to case 3.
6622 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6623 if (Subtarget->hasSSSE3()) {
6624 SmallVector<SDValue,16> pshufbMask;
6626 // If all result elements are from one input vector, then only translate
6627 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6629 // Otherwise, we have elements from both input vectors, and must zero out
6630 // elements that come from V2 in the first mask, and V1 in the second mask
6631 // so that we can OR them together.
6632 for (unsigned i = 0; i != 16; ++i) {
6633 int EltIdx = MaskVals[i];
6634 if (EltIdx < 0 || EltIdx >= 16)
6636 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6638 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6639 DAG.getNode(ISD::BUILD_VECTOR, dl,
6640 MVT::v16i8, &pshufbMask[0], 16));
6642 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6643 // the 2nd operand if it's undefined or zero.
6644 if (V2.getOpcode() == ISD::UNDEF ||
6645 ISD::isBuildVectorAllZeros(V2.getNode()))
6648 // Calculate the shuffle mask for the second input, shuffle it, and
6649 // OR it with the first shuffled input.
6651 for (unsigned i = 0; i != 16; ++i) {
6652 int EltIdx = MaskVals[i];
6653 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6654 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6656 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6657 DAG.getNode(ISD::BUILD_VECTOR, dl,
6658 MVT::v16i8, &pshufbMask[0], 16));
6659 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6662 // No SSSE3 - Calculate in place words and then fix all out of place words
6663 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6664 // the 16 different words that comprise the two doublequadword input vectors.
6665 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6666 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6668 for (int i = 0; i != 8; ++i) {
6669 int Elt0 = MaskVals[i*2];
6670 int Elt1 = MaskVals[i*2+1];
6672 // This word of the result is all undef, skip it.
6673 if (Elt0 < 0 && Elt1 < 0)
6676 // This word of the result is already in the correct place, skip it.
6677 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6680 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6681 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6684 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6685 // using a single extract together, load it and store it.
6686 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6687 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6688 DAG.getIntPtrConstant(Elt1 / 2));
6689 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6690 DAG.getIntPtrConstant(i));
6694 // If Elt1 is defined, extract it from the appropriate source. If the
6695 // source byte is not also odd, shift the extracted word left 8 bits
6696 // otherwise clear the bottom 8 bits if we need to do an or.
6698 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6699 DAG.getIntPtrConstant(Elt1 / 2));
6700 if ((Elt1 & 1) == 0)
6701 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6703 TLI.getShiftAmountTy(InsElt.getValueType())));
6705 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6706 DAG.getConstant(0xFF00, MVT::i16));
6708 // If Elt0 is defined, extract it from the appropriate source. If the
6709 // source byte is not also even, shift the extracted word right 8 bits. If
6710 // Elt1 was also defined, OR the extracted values together before
6711 // inserting them in the result.
6713 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6714 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6715 if ((Elt0 & 1) != 0)
6716 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6718 TLI.getShiftAmountTy(InsElt0.getValueType())));
6720 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6721 DAG.getConstant(0x00FF, MVT::i16));
6722 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6725 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6726 DAG.getIntPtrConstant(i));
6728 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6731 // v32i8 shuffles - Translate to VPSHUFB if possible.
6733 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6734 const X86Subtarget *Subtarget,
6735 SelectionDAG &DAG) {
6736 MVT VT = SVOp->getSimpleValueType(0);
6737 SDValue V1 = SVOp->getOperand(0);
6738 SDValue V2 = SVOp->getOperand(1);
6740 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6742 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6743 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6744 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6746 // VPSHUFB may be generated if
6747 // (1) one of input vector is undefined or zeroinitializer.
6748 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6749 // And (2) the mask indexes don't cross the 128-bit lane.
6750 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6751 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6754 if (V1IsAllZero && !V2IsAllZero) {
6755 CommuteVectorShuffleMask(MaskVals, 32);
6758 return getPSHUFB(MaskVals, V1, dl, DAG);
6761 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6762 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6763 /// done when every pair / quad of shuffle mask elements point to elements in
6764 /// the right sequence. e.g.
6765 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6767 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6768 SelectionDAG &DAG) {
6769 MVT VT = SVOp->getSimpleValueType(0);
6771 unsigned NumElems = VT.getVectorNumElements();
6774 switch (VT.SimpleTy) {
6775 default: llvm_unreachable("Unexpected!");
6776 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6777 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6778 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6779 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6780 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6781 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6784 SmallVector<int, 8> MaskVec;
6785 for (unsigned i = 0; i != NumElems; i += Scale) {
6787 for (unsigned j = 0; j != Scale; ++j) {
6788 int EltIdx = SVOp->getMaskElt(i+j);
6792 StartIdx = (EltIdx / Scale);
6793 if (EltIdx != (int)(StartIdx*Scale + j))
6796 MaskVec.push_back(StartIdx);
6799 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6800 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6801 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6804 /// getVZextMovL - Return a zero-extending vector move low node.
6806 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6807 SDValue SrcOp, SelectionDAG &DAG,
6808 const X86Subtarget *Subtarget, SDLoc dl) {
6809 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6810 LoadSDNode *LD = NULL;
6811 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6812 LD = dyn_cast<LoadSDNode>(SrcOp);
6814 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6816 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6817 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6818 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6819 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6820 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6822 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6823 return DAG.getNode(ISD::BITCAST, dl, VT,
6824 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6825 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6833 return DAG.getNode(ISD::BITCAST, dl, VT,
6834 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6835 DAG.getNode(ISD::BITCAST, dl,
6839 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6840 /// which could not be matched by any known target speficic shuffle
6842 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6844 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6845 if (NewOp.getNode())
6848 MVT VT = SVOp->getSimpleValueType(0);
6850 unsigned NumElems = VT.getVectorNumElements();
6851 unsigned NumLaneElems = NumElems / 2;
6854 MVT EltVT = VT.getVectorElementType();
6855 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6858 SmallVector<int, 16> Mask;
6859 for (unsigned l = 0; l < 2; ++l) {
6860 // Build a shuffle mask for the output, discovering on the fly which
6861 // input vectors to use as shuffle operands (recorded in InputUsed).
6862 // If building a suitable shuffle vector proves too hard, then bail
6863 // out with UseBuildVector set.
6864 bool UseBuildVector = false;
6865 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6866 unsigned LaneStart = l * NumLaneElems;
6867 for (unsigned i = 0; i != NumLaneElems; ++i) {
6868 // The mask element. This indexes into the input.
6869 int Idx = SVOp->getMaskElt(i+LaneStart);
6871 // the mask element does not index into any input vector.
6876 // The input vector this mask element indexes into.
6877 int Input = Idx / NumLaneElems;
6879 // Turn the index into an offset from the start of the input vector.
6880 Idx -= Input * NumLaneElems;
6882 // Find or create a shuffle vector operand to hold this input.
6884 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6885 if (InputUsed[OpNo] == Input)
6886 // This input vector is already an operand.
6888 if (InputUsed[OpNo] < 0) {
6889 // Create a new operand for this input vector.
6890 InputUsed[OpNo] = Input;
6895 if (OpNo >= array_lengthof(InputUsed)) {
6896 // More than two input vectors used! Give up on trying to create a
6897 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6898 UseBuildVector = true;
6902 // Add the mask index for the new shuffle vector.
6903 Mask.push_back(Idx + OpNo * NumLaneElems);
6906 if (UseBuildVector) {
6907 SmallVector<SDValue, 16> SVOps;
6908 for (unsigned i = 0; i != NumLaneElems; ++i) {
6909 // The mask element. This indexes into the input.
6910 int Idx = SVOp->getMaskElt(i+LaneStart);
6912 SVOps.push_back(DAG.getUNDEF(EltVT));
6916 // The input vector this mask element indexes into.
6917 int Input = Idx / NumElems;
6919 // Turn the index into an offset from the start of the input vector.
6920 Idx -= Input * NumElems;
6922 // Extract the vector element by hand.
6923 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6924 SVOp->getOperand(Input),
6925 DAG.getIntPtrConstant(Idx)));
6928 // Construct the output using a BUILD_VECTOR.
6929 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6931 } else if (InputUsed[0] < 0) {
6932 // No input vectors were used! The result is undefined.
6933 Output[l] = DAG.getUNDEF(NVT);
6935 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6936 (InputUsed[0] % 2) * NumLaneElems,
6938 // If only one input was used, use an undefined vector for the other.
6939 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6940 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6941 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6942 // At least one input vector was used. Create a new shuffle vector.
6943 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6949 // Concatenate the result back
6950 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6953 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6954 /// 4 elements, and match them with several different shuffle types.
6956 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6957 SDValue V1 = SVOp->getOperand(0);
6958 SDValue V2 = SVOp->getOperand(1);
6960 MVT VT = SVOp->getSimpleValueType(0);
6962 assert(VT.is128BitVector() && "Unsupported vector size");
6964 std::pair<int, int> Locs[4];
6965 int Mask1[] = { -1, -1, -1, -1 };
6966 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6970 for (unsigned i = 0; i != 4; ++i) {
6971 int Idx = PermMask[i];
6973 Locs[i] = std::make_pair(-1, -1);
6975 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6977 Locs[i] = std::make_pair(0, NumLo);
6981 Locs[i] = std::make_pair(1, NumHi);
6983 Mask1[2+NumHi] = Idx;
6989 if (NumLo <= 2 && NumHi <= 2) {
6990 // If no more than two elements come from either vector. This can be
6991 // implemented with two shuffles. First shuffle gather the elements.
6992 // The second shuffle, which takes the first shuffle as both of its
6993 // vector operands, put the elements into the right order.
6994 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6996 int Mask2[] = { -1, -1, -1, -1 };
6998 for (unsigned i = 0; i != 4; ++i)
6999 if (Locs[i].first != -1) {
7000 unsigned Idx = (i < 2) ? 0 : 4;
7001 Idx += Locs[i].first * 2 + Locs[i].second;
7005 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7008 if (NumLo == 3 || NumHi == 3) {
7009 // Otherwise, we must have three elements from one vector, call it X, and
7010 // one element from the other, call it Y. First, use a shufps to build an
7011 // intermediate vector with the one element from Y and the element from X
7012 // that will be in the same half in the final destination (the indexes don't
7013 // matter). Then, use a shufps to build the final vector, taking the half
7014 // containing the element from Y from the intermediate, and the other half
7017 // Normalize it so the 3 elements come from V1.
7018 CommuteVectorShuffleMask(PermMask, 4);
7022 // Find the element from V2.
7024 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7025 int Val = PermMask[HiIndex];
7032 Mask1[0] = PermMask[HiIndex];
7034 Mask1[2] = PermMask[HiIndex^1];
7036 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7039 Mask1[0] = PermMask[0];
7040 Mask1[1] = PermMask[1];
7041 Mask1[2] = HiIndex & 1 ? 6 : 4;
7042 Mask1[3] = HiIndex & 1 ? 4 : 6;
7043 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7046 Mask1[0] = HiIndex & 1 ? 2 : 0;
7047 Mask1[1] = HiIndex & 1 ? 0 : 2;
7048 Mask1[2] = PermMask[2];
7049 Mask1[3] = PermMask[3];
7054 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7057 // Break it into (shuffle shuffle_hi, shuffle_lo).
7058 int LoMask[] = { -1, -1, -1, -1 };
7059 int HiMask[] = { -1, -1, -1, -1 };
7061 int *MaskPtr = LoMask;
7062 unsigned MaskIdx = 0;
7065 for (unsigned i = 0; i != 4; ++i) {
7072 int Idx = PermMask[i];
7074 Locs[i] = std::make_pair(-1, -1);
7075 } else if (Idx < 4) {
7076 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7077 MaskPtr[LoIdx] = Idx;
7080 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7081 MaskPtr[HiIdx] = Idx;
7086 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7087 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7088 int MaskOps[] = { -1, -1, -1, -1 };
7089 for (unsigned i = 0; i != 4; ++i)
7090 if (Locs[i].first != -1)
7091 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7092 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7095 static bool MayFoldVectorLoad(SDValue V) {
7096 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7097 V = V.getOperand(0);
7099 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7100 V = V.getOperand(0);
7101 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7102 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7103 // BUILD_VECTOR (load), undef
7104 V = V.getOperand(0);
7106 return MayFoldLoad(V);
7110 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7111 MVT VT = Op.getSimpleValueType();
7113 // Canonizalize to v2f64.
7114 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7115 return DAG.getNode(ISD::BITCAST, dl, VT,
7116 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7121 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7123 SDValue V1 = Op.getOperand(0);
7124 SDValue V2 = Op.getOperand(1);
7125 MVT VT = Op.getSimpleValueType();
7127 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7129 if (HasSSE2 && VT == MVT::v2f64)
7130 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7132 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7133 return DAG.getNode(ISD::BITCAST, dl, VT,
7134 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7135 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7136 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7140 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7141 SDValue V1 = Op.getOperand(0);
7142 SDValue V2 = Op.getOperand(1);
7143 MVT VT = Op.getSimpleValueType();
7145 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7146 "unsupported shuffle type");
7148 if (V2.getOpcode() == ISD::UNDEF)
7152 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7156 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7157 SDValue V1 = Op.getOperand(0);
7158 SDValue V2 = Op.getOperand(1);
7159 MVT VT = Op.getSimpleValueType();
7160 unsigned NumElems = VT.getVectorNumElements();
7162 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7163 // operand of these instructions is only memory, so check if there's a
7164 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7166 bool CanFoldLoad = false;
7168 // Trivial case, when V2 comes from a load.
7169 if (MayFoldVectorLoad(V2))
7172 // When V1 is a load, it can be folded later into a store in isel, example:
7173 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7175 // (MOVLPSmr addr:$src1, VR128:$src2)
7176 // So, recognize this potential and also use MOVLPS or MOVLPD
7177 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7180 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7182 if (HasSSE2 && NumElems == 2)
7183 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7186 // If we don't care about the second element, proceed to use movss.
7187 if (SVOp->getMaskElt(1) != -1)
7188 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7191 // movl and movlp will both match v2i64, but v2i64 is never matched by
7192 // movl earlier because we make it strict to avoid messing with the movlp load
7193 // folding logic (see the code above getMOVLP call). Match it here then,
7194 // this is horrible, but will stay like this until we move all shuffle
7195 // matching to x86 specific nodes. Note that for the 1st condition all
7196 // types are matched with movsd.
7198 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7199 // as to remove this logic from here, as much as possible
7200 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7201 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7202 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7205 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7207 // Invert the operand order and use SHUFPS to match it.
7208 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7209 getShuffleSHUFImmediate(SVOp), DAG);
7212 // Reduce a vector shuffle to zext.
7213 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7214 SelectionDAG &DAG) {
7215 // PMOVZX is only available from SSE41.
7216 if (!Subtarget->hasSSE41())
7219 MVT VT = Op.getSimpleValueType();
7221 // Only AVX2 support 256-bit vector integer extending.
7222 if (!Subtarget->hasInt256() && VT.is256BitVector())
7225 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7227 SDValue V1 = Op.getOperand(0);
7228 SDValue V2 = Op.getOperand(1);
7229 unsigned NumElems = VT.getVectorNumElements();
7231 // Extending is an unary operation and the element type of the source vector
7232 // won't be equal to or larger than i64.
7233 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7234 VT.getVectorElementType() == MVT::i64)
7237 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7238 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7239 while ((1U << Shift) < NumElems) {
7240 if (SVOp->getMaskElt(1U << Shift) == 1)
7243 // The maximal ratio is 8, i.e. from i8 to i64.
7248 // Check the shuffle mask.
7249 unsigned Mask = (1U << Shift) - 1;
7250 for (unsigned i = 0; i != NumElems; ++i) {
7251 int EltIdx = SVOp->getMaskElt(i);
7252 if ((i & Mask) != 0 && EltIdx != -1)
7254 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7258 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7259 MVT NeVT = MVT::getIntegerVT(NBits);
7260 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7262 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7265 // Simplify the operand as it's prepared to be fed into shuffle.
7266 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7267 if (V1.getOpcode() == ISD::BITCAST &&
7268 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7269 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7270 V1.getOperand(0).getOperand(0)
7271 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7272 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7273 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7274 ConstantSDNode *CIdx =
7275 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7276 // If it's foldable, i.e. normal load with single use, we will let code
7277 // selection to fold it. Otherwise, we will short the conversion sequence.
7278 if (CIdx && CIdx->getZExtValue() == 0 &&
7279 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7280 MVT FullVT = V.getSimpleValueType();
7281 MVT V1VT = V1.getSimpleValueType();
7282 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7283 // The "ext_vec_elt" node is wider than the result node.
7284 // In this case we should extract subvector from V.
7285 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7286 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7287 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7288 FullVT.getVectorNumElements()/Ratio);
7289 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7290 DAG.getIntPtrConstant(0));
7292 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7296 return DAG.getNode(ISD::BITCAST, DL, VT,
7297 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7301 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7302 SelectionDAG &DAG) {
7303 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7304 MVT VT = Op.getSimpleValueType();
7306 SDValue V1 = Op.getOperand(0);
7307 SDValue V2 = Op.getOperand(1);
7309 if (isZeroShuffle(SVOp))
7310 return getZeroVector(VT, Subtarget, DAG, dl);
7312 // Handle splat operations
7313 if (SVOp->isSplat()) {
7314 // Use vbroadcast whenever the splat comes from a foldable load
7315 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7316 if (Broadcast.getNode())
7320 // Check integer expanding shuffles.
7321 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7322 if (NewOp.getNode())
7325 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7327 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7328 VT == MVT::v16i16 || VT == MVT::v32i8) {
7329 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7330 if (NewOp.getNode())
7331 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7332 } else if ((VT == MVT::v4i32 ||
7333 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7334 // FIXME: Figure out a cleaner way to do this.
7335 // Try to make use of movq to zero out the top part.
7336 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7337 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7338 if (NewOp.getNode()) {
7339 MVT NewVT = NewOp.getSimpleValueType();
7340 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7341 NewVT, true, false))
7342 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7343 DAG, Subtarget, dl);
7345 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7346 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7347 if (NewOp.getNode()) {
7348 MVT NewVT = NewOp.getSimpleValueType();
7349 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7350 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7351 DAG, Subtarget, dl);
7359 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7360 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7361 SDValue V1 = Op.getOperand(0);
7362 SDValue V2 = Op.getOperand(1);
7363 MVT VT = Op.getSimpleValueType();
7365 unsigned NumElems = VT.getVectorNumElements();
7366 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7367 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7368 bool V1IsSplat = false;
7369 bool V2IsSplat = false;
7370 bool HasSSE2 = Subtarget->hasSSE2();
7371 bool HasFp256 = Subtarget->hasFp256();
7372 bool HasInt256 = Subtarget->hasInt256();
7373 MachineFunction &MF = DAG.getMachineFunction();
7374 bool OptForSize = MF.getFunction()->getAttributes().
7375 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7377 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7379 if (V1IsUndef && V2IsUndef)
7380 return DAG.getUNDEF(VT);
7382 // When we create a shuffle node we put the UNDEF node to second operand,
7383 // but in some cases the first operand may be transformed to UNDEF.
7384 // In this case we should just commute the node.
7386 return CommuteVectorShuffle(SVOp, DAG);
7388 // Vector shuffle lowering takes 3 steps:
7390 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7391 // narrowing and commutation of operands should be handled.
7392 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7394 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7395 // so the shuffle can be broken into other shuffles and the legalizer can
7396 // try the lowering again.
7398 // The general idea is that no vector_shuffle operation should be left to
7399 // be matched during isel, all of them must be converted to a target specific
7402 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7403 // narrowing and commutation of operands should be handled. The actual code
7404 // doesn't include all of those, work in progress...
7405 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7406 if (NewOp.getNode())
7409 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7411 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7412 // unpckh_undef). Only use pshufd if speed is more important than size.
7413 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7414 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7415 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7416 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7418 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7419 V2IsUndef && MayFoldVectorLoad(V1))
7420 return getMOVDDup(Op, dl, V1, DAG);
7422 if (isMOVHLPS_v_undef_Mask(M, VT))
7423 return getMOVHighToLow(Op, dl, DAG);
7425 // Use to match splats
7426 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7427 (VT == MVT::v2f64 || VT == MVT::v2i64))
7428 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7430 if (isPSHUFDMask(M, VT)) {
7431 // The actual implementation will match the mask in the if above and then
7432 // during isel it can match several different instructions, not only pshufd
7433 // as its name says, sad but true, emulate the behavior for now...
7434 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7435 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7437 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7439 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7440 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7442 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7443 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7446 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7450 if (isPALIGNRMask(M, VT, Subtarget))
7451 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7452 getShufflePALIGNRImmediate(SVOp),
7455 // Check if this can be converted into a logical shift.
7456 bool isLeft = false;
7459 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7460 if (isShift && ShVal.hasOneUse()) {
7461 // If the shifted value has multiple uses, it may be cheaper to use
7462 // v_set0 + movlhps or movhlps, etc.
7463 MVT EltVT = VT.getVectorElementType();
7464 ShAmt *= EltVT.getSizeInBits();
7465 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7468 if (isMOVLMask(M, VT)) {
7469 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7470 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7471 if (!isMOVLPMask(M, VT)) {
7472 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7473 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7475 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7476 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7480 // FIXME: fold these into legal mask.
7481 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7482 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7484 if (isMOVHLPSMask(M, VT))
7485 return getMOVHighToLow(Op, dl, DAG);
7487 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7488 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7490 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7491 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7493 if (isMOVLPMask(M, VT))
7494 return getMOVLP(Op, dl, DAG, HasSSE2);
7496 if (ShouldXformToMOVHLPS(M, VT) ||
7497 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7498 return CommuteVectorShuffle(SVOp, DAG);
7501 // No better options. Use a vshldq / vsrldq.
7502 MVT EltVT = VT.getVectorElementType();
7503 ShAmt *= EltVT.getSizeInBits();
7504 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7507 bool Commuted = false;
7508 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7509 // 1,1,1,1 -> v8i16 though.
7510 V1IsSplat = isSplatVector(V1.getNode());
7511 V2IsSplat = isSplatVector(V2.getNode());
7513 // Canonicalize the splat or undef, if present, to be on the RHS.
7514 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7515 CommuteVectorShuffleMask(M, NumElems);
7517 std::swap(V1IsSplat, V2IsSplat);
7521 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7522 // Shuffling low element of v1 into undef, just return v1.
7525 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7526 // the instruction selector will not match, so get a canonical MOVL with
7527 // swapped operands to undo the commute.
7528 return getMOVL(DAG, dl, VT, V2, V1);
7531 if (isUNPCKLMask(M, VT, HasInt256))
7532 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7534 if (isUNPCKHMask(M, VT, HasInt256))
7535 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7538 // Normalize mask so all entries that point to V2 points to its first
7539 // element then try to match unpck{h|l} again. If match, return a
7540 // new vector_shuffle with the corrected mask.p
7541 SmallVector<int, 8> NewMask(M.begin(), M.end());
7542 NormalizeMask(NewMask, NumElems);
7543 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7544 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7545 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7546 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7550 // Commute is back and try unpck* again.
7551 // FIXME: this seems wrong.
7552 CommuteVectorShuffleMask(M, NumElems);
7554 std::swap(V1IsSplat, V2IsSplat);
7556 if (isUNPCKLMask(M, VT, HasInt256))
7557 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7559 if (isUNPCKHMask(M, VT, HasInt256))
7560 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7563 // Normalize the node to match x86 shuffle ops if needed
7564 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7565 return CommuteVectorShuffle(SVOp, DAG);
7567 // The checks below are all present in isShuffleMaskLegal, but they are
7568 // inlined here right now to enable us to directly emit target specific
7569 // nodes, and remove one by one until they don't return Op anymore.
7571 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7572 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7573 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7574 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7577 if (isPSHUFHWMask(M, VT, HasInt256))
7578 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7579 getShufflePSHUFHWImmediate(SVOp),
7582 if (isPSHUFLWMask(M, VT, HasInt256))
7583 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7584 getShufflePSHUFLWImmediate(SVOp),
7587 if (isSHUFPMask(M, VT))
7588 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7589 getShuffleSHUFImmediate(SVOp), DAG);
7591 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7592 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7593 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7594 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7596 //===--------------------------------------------------------------------===//
7597 // Generate target specific nodes for 128 or 256-bit shuffles only
7598 // supported in the AVX instruction set.
7601 // Handle VMOVDDUPY permutations
7602 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7603 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7605 // Handle VPERMILPS/D* permutations
7606 if (isVPERMILPMask(M, VT)) {
7607 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7608 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7609 getShuffleSHUFImmediate(SVOp), DAG);
7610 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7611 getShuffleSHUFImmediate(SVOp), DAG);
7614 // Handle VPERM2F128/VPERM2I128 permutations
7615 if (isVPERM2X128Mask(M, VT, HasFp256))
7616 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7617 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7619 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7620 if (BlendOp.getNode())
7624 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7625 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7627 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7628 VT.is512BitVector()) {
7629 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7630 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7631 SmallVector<SDValue, 16> permclMask;
7632 for (unsigned i = 0; i != NumElems; ++i) {
7633 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7636 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7637 &permclMask[0], NumElems);
7639 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7640 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7641 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7642 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7643 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7646 //===--------------------------------------------------------------------===//
7647 // Since no target specific shuffle was selected for this generic one,
7648 // lower it into other known shuffles. FIXME: this isn't true yet, but
7649 // this is the plan.
7652 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7653 if (VT == MVT::v8i16) {
7654 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7655 if (NewOp.getNode())
7659 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7660 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7661 if (NewOp.getNode())
7665 if (VT == MVT::v16i8) {
7666 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7667 if (NewOp.getNode())
7671 if (VT == MVT::v32i8) {
7672 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7673 if (NewOp.getNode())
7677 // Handle all 128-bit wide vectors with 4 elements, and match them with
7678 // several different shuffle types.
7679 if (NumElems == 4 && VT.is128BitVector())
7680 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7682 // Handle general 256-bit shuffles
7683 if (VT.is256BitVector())
7684 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7689 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7690 MVT VT = Op.getSimpleValueType();
7693 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7696 if (VT.getSizeInBits() == 8) {
7697 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7698 Op.getOperand(0), Op.getOperand(1));
7699 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7700 DAG.getValueType(VT));
7701 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7704 if (VT.getSizeInBits() == 16) {
7705 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7706 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7708 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7709 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7710 DAG.getNode(ISD::BITCAST, dl,
7714 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7715 Op.getOperand(0), Op.getOperand(1));
7716 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7717 DAG.getValueType(VT));
7718 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7721 if (VT == MVT::f32) {
7722 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7723 // the result back to FR32 register. It's only worth matching if the
7724 // result has a single use which is a store or a bitcast to i32. And in
7725 // the case of a store, it's not worth it if the index is a constant 0,
7726 // because a MOVSSmr can be used instead, which is smaller and faster.
7727 if (!Op.hasOneUse())
7729 SDNode *User = *Op.getNode()->use_begin();
7730 if ((User->getOpcode() != ISD::STORE ||
7731 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7732 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7733 (User->getOpcode() != ISD::BITCAST ||
7734 User->getValueType(0) != MVT::i32))
7736 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7737 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7740 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7743 if (VT == MVT::i32 || VT == MVT::i64) {
7744 // ExtractPS/pextrq works with constant index.
7745 if (isa<ConstantSDNode>(Op.getOperand(1)))
7751 /// Extract one bit from mask vector, like v16i1 or v8i1.
7752 /// AVX-512 feature.
7754 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7755 SDValue Vec = Op.getOperand(0);
7757 MVT VecVT = Vec.getSimpleValueType();
7758 SDValue Idx = Op.getOperand(1);
7759 MVT EltVT = Op.getSimpleValueType();
7761 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7763 // variable index can't be handled in mask registers,
7764 // extend vector to VR512
7765 if (!isa<ConstantSDNode>(Idx)) {
7766 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7767 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7768 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7769 ExtVT.getVectorElementType(), Ext, Idx);
7770 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7773 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7774 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7775 unsigned MaxSift = rc->getSize()*8 - 1;
7776 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7777 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7778 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7779 DAG.getConstant(MaxSift, MVT::i8));
7780 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7781 DAG.getIntPtrConstant(0));
7785 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7786 SelectionDAG &DAG) const {
7788 SDValue Vec = Op.getOperand(0);
7789 MVT VecVT = Vec.getSimpleValueType();
7790 SDValue Idx = Op.getOperand(1);
7792 if (Op.getSimpleValueType() == MVT::i1)
7793 return ExtractBitFromMaskVector(Op, DAG);
7795 if (!isa<ConstantSDNode>(Idx)) {
7796 if (VecVT.is512BitVector() ||
7797 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7798 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7801 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7802 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7803 MaskEltVT.getSizeInBits());
7805 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7806 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7807 getZeroVector(MaskVT, Subtarget, DAG, dl),
7808 Idx, DAG.getConstant(0, getPointerTy()));
7809 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7810 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7811 Perm, DAG.getConstant(0, getPointerTy()));
7816 // If this is a 256-bit vector result, first extract the 128-bit vector and
7817 // then extract the element from the 128-bit vector.
7818 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7820 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7821 // Get the 128-bit vector.
7822 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7823 MVT EltVT = VecVT.getVectorElementType();
7825 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7827 //if (IdxVal >= NumElems/2)
7828 // IdxVal -= NumElems/2;
7829 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7830 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7831 DAG.getConstant(IdxVal, MVT::i32));
7834 assert(VecVT.is128BitVector() && "Unexpected vector length");
7836 if (Subtarget->hasSSE41()) {
7837 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7842 MVT VT = Op.getSimpleValueType();
7843 // TODO: handle v16i8.
7844 if (VT.getSizeInBits() == 16) {
7845 SDValue Vec = Op.getOperand(0);
7846 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7848 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7849 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7850 DAG.getNode(ISD::BITCAST, dl,
7853 // Transform it so it match pextrw which produces a 32-bit result.
7854 MVT EltVT = MVT::i32;
7855 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7856 Op.getOperand(0), Op.getOperand(1));
7857 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7858 DAG.getValueType(VT));
7859 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7862 if (VT.getSizeInBits() == 32) {
7863 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7867 // SHUFPS the element to the lowest double word, then movss.
7868 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7869 MVT VVT = Op.getOperand(0).getSimpleValueType();
7870 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7871 DAG.getUNDEF(VVT), Mask);
7872 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7873 DAG.getIntPtrConstant(0));
7876 if (VT.getSizeInBits() == 64) {
7877 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7878 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7879 // to match extract_elt for f64.
7880 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7884 // UNPCKHPD the element to the lowest double word, then movsd.
7885 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7886 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7887 int Mask[2] = { 1, -1 };
7888 MVT VVT = Op.getOperand(0).getSimpleValueType();
7889 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7890 DAG.getUNDEF(VVT), Mask);
7891 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7892 DAG.getIntPtrConstant(0));
7898 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7899 MVT VT = Op.getSimpleValueType();
7900 MVT EltVT = VT.getVectorElementType();
7903 SDValue N0 = Op.getOperand(0);
7904 SDValue N1 = Op.getOperand(1);
7905 SDValue N2 = Op.getOperand(2);
7907 if (!VT.is128BitVector())
7910 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7911 isa<ConstantSDNode>(N2)) {
7913 if (VT == MVT::v8i16)
7914 Opc = X86ISD::PINSRW;
7915 else if (VT == MVT::v16i8)
7916 Opc = X86ISD::PINSRB;
7918 Opc = X86ISD::PINSRB;
7920 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7922 if (N1.getValueType() != MVT::i32)
7923 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7924 if (N2.getValueType() != MVT::i32)
7925 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7926 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7929 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7930 // Bits [7:6] of the constant are the source select. This will always be
7931 // zero here. The DAG Combiner may combine an extract_elt index into these
7932 // bits. For example (insert (extract, 3), 2) could be matched by putting
7933 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7934 // Bits [5:4] of the constant are the destination select. This is the
7935 // value of the incoming immediate.
7936 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7937 // combine either bitwise AND or insert of float 0.0 to set these bits.
7938 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7939 // Create this as a scalar to vector..
7940 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7941 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7944 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7945 // PINSR* works with constant index.
7952 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7953 MVT VT = Op.getSimpleValueType();
7954 MVT EltVT = VT.getVectorElementType();
7957 SDValue N0 = Op.getOperand(0);
7958 SDValue N1 = Op.getOperand(1);
7959 SDValue N2 = Op.getOperand(2);
7961 // If this is a 256-bit vector result, first extract the 128-bit vector,
7962 // insert the element into the extracted half and then place it back.
7963 if (VT.is256BitVector() || VT.is512BitVector()) {
7964 if (!isa<ConstantSDNode>(N2))
7967 // Get the desired 128-bit vector half.
7968 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7969 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7971 // Insert the element into the desired half.
7972 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7973 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7975 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7976 DAG.getConstant(IdxIn128, MVT::i32));
7978 // Insert the changed part back to the 256-bit vector
7979 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7982 if (Subtarget->hasSSE41())
7983 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7985 if (EltVT == MVT::i8)
7988 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7989 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7990 // as its second argument.
7991 if (N1.getValueType() != MVT::i32)
7992 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7993 if (N2.getValueType() != MVT::i32)
7994 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7995 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8000 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8002 MVT OpVT = Op.getSimpleValueType();
8004 // If this is a 256-bit vector result, first insert into a 128-bit
8005 // vector and then insert into the 256-bit vector.
8006 if (!OpVT.is128BitVector()) {
8007 // Insert into a 128-bit vector.
8008 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8009 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8010 OpVT.getVectorNumElements() / SizeFactor);
8012 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8014 // Insert the 128-bit vector.
8015 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8018 if (OpVT == MVT::v1i64 &&
8019 Op.getOperand(0).getValueType() == MVT::i64)
8020 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8022 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8023 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8024 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8025 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8028 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8029 // a simple subregister reference or explicit instructions to grab
8030 // upper bits of a vector.
8031 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8032 SelectionDAG &DAG) {
8034 SDValue In = Op.getOperand(0);
8035 SDValue Idx = Op.getOperand(1);
8036 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8037 MVT ResVT = Op.getSimpleValueType();
8038 MVT InVT = In.getSimpleValueType();
8040 if (Subtarget->hasFp256()) {
8041 if (ResVT.is128BitVector() &&
8042 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8043 isa<ConstantSDNode>(Idx)) {
8044 return Extract128BitVector(In, IdxVal, DAG, dl);
8046 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8047 isa<ConstantSDNode>(Idx)) {
8048 return Extract256BitVector(In, IdxVal, DAG, dl);
8054 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8055 // simple superregister reference or explicit instructions to insert
8056 // the upper bits of a vector.
8057 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8058 SelectionDAG &DAG) {
8059 if (Subtarget->hasFp256()) {
8060 SDLoc dl(Op.getNode());
8061 SDValue Vec = Op.getNode()->getOperand(0);
8062 SDValue SubVec = Op.getNode()->getOperand(1);
8063 SDValue Idx = Op.getNode()->getOperand(2);
8065 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8066 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8067 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8068 isa<ConstantSDNode>(Idx)) {
8069 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8070 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8073 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8074 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8075 isa<ConstantSDNode>(Idx)) {
8076 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8077 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8083 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8084 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8085 // one of the above mentioned nodes. It has to be wrapped because otherwise
8086 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8087 // be used to form addressing mode. These wrapped nodes will be selected
8090 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8091 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8093 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8095 unsigned char OpFlag = 0;
8096 unsigned WrapperKind = X86ISD::Wrapper;
8097 CodeModel::Model M = getTargetMachine().getCodeModel();
8099 if (Subtarget->isPICStyleRIPRel() &&
8100 (M == CodeModel::Small || M == CodeModel::Kernel))
8101 WrapperKind = X86ISD::WrapperRIP;
8102 else if (Subtarget->isPICStyleGOT())
8103 OpFlag = X86II::MO_GOTOFF;
8104 else if (Subtarget->isPICStyleStubPIC())
8105 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8107 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8109 CP->getOffset(), OpFlag);
8111 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8112 // With PIC, the address is actually $g + Offset.
8114 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8115 DAG.getNode(X86ISD::GlobalBaseReg,
8116 SDLoc(), getPointerTy()),
8123 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8124 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8126 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8128 unsigned char OpFlag = 0;
8129 unsigned WrapperKind = X86ISD::Wrapper;
8130 CodeModel::Model M = getTargetMachine().getCodeModel();
8132 if (Subtarget->isPICStyleRIPRel() &&
8133 (M == CodeModel::Small || M == CodeModel::Kernel))
8134 WrapperKind = X86ISD::WrapperRIP;
8135 else if (Subtarget->isPICStyleGOT())
8136 OpFlag = X86II::MO_GOTOFF;
8137 else if (Subtarget->isPICStyleStubPIC())
8138 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8140 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8143 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8145 // With PIC, the address is actually $g + Offset.
8147 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8148 DAG.getNode(X86ISD::GlobalBaseReg,
8149 SDLoc(), getPointerTy()),
8156 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8157 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8159 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8161 unsigned char OpFlag = 0;
8162 unsigned WrapperKind = X86ISD::Wrapper;
8163 CodeModel::Model M = getTargetMachine().getCodeModel();
8165 if (Subtarget->isPICStyleRIPRel() &&
8166 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8167 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8168 OpFlag = X86II::MO_GOTPCREL;
8169 WrapperKind = X86ISD::WrapperRIP;
8170 } else if (Subtarget->isPICStyleGOT()) {
8171 OpFlag = X86II::MO_GOT;
8172 } else if (Subtarget->isPICStyleStubPIC()) {
8173 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8174 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8175 OpFlag = X86II::MO_DARWIN_NONLAZY;
8178 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8181 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8183 // With PIC, the address is actually $g + Offset.
8184 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8185 !Subtarget->is64Bit()) {
8186 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8187 DAG.getNode(X86ISD::GlobalBaseReg,
8188 SDLoc(), getPointerTy()),
8192 // For symbols that require a load from a stub to get the address, emit the
8194 if (isGlobalStubReference(OpFlag))
8195 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8196 MachinePointerInfo::getGOT(), false, false, false, 0);
8202 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8203 // Create the TargetBlockAddressAddress node.
8204 unsigned char OpFlags =
8205 Subtarget->ClassifyBlockAddressReference();
8206 CodeModel::Model M = getTargetMachine().getCodeModel();
8207 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8208 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8210 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8213 if (Subtarget->isPICStyleRIPRel() &&
8214 (M == CodeModel::Small || M == CodeModel::Kernel))
8215 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8217 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8219 // With PIC, the address is actually $g + Offset.
8220 if (isGlobalRelativeToPICBase(OpFlags)) {
8221 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8222 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8230 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8231 int64_t Offset, SelectionDAG &DAG) const {
8232 // Create the TargetGlobalAddress node, folding in the constant
8233 // offset if it is legal.
8234 unsigned char OpFlags =
8235 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8236 CodeModel::Model M = getTargetMachine().getCodeModel();
8238 if (OpFlags == X86II::MO_NO_FLAG &&
8239 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8240 // A direct static reference to a global.
8241 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8244 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8247 if (Subtarget->isPICStyleRIPRel() &&
8248 (M == CodeModel::Small || M == CodeModel::Kernel))
8249 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8251 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8253 // With PIC, the address is actually $g + Offset.
8254 if (isGlobalRelativeToPICBase(OpFlags)) {
8255 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8256 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8260 // For globals that require a load from a stub to get the address, emit the
8262 if (isGlobalStubReference(OpFlags))
8263 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8264 MachinePointerInfo::getGOT(), false, false, false, 0);
8266 // If there was a non-zero offset that we didn't fold, create an explicit
8269 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8270 DAG.getConstant(Offset, getPointerTy()));
8276 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8277 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8278 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8279 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8283 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8284 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8285 unsigned char OperandFlags, bool LocalDynamic = false) {
8286 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8287 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8289 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8290 GA->getValueType(0),
8294 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8298 SDValue Ops[] = { Chain, TGA, *InFlag };
8299 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8301 SDValue Ops[] = { Chain, TGA };
8302 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8305 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8306 MFI->setAdjustsStack(true);
8308 SDValue Flag = Chain.getValue(1);
8309 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8312 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8314 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8317 SDLoc dl(GA); // ? function entry point might be better
8318 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8319 DAG.getNode(X86ISD::GlobalBaseReg,
8320 SDLoc(), PtrVT), InFlag);
8321 InFlag = Chain.getValue(1);
8323 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8326 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8328 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8330 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8331 X86::RAX, X86II::MO_TLSGD);
8334 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8340 // Get the start address of the TLS block for this module.
8341 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8342 .getInfo<X86MachineFunctionInfo>();
8343 MFI->incNumLocalDynamicTLSAccesses();
8347 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8348 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8351 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8352 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8353 InFlag = Chain.getValue(1);
8354 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8355 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8358 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8362 unsigned char OperandFlags = X86II::MO_DTPOFF;
8363 unsigned WrapperKind = X86ISD::Wrapper;
8364 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8365 GA->getValueType(0),
8366 GA->getOffset(), OperandFlags);
8367 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8369 // Add x@dtpoff with the base.
8370 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8373 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8374 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8375 const EVT PtrVT, TLSModel::Model model,
8376 bool is64Bit, bool isPIC) {
8379 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8380 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8381 is64Bit ? 257 : 256));
8383 SDValue ThreadPointer =
8384 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8385 MachinePointerInfo(Ptr), false, false, false, 0);
8387 unsigned char OperandFlags = 0;
8388 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8390 unsigned WrapperKind = X86ISD::Wrapper;
8391 if (model == TLSModel::LocalExec) {
8392 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8393 } else if (model == TLSModel::InitialExec) {
8395 OperandFlags = X86II::MO_GOTTPOFF;
8396 WrapperKind = X86ISD::WrapperRIP;
8398 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8401 llvm_unreachable("Unexpected model");
8404 // emit "addl x@ntpoff,%eax" (local exec)
8405 // or "addl x@indntpoff,%eax" (initial exec)
8406 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8408 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8409 GA->getOffset(), OperandFlags);
8410 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8412 if (model == TLSModel::InitialExec) {
8413 if (isPIC && !is64Bit) {
8414 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8415 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8419 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8420 MachinePointerInfo::getGOT(), false, false, false, 0);
8423 // The address of the thread local variable is the add of the thread
8424 // pointer with the offset of the variable.
8425 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8429 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8431 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8432 const GlobalValue *GV = GA->getGlobal();
8434 if (Subtarget->isTargetELF()) {
8435 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8438 case TLSModel::GeneralDynamic:
8439 if (Subtarget->is64Bit())
8440 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8441 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8442 case TLSModel::LocalDynamic:
8443 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8444 Subtarget->is64Bit());
8445 case TLSModel::InitialExec:
8446 case TLSModel::LocalExec:
8447 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8448 Subtarget->is64Bit(),
8449 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8451 llvm_unreachable("Unknown TLS model.");
8454 if (Subtarget->isTargetDarwin()) {
8455 // Darwin only has one model of TLS. Lower to that.
8456 unsigned char OpFlag = 0;
8457 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8458 X86ISD::WrapperRIP : X86ISD::Wrapper;
8460 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8462 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8463 !Subtarget->is64Bit();
8465 OpFlag = X86II::MO_TLVP_PIC_BASE;
8467 OpFlag = X86II::MO_TLVP;
8469 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8470 GA->getValueType(0),
8471 GA->getOffset(), OpFlag);
8472 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8474 // With PIC32, the address is actually $g + Offset.
8476 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8477 DAG.getNode(X86ISD::GlobalBaseReg,
8478 SDLoc(), getPointerTy()),
8481 // Lowering the machine isd will make sure everything is in the right
8483 SDValue Chain = DAG.getEntryNode();
8484 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8485 SDValue Args[] = { Chain, Offset };
8486 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8488 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8489 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8490 MFI->setAdjustsStack(true);
8492 // And our return value (tls address) is in the standard call return value
8494 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8495 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8499 if (Subtarget->isTargetKnownWindowsMSVC() ||
8500 Subtarget->isTargetWindowsGNU()) {
8501 // Just use the implicit TLS architecture
8502 // Need to generate someting similar to:
8503 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8505 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8506 // mov rcx, qword [rdx+rcx*8]
8507 // mov eax, .tls$:tlsvar
8508 // [rax+rcx] contains the address
8509 // Windows 64bit: gs:0x58
8510 // Windows 32bit: fs:__tls_array
8512 // If GV is an alias then use the aliasee for determining
8513 // thread-localness.
8514 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8515 GV = GA->getAliasedGlobal();
8517 SDValue Chain = DAG.getEntryNode();
8519 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8520 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8521 // use its literal value of 0x2C.
8522 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8523 ? Type::getInt8PtrTy(*DAG.getContext(),
8525 : Type::getInt32PtrTy(*DAG.getContext(),
8529 Subtarget->is64Bit()
8530 ? DAG.getIntPtrConstant(0x58)
8531 : (Subtarget->isTargetWindowsGNU()
8532 ? DAG.getIntPtrConstant(0x2C)
8533 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8535 SDValue ThreadPointer =
8536 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8537 MachinePointerInfo(Ptr), false, false, false, 0);
8539 // Load the _tls_index variable
8540 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8541 if (Subtarget->is64Bit())
8542 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8543 IDX, MachinePointerInfo(), MVT::i32,
8546 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8547 false, false, false, 0);
8549 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8551 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8553 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8554 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8555 false, false, false, 0);
8557 // Get the offset of start of .tls section
8558 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8559 GA->getValueType(0),
8560 GA->getOffset(), X86II::MO_SECREL);
8561 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8563 // The address of the thread local variable is the add of the thread
8564 // pointer with the offset of the variable.
8565 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8568 llvm_unreachable("TLS not implemented for this target.");
8571 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8572 /// and take a 2 x i32 value to shift plus a shift amount.
8573 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8574 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8575 MVT VT = Op.getSimpleValueType();
8576 unsigned VTBits = VT.getSizeInBits();
8578 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8579 SDValue ShOpLo = Op.getOperand(0);
8580 SDValue ShOpHi = Op.getOperand(1);
8581 SDValue ShAmt = Op.getOperand(2);
8582 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8583 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8585 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8586 DAG.getConstant(VTBits - 1, MVT::i8));
8587 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8588 DAG.getConstant(VTBits - 1, MVT::i8))
8589 : DAG.getConstant(0, VT);
8592 if (Op.getOpcode() == ISD::SHL_PARTS) {
8593 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8594 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8596 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8597 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8600 // If the shift amount is larger or equal than the width of a part we can't
8601 // rely on the results of shld/shrd. Insert a test and select the appropriate
8602 // values for large shift amounts.
8603 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8604 DAG.getConstant(VTBits, MVT::i8));
8605 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8606 AndNode, DAG.getConstant(0, MVT::i8));
8609 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8610 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8611 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8613 if (Op.getOpcode() == ISD::SHL_PARTS) {
8614 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8615 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8617 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8618 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8621 SDValue Ops[2] = { Lo, Hi };
8622 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8625 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8626 SelectionDAG &DAG) const {
8627 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8629 if (SrcVT.isVector())
8632 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8633 "Unknown SINT_TO_FP to lower!");
8635 // These are really Legal; return the operand so the caller accepts it as
8637 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8639 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8640 Subtarget->is64Bit()) {
8645 unsigned Size = SrcVT.getSizeInBits()/8;
8646 MachineFunction &MF = DAG.getMachineFunction();
8647 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8648 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8649 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8651 MachinePointerInfo::getFixedStack(SSFI),
8653 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8656 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8658 SelectionDAG &DAG) const {
8662 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8664 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8666 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8668 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8670 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8671 MachineMemOperand *MMO;
8673 int SSFI = FI->getIndex();
8675 DAG.getMachineFunction()
8676 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8677 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8679 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8680 StackSlot = StackSlot.getOperand(1);
8682 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8683 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8685 Tys, Ops, array_lengthof(Ops),
8689 Chain = Result.getValue(1);
8690 SDValue InFlag = Result.getValue(2);
8692 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8693 // shouldn't be necessary except that RFP cannot be live across
8694 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8695 MachineFunction &MF = DAG.getMachineFunction();
8696 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8697 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8698 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8699 Tys = DAG.getVTList(MVT::Other);
8701 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8703 MachineMemOperand *MMO =
8704 DAG.getMachineFunction()
8705 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8706 MachineMemOperand::MOStore, SSFISize, SSFISize);
8708 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8709 Ops, array_lengthof(Ops),
8710 Op.getValueType(), MMO);
8711 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8712 MachinePointerInfo::getFixedStack(SSFI),
8713 false, false, false, 0);
8719 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8720 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8721 SelectionDAG &DAG) const {
8722 // This algorithm is not obvious. Here it is what we're trying to output:
8725 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8726 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8730 pshufd $0x4e, %xmm0, %xmm1
8736 LLVMContext *Context = DAG.getContext();
8738 // Build some magic constants.
8739 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8740 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8741 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8743 SmallVector<Constant*,2> CV1;
8745 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8746 APInt(64, 0x4330000000000000ULL))));
8748 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8749 APInt(64, 0x4530000000000000ULL))));
8750 Constant *C1 = ConstantVector::get(CV1);
8751 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8753 // Load the 64-bit value into an XMM register.
8754 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8756 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8757 MachinePointerInfo::getConstantPool(),
8758 false, false, false, 16);
8759 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8760 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8763 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8764 MachinePointerInfo::getConstantPool(),
8765 false, false, false, 16);
8766 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8767 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8770 if (Subtarget->hasSSE3()) {
8771 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8772 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8774 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8775 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8777 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8778 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8782 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8783 DAG.getIntPtrConstant(0));
8786 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8787 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8788 SelectionDAG &DAG) const {
8790 // FP constant to bias correct the final result.
8791 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8794 // Load the 32-bit value into an XMM register.
8795 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8798 // Zero out the upper parts of the register.
8799 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8801 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8802 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8803 DAG.getIntPtrConstant(0));
8805 // Or the load with the bias.
8806 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8807 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8808 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8810 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8811 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8812 MVT::v2f64, Bias)));
8813 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8814 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8815 DAG.getIntPtrConstant(0));
8817 // Subtract the bias.
8818 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8820 // Handle final rounding.
8821 EVT DestVT = Op.getValueType();
8823 if (DestVT.bitsLT(MVT::f64))
8824 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8825 DAG.getIntPtrConstant(0));
8826 if (DestVT.bitsGT(MVT::f64))
8827 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8829 // Handle final rounding.
8833 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8834 SelectionDAG &DAG) const {
8835 SDValue N0 = Op.getOperand(0);
8836 MVT SVT = N0.getSimpleValueType();
8839 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8840 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8841 "Custom UINT_TO_FP is not supported!");
8843 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8844 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8845 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8848 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8849 SelectionDAG &DAG) const {
8850 SDValue N0 = Op.getOperand(0);
8853 if (Op.getValueType().isVector())
8854 return lowerUINT_TO_FP_vec(Op, DAG);
8856 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8857 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8858 // the optimization here.
8859 if (DAG.SignBitIsZero(N0))
8860 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8862 MVT SrcVT = N0.getSimpleValueType();
8863 MVT DstVT = Op.getSimpleValueType();
8864 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8865 return LowerUINT_TO_FP_i64(Op, DAG);
8866 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8867 return LowerUINT_TO_FP_i32(Op, DAG);
8868 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8871 // Make a 64-bit buffer, and use it to build an FILD.
8872 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8873 if (SrcVT == MVT::i32) {
8874 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8875 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8876 getPointerTy(), StackSlot, WordOff);
8877 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8878 StackSlot, MachinePointerInfo(),
8880 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8881 OffsetSlot, MachinePointerInfo(),
8883 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8887 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8888 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8889 StackSlot, MachinePointerInfo(),
8891 // For i64 source, we need to add the appropriate power of 2 if the input
8892 // was negative. This is the same as the optimization in
8893 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8894 // we must be careful to do the computation in x87 extended precision, not
8895 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8896 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8897 MachineMemOperand *MMO =
8898 DAG.getMachineFunction()
8899 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8900 MachineMemOperand::MOLoad, 8, 8);
8902 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8903 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8904 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8905 array_lengthof(Ops), MVT::i64, MMO);
8907 APInt FF(32, 0x5F800000ULL);
8909 // Check whether the sign bit is set.
8910 SDValue SignSet = DAG.getSetCC(dl,
8911 getSetCCResultType(*DAG.getContext(), MVT::i64),
8912 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8915 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8916 SDValue FudgePtr = DAG.getConstantPool(
8917 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8920 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8921 SDValue Zero = DAG.getIntPtrConstant(0);
8922 SDValue Four = DAG.getIntPtrConstant(4);
8923 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8925 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8927 // Load the value out, extending it from f32 to f80.
8928 // FIXME: Avoid the extend by constructing the right constant pool?
8929 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8930 FudgePtr, MachinePointerInfo::getConstantPool(),
8931 MVT::f32, false, false, 4);
8932 // Extend everything to 80 bits to force it to be done on x87.
8933 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8934 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8937 std::pair<SDValue,SDValue>
8938 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8939 bool IsSigned, bool IsReplace) const {
8942 EVT DstTy = Op.getValueType();
8944 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8945 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8949 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8950 DstTy.getSimpleVT() >= MVT::i16 &&
8951 "Unknown FP_TO_INT to lower!");
8953 // These are really Legal.
8954 if (DstTy == MVT::i32 &&
8955 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8956 return std::make_pair(SDValue(), SDValue());
8957 if (Subtarget->is64Bit() &&
8958 DstTy == MVT::i64 &&
8959 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8960 return std::make_pair(SDValue(), SDValue());
8962 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8963 // stack slot, or into the FTOL runtime function.
8964 MachineFunction &MF = DAG.getMachineFunction();
8965 unsigned MemSize = DstTy.getSizeInBits()/8;
8966 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8967 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8970 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8971 Opc = X86ISD::WIN_FTOL;
8973 switch (DstTy.getSimpleVT().SimpleTy) {
8974 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8975 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8976 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8977 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8980 SDValue Chain = DAG.getEntryNode();
8981 SDValue Value = Op.getOperand(0);
8982 EVT TheVT = Op.getOperand(0).getValueType();
8983 // FIXME This causes a redundant load/store if the SSE-class value is already
8984 // in memory, such as if it is on the callstack.
8985 if (isScalarFPTypeInSSEReg(TheVT)) {
8986 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8987 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8988 MachinePointerInfo::getFixedStack(SSFI),
8990 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8992 Chain, StackSlot, DAG.getValueType(TheVT)
8995 MachineMemOperand *MMO =
8996 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8997 MachineMemOperand::MOLoad, MemSize, MemSize);
8998 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8999 array_lengthof(Ops), DstTy, MMO);
9000 Chain = Value.getValue(1);
9001 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9002 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9005 MachineMemOperand *MMO =
9006 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9007 MachineMemOperand::MOStore, MemSize, MemSize);
9009 if (Opc != X86ISD::WIN_FTOL) {
9010 // Build the FP_TO_INT*_IN_MEM
9011 SDValue Ops[] = { Chain, Value, StackSlot };
9012 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9013 Ops, array_lengthof(Ops), DstTy,
9015 return std::make_pair(FIST, StackSlot);
9017 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9018 DAG.getVTList(MVT::Other, MVT::Glue),
9020 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9021 MVT::i32, ftol.getValue(1));
9022 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9023 MVT::i32, eax.getValue(2));
9024 SDValue Ops[] = { eax, edx };
9025 SDValue pair = IsReplace
9026 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9027 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9028 return std::make_pair(pair, SDValue());
9032 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9033 const X86Subtarget *Subtarget) {
9034 MVT VT = Op->getSimpleValueType(0);
9035 SDValue In = Op->getOperand(0);
9036 MVT InVT = In.getSimpleValueType();
9039 // Optimize vectors in AVX mode:
9042 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9043 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9044 // Concat upper and lower parts.
9047 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9048 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9049 // Concat upper and lower parts.
9052 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9053 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9054 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9057 if (Subtarget->hasInt256())
9058 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9060 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9061 SDValue Undef = DAG.getUNDEF(InVT);
9062 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9063 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9064 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9066 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9067 VT.getVectorNumElements()/2);
9069 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9070 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9072 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9075 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9076 SelectionDAG &DAG) {
9077 MVT VT = Op->getSimpleValueType(0);
9078 SDValue In = Op->getOperand(0);
9079 MVT InVT = In.getSimpleValueType();
9081 unsigned int NumElts = VT.getVectorNumElements();
9082 if (NumElts != 8 && NumElts != 16)
9085 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9086 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9088 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9089 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9090 // Now we have only mask extension
9091 assert(InVT.getVectorElementType() == MVT::i1);
9092 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9093 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9094 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9095 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9096 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9097 MachinePointerInfo::getConstantPool(),
9098 false, false, false, Alignment);
9100 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9101 if (VT.is512BitVector())
9103 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9106 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9107 SelectionDAG &DAG) {
9108 if (Subtarget->hasFp256()) {
9109 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9117 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9118 SelectionDAG &DAG) {
9120 MVT VT = Op.getSimpleValueType();
9121 SDValue In = Op.getOperand(0);
9122 MVT SVT = In.getSimpleValueType();
9124 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9125 return LowerZERO_EXTEND_AVX512(Op, DAG);
9127 if (Subtarget->hasFp256()) {
9128 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9133 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9134 VT.getVectorNumElements() != SVT.getVectorNumElements());
9138 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9140 MVT VT = Op.getSimpleValueType();
9141 SDValue In = Op.getOperand(0);
9142 MVT InVT = In.getSimpleValueType();
9144 if (VT == MVT::i1) {
9145 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9146 "Invalid scalar TRUNCATE operation");
9147 if (InVT == MVT::i32)
9149 if (InVT.getSizeInBits() == 64)
9150 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9151 else if (InVT.getSizeInBits() < 32)
9152 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9153 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9155 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9156 "Invalid TRUNCATE operation");
9158 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9159 if (VT.getVectorElementType().getSizeInBits() >=8)
9160 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9162 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9163 unsigned NumElts = InVT.getVectorNumElements();
9164 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9165 if (InVT.getSizeInBits() < 512) {
9166 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9167 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9171 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9172 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9173 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9174 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9175 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9176 MachinePointerInfo::getConstantPool(),
9177 false, false, false, Alignment);
9178 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9179 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9180 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9183 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9184 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9185 if (Subtarget->hasInt256()) {
9186 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9187 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9188 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9190 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9191 DAG.getIntPtrConstant(0));
9194 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9195 DAG.getIntPtrConstant(0));
9196 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9197 DAG.getIntPtrConstant(2));
9198 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9199 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9200 static const int ShufMask[] = {0, 2, 4, 6};
9201 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9204 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9205 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9206 if (Subtarget->hasInt256()) {
9207 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9209 SmallVector<SDValue,32> pshufbMask;
9210 for (unsigned i = 0; i < 2; ++i) {
9211 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9212 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9213 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9214 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9215 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9216 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9217 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9218 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9219 for (unsigned j = 0; j < 8; ++j)
9220 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9222 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9223 &pshufbMask[0], 32);
9224 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9225 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9227 static const int ShufMask[] = {0, 2, -1, -1};
9228 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9230 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9231 DAG.getIntPtrConstant(0));
9232 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9235 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9236 DAG.getIntPtrConstant(0));
9238 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9239 DAG.getIntPtrConstant(4));
9241 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9242 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9245 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9246 -1, -1, -1, -1, -1, -1, -1, -1};
9248 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9249 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9250 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9252 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9253 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9255 // The MOVLHPS Mask:
9256 static const int ShufMask2[] = {0, 1, 4, 5};
9257 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9258 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9261 // Handle truncation of V256 to V128 using shuffles.
9262 if (!VT.is128BitVector() || !InVT.is256BitVector())
9265 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9267 unsigned NumElems = VT.getVectorNumElements();
9268 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9270 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9271 // Prepare truncation shuffle mask
9272 for (unsigned i = 0; i != NumElems; ++i)
9274 SDValue V = DAG.getVectorShuffle(NVT, DL,
9275 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9276 DAG.getUNDEF(NVT), &MaskVec[0]);
9277 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9278 DAG.getIntPtrConstant(0));
9281 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9282 SelectionDAG &DAG) const {
9283 assert(!Op.getSimpleValueType().isVector());
9285 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9286 /*IsSigned=*/ true, /*IsReplace=*/ false);
9287 SDValue FIST = Vals.first, StackSlot = Vals.second;
9288 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9289 if (FIST.getNode() == 0) return Op;
9291 if (StackSlot.getNode())
9293 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9294 FIST, StackSlot, MachinePointerInfo(),
9295 false, false, false, 0);
9297 // The node is the result.
9301 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9302 SelectionDAG &DAG) const {
9303 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9304 /*IsSigned=*/ false, /*IsReplace=*/ false);
9305 SDValue FIST = Vals.first, StackSlot = Vals.second;
9306 assert(FIST.getNode() && "Unexpected failure");
9308 if (StackSlot.getNode())
9310 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9311 FIST, StackSlot, MachinePointerInfo(),
9312 false, false, false, 0);
9314 // The node is the result.
9318 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9320 MVT VT = Op.getSimpleValueType();
9321 SDValue In = Op.getOperand(0);
9322 MVT SVT = In.getSimpleValueType();
9324 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9326 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9327 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9328 In, DAG.getUNDEF(SVT)));
9331 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9332 LLVMContext *Context = DAG.getContext();
9334 MVT VT = Op.getSimpleValueType();
9336 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9337 if (VT.isVector()) {
9338 EltVT = VT.getVectorElementType();
9339 NumElts = VT.getVectorNumElements();
9342 if (EltVT == MVT::f64)
9343 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9344 APInt(64, ~(1ULL << 63))));
9346 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9347 APInt(32, ~(1U << 31))));
9348 C = ConstantVector::getSplat(NumElts, C);
9349 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9350 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9351 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9352 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9353 MachinePointerInfo::getConstantPool(),
9354 false, false, false, Alignment);
9355 if (VT.isVector()) {
9356 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9357 return DAG.getNode(ISD::BITCAST, dl, VT,
9358 DAG.getNode(ISD::AND, dl, ANDVT,
9359 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9361 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9363 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9366 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9367 LLVMContext *Context = DAG.getContext();
9369 MVT VT = Op.getSimpleValueType();
9371 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9372 if (VT.isVector()) {
9373 EltVT = VT.getVectorElementType();
9374 NumElts = VT.getVectorNumElements();
9377 if (EltVT == MVT::f64)
9378 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9379 APInt(64, 1ULL << 63)));
9381 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9382 APInt(32, 1U << 31)));
9383 C = ConstantVector::getSplat(NumElts, C);
9384 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9385 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9386 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9387 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9388 MachinePointerInfo::getConstantPool(),
9389 false, false, false, Alignment);
9390 if (VT.isVector()) {
9391 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9392 return DAG.getNode(ISD::BITCAST, dl, VT,
9393 DAG.getNode(ISD::XOR, dl, XORVT,
9394 DAG.getNode(ISD::BITCAST, dl, XORVT,
9396 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9399 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9402 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9403 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9404 LLVMContext *Context = DAG.getContext();
9405 SDValue Op0 = Op.getOperand(0);
9406 SDValue Op1 = Op.getOperand(1);
9408 MVT VT = Op.getSimpleValueType();
9409 MVT SrcVT = Op1.getSimpleValueType();
9411 // If second operand is smaller, extend it first.
9412 if (SrcVT.bitsLT(VT)) {
9413 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9416 // And if it is bigger, shrink it first.
9417 if (SrcVT.bitsGT(VT)) {
9418 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9422 // At this point the operands and the result should have the same
9423 // type, and that won't be f80 since that is not custom lowered.
9425 // First get the sign bit of second operand.
9426 SmallVector<Constant*,4> CV;
9427 if (SrcVT == MVT::f64) {
9428 const fltSemantics &Sem = APFloat::IEEEdouble;
9429 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9430 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9432 const fltSemantics &Sem = APFloat::IEEEsingle;
9433 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9434 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9435 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9436 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9438 Constant *C = ConstantVector::get(CV);
9439 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9440 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9441 MachinePointerInfo::getConstantPool(),
9442 false, false, false, 16);
9443 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9445 // Shift sign bit right or left if the two operands have different types.
9446 if (SrcVT.bitsGT(VT)) {
9447 // Op0 is MVT::f32, Op1 is MVT::f64.
9448 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9449 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9450 DAG.getConstant(32, MVT::i32));
9451 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9452 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9453 DAG.getIntPtrConstant(0));
9456 // Clear first operand sign bit.
9458 if (VT == MVT::f64) {
9459 const fltSemantics &Sem = APFloat::IEEEdouble;
9460 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9461 APInt(64, ~(1ULL << 63)))));
9462 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9464 const fltSemantics &Sem = APFloat::IEEEsingle;
9465 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9466 APInt(32, ~(1U << 31)))));
9467 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9468 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9469 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9471 C = ConstantVector::get(CV);
9472 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9473 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9474 MachinePointerInfo::getConstantPool(),
9475 false, false, false, 16);
9476 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9478 // Or the value with the sign bit.
9479 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9482 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9483 SDValue N0 = Op.getOperand(0);
9485 MVT VT = Op.getSimpleValueType();
9487 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9488 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9489 DAG.getConstant(1, VT));
9490 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9493 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9495 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9496 SelectionDAG &DAG) {
9497 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9499 if (!Subtarget->hasSSE41())
9502 if (!Op->hasOneUse())
9505 SDNode *N = Op.getNode();
9508 SmallVector<SDValue, 8> Opnds;
9509 DenseMap<SDValue, unsigned> VecInMap;
9510 SmallVector<SDValue, 8> VecIns;
9511 EVT VT = MVT::Other;
9513 // Recognize a special case where a vector is casted into wide integer to
9515 Opnds.push_back(N->getOperand(0));
9516 Opnds.push_back(N->getOperand(1));
9518 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9519 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9520 // BFS traverse all OR'd operands.
9521 if (I->getOpcode() == ISD::OR) {
9522 Opnds.push_back(I->getOperand(0));
9523 Opnds.push_back(I->getOperand(1));
9524 // Re-evaluate the number of nodes to be traversed.
9525 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9529 // Quit if a non-EXTRACT_VECTOR_ELT
9530 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9533 // Quit if without a constant index.
9534 SDValue Idx = I->getOperand(1);
9535 if (!isa<ConstantSDNode>(Idx))
9538 SDValue ExtractedFromVec = I->getOperand(0);
9539 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9540 if (M == VecInMap.end()) {
9541 VT = ExtractedFromVec.getValueType();
9542 // Quit if not 128/256-bit vector.
9543 if (!VT.is128BitVector() && !VT.is256BitVector())
9545 // Quit if not the same type.
9546 if (VecInMap.begin() != VecInMap.end() &&
9547 VT != VecInMap.begin()->first.getValueType())
9549 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9550 VecIns.push_back(ExtractedFromVec);
9552 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9555 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9556 "Not extracted from 128-/256-bit vector.");
9558 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9560 for (DenseMap<SDValue, unsigned>::const_iterator
9561 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9562 // Quit if not all elements are used.
9563 if (I->second != FullMask)
9567 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9569 // Cast all vectors into TestVT for PTEST.
9570 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9571 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9573 // If more than one full vectors are evaluated, OR them first before PTEST.
9574 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9575 // Each iteration will OR 2 nodes and append the result until there is only
9576 // 1 node left, i.e. the final OR'd value of all vectors.
9577 SDValue LHS = VecIns[Slot];
9578 SDValue RHS = VecIns[Slot + 1];
9579 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9582 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9583 VecIns.back(), VecIns.back());
9586 /// Emit nodes that will be selected as "test Op0,Op0", or something
9588 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9589 SelectionDAG &DAG) const {
9592 if (Op.getValueType() == MVT::i1)
9593 // KORTEST instruction should be selected
9594 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9595 DAG.getConstant(0, Op.getValueType()));
9597 // CF and OF aren't always set the way we want. Determine which
9598 // of these we need.
9599 bool NeedCF = false;
9600 bool NeedOF = false;
9603 case X86::COND_A: case X86::COND_AE:
9604 case X86::COND_B: case X86::COND_BE:
9607 case X86::COND_G: case X86::COND_GE:
9608 case X86::COND_L: case X86::COND_LE:
9609 case X86::COND_O: case X86::COND_NO:
9613 // See if we can use the EFLAGS value from the operand instead of
9614 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9615 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9616 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9617 // Emit a CMP with 0, which is the TEST pattern.
9618 //if (Op.getValueType() == MVT::i1)
9619 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9620 // DAG.getConstant(0, MVT::i1));
9621 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9622 DAG.getConstant(0, Op.getValueType()));
9624 unsigned Opcode = 0;
9625 unsigned NumOperands = 0;
9627 // Truncate operations may prevent the merge of the SETCC instruction
9628 // and the arithmetic instruction before it. Attempt to truncate the operands
9629 // of the arithmetic instruction and use a reduced bit-width instruction.
9630 bool NeedTruncation = false;
9631 SDValue ArithOp = Op;
9632 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9633 SDValue Arith = Op->getOperand(0);
9634 // Both the trunc and the arithmetic op need to have one user each.
9635 if (Arith->hasOneUse())
9636 switch (Arith.getOpcode()) {
9643 NeedTruncation = true;
9649 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9650 // which may be the result of a CAST. We use the variable 'Op', which is the
9651 // non-casted variable when we check for possible users.
9652 switch (ArithOp.getOpcode()) {
9654 // Due to an isel shortcoming, be conservative if this add is likely to be
9655 // selected as part of a load-modify-store instruction. When the root node
9656 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9657 // uses of other nodes in the match, such as the ADD in this case. This
9658 // leads to the ADD being left around and reselected, with the result being
9659 // two adds in the output. Alas, even if none our users are stores, that
9660 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9661 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9662 // climbing the DAG back to the root, and it doesn't seem to be worth the
9664 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9665 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9666 if (UI->getOpcode() != ISD::CopyToReg &&
9667 UI->getOpcode() != ISD::SETCC &&
9668 UI->getOpcode() != ISD::STORE)
9671 if (ConstantSDNode *C =
9672 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9673 // An add of one will be selected as an INC.
9674 if (C->getAPIntValue() == 1) {
9675 Opcode = X86ISD::INC;
9680 // An add of negative one (subtract of one) will be selected as a DEC.
9681 if (C->getAPIntValue().isAllOnesValue()) {
9682 Opcode = X86ISD::DEC;
9688 // Otherwise use a regular EFLAGS-setting add.
9689 Opcode = X86ISD::ADD;
9693 // If the primary and result isn't used, don't bother using X86ISD::AND,
9694 // because a TEST instruction will be better.
9695 bool NonFlagUse = false;
9696 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9697 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9699 unsigned UOpNo = UI.getOperandNo();
9700 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9701 // Look pass truncate.
9702 UOpNo = User->use_begin().getOperandNo();
9703 User = *User->use_begin();
9706 if (User->getOpcode() != ISD::BRCOND &&
9707 User->getOpcode() != ISD::SETCC &&
9708 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9721 // Due to the ISEL shortcoming noted above, be conservative if this op is
9722 // likely to be selected as part of a load-modify-store instruction.
9723 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9724 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9725 if (UI->getOpcode() == ISD::STORE)
9728 // Otherwise use a regular EFLAGS-setting instruction.
9729 switch (ArithOp.getOpcode()) {
9730 default: llvm_unreachable("unexpected operator!");
9731 case ISD::SUB: Opcode = X86ISD::SUB; break;
9732 case ISD::XOR: Opcode = X86ISD::XOR; break;
9733 case ISD::AND: Opcode = X86ISD::AND; break;
9735 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9736 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9737 if (EFLAGS.getNode())
9740 Opcode = X86ISD::OR;
9754 return SDValue(Op.getNode(), 1);
9760 // If we found that truncation is beneficial, perform the truncation and
9762 if (NeedTruncation) {
9763 EVT VT = Op.getValueType();
9764 SDValue WideVal = Op->getOperand(0);
9765 EVT WideVT = WideVal.getValueType();
9766 unsigned ConvertedOp = 0;
9767 // Use a target machine opcode to prevent further DAGCombine
9768 // optimizations that may separate the arithmetic operations
9769 // from the setcc node.
9770 switch (WideVal.getOpcode()) {
9772 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9773 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9774 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9775 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9776 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9780 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9781 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9782 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9783 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9784 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9790 // Emit a CMP with 0, which is the TEST pattern.
9791 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9792 DAG.getConstant(0, Op.getValueType()));
9794 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9795 SmallVector<SDValue, 4> Ops;
9796 for (unsigned i = 0; i != NumOperands; ++i)
9797 Ops.push_back(Op.getOperand(i));
9799 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9800 DAG.ReplaceAllUsesWith(Op, New);
9801 return SDValue(New.getNode(), 1);
9804 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9806 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9807 SelectionDAG &DAG) const {
9809 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9810 if (C->getAPIntValue() == 0)
9811 return EmitTest(Op0, X86CC, DAG);
9813 if (Op0.getValueType() == MVT::i1)
9814 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
9817 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9818 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9819 // Do the comparison at i32 if it's smaller, besides the Atom case.
9820 // This avoids subregister aliasing issues. Keep the smaller reference
9821 // if we're optimizing for size, however, as that'll allow better folding
9822 // of memory operations.
9823 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9824 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9825 AttributeSet::FunctionIndex, Attribute::MinSize) &&
9826 !Subtarget->isAtom()) {
9828 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9829 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9830 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9832 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9833 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9834 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9836 return SDValue(Sub.getNode(), 1);
9838 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9841 /// Convert a comparison if required by the subtarget.
9842 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9843 SelectionDAG &DAG) const {
9844 // If the subtarget does not support the FUCOMI instruction, floating-point
9845 // comparisons have to be converted.
9846 if (Subtarget->hasCMov() ||
9847 Cmp.getOpcode() != X86ISD::CMP ||
9848 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9849 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9852 // The instruction selector will select an FUCOM instruction instead of
9853 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9854 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9855 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9857 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9858 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9859 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9860 DAG.getConstant(8, MVT::i8));
9861 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9862 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9865 static bool isAllOnes(SDValue V) {
9866 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9867 return C && C->isAllOnesValue();
9870 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9871 /// if it's possible.
9872 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9873 SDLoc dl, SelectionDAG &DAG) const {
9874 SDValue Op0 = And.getOperand(0);
9875 SDValue Op1 = And.getOperand(1);
9876 if (Op0.getOpcode() == ISD::TRUNCATE)
9877 Op0 = Op0.getOperand(0);
9878 if (Op1.getOpcode() == ISD::TRUNCATE)
9879 Op1 = Op1.getOperand(0);
9882 if (Op1.getOpcode() == ISD::SHL)
9883 std::swap(Op0, Op1);
9884 if (Op0.getOpcode() == ISD::SHL) {
9885 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9886 if (And00C->getZExtValue() == 1) {
9887 // If we looked past a truncate, check that it's only truncating away
9889 unsigned BitWidth = Op0.getValueSizeInBits();
9890 unsigned AndBitWidth = And.getValueSizeInBits();
9891 if (BitWidth > AndBitWidth) {
9893 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9894 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9898 RHS = Op0.getOperand(1);
9900 } else if (Op1.getOpcode() == ISD::Constant) {
9901 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9902 uint64_t AndRHSVal = AndRHS->getZExtValue();
9903 SDValue AndLHS = Op0;
9905 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9906 LHS = AndLHS.getOperand(0);
9907 RHS = AndLHS.getOperand(1);
9910 // Use BT if the immediate can't be encoded in a TEST instruction.
9911 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9913 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9917 if (LHS.getNode()) {
9918 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9919 // instruction. Since the shift amount is in-range-or-undefined, we know
9920 // that doing a bittest on the i32 value is ok. We extend to i32 because
9921 // the encoding for the i16 version is larger than the i32 version.
9922 // Also promote i16 to i32 for performance / code size reason.
9923 if (LHS.getValueType() == MVT::i8 ||
9924 LHS.getValueType() == MVT::i16)
9925 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9927 // If the operand types disagree, extend the shift amount to match. Since
9928 // BT ignores high bits (like shifts) we can use anyextend.
9929 if (LHS.getValueType() != RHS.getValueType())
9930 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9932 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9933 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9934 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9935 DAG.getConstant(Cond, MVT::i8), BT);
9941 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9943 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9948 // SSE Condition code mapping:
9957 switch (SetCCOpcode) {
9958 default: llvm_unreachable("Unexpected SETCC condition");
9960 case ISD::SETEQ: SSECC = 0; break;
9962 case ISD::SETGT: Swap = true; // Fallthrough
9964 case ISD::SETOLT: SSECC = 1; break;
9966 case ISD::SETGE: Swap = true; // Fallthrough
9968 case ISD::SETOLE: SSECC = 2; break;
9969 case ISD::SETUO: SSECC = 3; break;
9971 case ISD::SETNE: SSECC = 4; break;
9972 case ISD::SETULE: Swap = true; // Fallthrough
9973 case ISD::SETUGE: SSECC = 5; break;
9974 case ISD::SETULT: Swap = true; // Fallthrough
9975 case ISD::SETUGT: SSECC = 6; break;
9976 case ISD::SETO: SSECC = 7; break;
9978 case ISD::SETONE: SSECC = 8; break;
9981 std::swap(Op0, Op1);
9986 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9987 // ones, and then concatenate the result back.
9988 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9989 MVT VT = Op.getSimpleValueType();
9991 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9992 "Unsupported value type for operation");
9994 unsigned NumElems = VT.getVectorNumElements();
9996 SDValue CC = Op.getOperand(2);
9998 // Extract the LHS vectors
9999 SDValue LHS = Op.getOperand(0);
10000 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10001 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10003 // Extract the RHS vectors
10004 SDValue RHS = Op.getOperand(1);
10005 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10006 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10008 // Issue the operation on the smaller types and concatenate the result back
10009 MVT EltVT = VT.getVectorElementType();
10010 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10011 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10012 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10013 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10016 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10017 const X86Subtarget *Subtarget) {
10018 SDValue Op0 = Op.getOperand(0);
10019 SDValue Op1 = Op.getOperand(1);
10020 SDValue CC = Op.getOperand(2);
10021 MVT VT = Op.getSimpleValueType();
10024 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10025 Op.getValueType().getScalarType() == MVT::i1 &&
10026 "Cannot set masked compare for this operation");
10028 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10030 bool Unsigned = false;
10033 switch (SetCCOpcode) {
10034 default: llvm_unreachable("Unexpected SETCC condition");
10035 case ISD::SETNE: SSECC = 4; break;
10036 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10037 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10038 case ISD::SETLT: Swap = true; //fall-through
10039 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10040 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10041 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10042 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10043 case ISD::SETULE: Unsigned = true; //fall-through
10044 case ISD::SETLE: SSECC = 2; break;
10048 std::swap(Op0, Op1);
10050 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10051 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10052 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10053 DAG.getConstant(SSECC, MVT::i8));
10056 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10057 /// operand \p Op1. If non-trivial (for example because it's not constant)
10058 /// return an empty value.
10059 static SDValue ChangeVSETULTtoVSETULE(SDValue Op1, SelectionDAG &DAG)
10061 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10065 MVT VT = Op1.getSimpleValueType();
10066 MVT EVT = VT.getVectorElementType();
10067 unsigned n = VT.getVectorNumElements();
10068 SmallVector<SDValue, 8> ULTOp1;
10070 for (unsigned i = 0; i < n; ++i) {
10071 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10072 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10075 // Avoid underflow.
10076 APInt Val = Elt->getAPIntValue();
10080 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10083 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op1), VT, ULTOp1.data(),
10087 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10088 SelectionDAG &DAG) {
10089 SDValue Op0 = Op.getOperand(0);
10090 SDValue Op1 = Op.getOperand(1);
10091 SDValue CC = Op.getOperand(2);
10092 MVT VT = Op.getSimpleValueType();
10093 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10094 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10099 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10100 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10103 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10104 unsigned Opc = X86ISD::CMPP;
10105 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10106 assert(VT.getVectorNumElements() <= 16);
10107 Opc = X86ISD::CMPM;
10109 // In the two special cases we can't handle, emit two comparisons.
10112 unsigned CombineOpc;
10113 if (SetCCOpcode == ISD::SETUEQ) {
10114 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10116 assert(SetCCOpcode == ISD::SETONE);
10117 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10120 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10121 DAG.getConstant(CC0, MVT::i8));
10122 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10123 DAG.getConstant(CC1, MVT::i8));
10124 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10126 // Handle all other FP comparisons here.
10127 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10128 DAG.getConstant(SSECC, MVT::i8));
10131 // Break 256-bit integer vector compare into smaller ones.
10132 if (VT.is256BitVector() && !Subtarget->hasInt256())
10133 return Lower256IntVSETCC(Op, DAG);
10135 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10136 EVT OpVT = Op1.getValueType();
10137 if (Subtarget->hasAVX512()) {
10138 if (Op1.getValueType().is512BitVector() ||
10139 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10140 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10142 // In AVX-512 architecture setcc returns mask with i1 elements,
10143 // But there is no compare instruction for i8 and i16 elements.
10144 // We are not talking about 512-bit operands in this case, these
10145 // types are illegal.
10147 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10148 OpVT.getVectorElementType().getSizeInBits() >= 8))
10149 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10150 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10153 // We are handling one of the integer comparisons here. Since SSE only has
10154 // GT and EQ comparisons for integer, swapping operands and multiple
10155 // operations may be required for some comparisons.
10157 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10158 bool Subus = false;
10160 switch (SetCCOpcode) {
10161 default: llvm_unreachable("Unexpected SETCC condition");
10162 case ISD::SETNE: Invert = true;
10163 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10164 case ISD::SETLT: Swap = true;
10165 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10166 case ISD::SETGE: Swap = true;
10167 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10168 Invert = true; break;
10169 case ISD::SETULT: Swap = true;
10170 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10171 FlipSigns = true; break;
10172 case ISD::SETUGE: Swap = true;
10173 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10174 FlipSigns = true; Invert = true; break;
10177 // Special case: Use min/max operations for SETULE/SETUGE
10178 MVT VET = VT.getVectorElementType();
10180 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10181 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10184 switch (SetCCOpcode) {
10186 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10187 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10190 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10193 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10194 if (!MinMax && hasSubus) {
10195 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10197 // t = psubus Op0, Op1
10198 // pcmpeq t, <0..0>
10199 switch (SetCCOpcode) {
10201 case ISD::SETULT: {
10202 // If the comparison is against a constant we can turn this into a
10203 // setule. With psubus, setule does not require a swap. This is
10204 // beneficial because the constant in the register is no longer
10205 // destructed as the destination so it can be hoisted out of a loop.
10206 // Only do this pre-AVX since vpcmp* is no longer destructive.
10207 if (Subtarget->hasAVX())
10209 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(Op1, DAG);
10210 if (ULEOp1.getNode()) {
10212 Subus = true; Invert = false; Swap = false;
10216 // Psubus is better than flip-sign because it requires no inversion.
10217 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10218 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10222 Opc = X86ISD::SUBUS;
10228 std::swap(Op0, Op1);
10230 // Check that the operation in question is available (most are plain SSE2,
10231 // but PCMPGTQ and PCMPEQQ have different requirements).
10232 if (VT == MVT::v2i64) {
10233 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10234 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10236 // First cast everything to the right type.
10237 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10238 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10240 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10241 // bits of the inputs before performing those operations. The lower
10242 // compare is always unsigned.
10245 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10247 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10248 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10249 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10250 Sign, Zero, Sign, Zero);
10252 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10253 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10255 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10256 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10257 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10259 // Create masks for only the low parts/high parts of the 64 bit integers.
10260 static const int MaskHi[] = { 1, 1, 3, 3 };
10261 static const int MaskLo[] = { 0, 0, 2, 2 };
10262 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10263 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10264 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10266 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10267 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10270 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10272 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10275 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10276 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10277 // pcmpeqd + pshufd + pand.
10278 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10280 // First cast everything to the right type.
10281 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10282 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10285 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10287 // Make sure the lower and upper halves are both all-ones.
10288 static const int Mask[] = { 1, 0, 3, 2 };
10289 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10290 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10293 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10295 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10299 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10300 // bits of the inputs before performing those operations.
10302 EVT EltVT = VT.getVectorElementType();
10303 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10304 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10305 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10308 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10310 // If the logical-not of the result is required, perform that now.
10312 Result = DAG.getNOT(dl, Result, VT);
10315 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10318 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10319 getZeroVector(VT, Subtarget, DAG, dl));
10324 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10326 MVT VT = Op.getSimpleValueType();
10328 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10330 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10331 && "SetCC type must be 8-bit or 1-bit integer");
10332 SDValue Op0 = Op.getOperand(0);
10333 SDValue Op1 = Op.getOperand(1);
10335 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10337 // Optimize to BT if possible.
10338 // Lower (X & (1 << N)) == 0 to BT(X, N).
10339 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10340 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10341 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10342 Op1.getOpcode() == ISD::Constant &&
10343 cast<ConstantSDNode>(Op1)->isNullValue() &&
10344 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10345 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10346 if (NewSetCC.getNode())
10350 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10352 if (Op1.getOpcode() == ISD::Constant &&
10353 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10354 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10355 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10357 // If the input is a setcc, then reuse the input setcc or use a new one with
10358 // the inverted condition.
10359 if (Op0.getOpcode() == X86ISD::SETCC) {
10360 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10361 bool Invert = (CC == ISD::SETNE) ^
10362 cast<ConstantSDNode>(Op1)->isNullValue();
10366 CCode = X86::GetOppositeBranchCondition(CCode);
10367 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10368 DAG.getConstant(CCode, MVT::i8),
10369 Op0.getOperand(1));
10371 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10375 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10376 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10377 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10379 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10380 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10383 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10384 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10385 if (X86CC == X86::COND_INVALID)
10388 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10389 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10390 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10391 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10393 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10397 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10398 static bool isX86LogicalCmp(SDValue Op) {
10399 unsigned Opc = Op.getNode()->getOpcode();
10400 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10401 Opc == X86ISD::SAHF)
10403 if (Op.getResNo() == 1 &&
10404 (Opc == X86ISD::ADD ||
10405 Opc == X86ISD::SUB ||
10406 Opc == X86ISD::ADC ||
10407 Opc == X86ISD::SBB ||
10408 Opc == X86ISD::SMUL ||
10409 Opc == X86ISD::UMUL ||
10410 Opc == X86ISD::INC ||
10411 Opc == X86ISD::DEC ||
10412 Opc == X86ISD::OR ||
10413 Opc == X86ISD::XOR ||
10414 Opc == X86ISD::AND))
10417 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10423 static bool isZero(SDValue V) {
10424 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10425 return C && C->isNullValue();
10428 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10429 if (V.getOpcode() != ISD::TRUNCATE)
10432 SDValue VOp0 = V.getOperand(0);
10433 unsigned InBits = VOp0.getValueSizeInBits();
10434 unsigned Bits = V.getValueSizeInBits();
10435 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10438 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10439 bool addTest = true;
10440 SDValue Cond = Op.getOperand(0);
10441 SDValue Op1 = Op.getOperand(1);
10442 SDValue Op2 = Op.getOperand(2);
10444 EVT VT = Op1.getValueType();
10447 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10448 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10449 // sequence later on.
10450 if (Cond.getOpcode() == ISD::SETCC &&
10451 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10452 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10453 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10454 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10455 int SSECC = translateX86FSETCC(
10456 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10459 if (Subtarget->hasAVX512()) {
10460 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10461 DAG.getConstant(SSECC, MVT::i8));
10462 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10464 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10465 DAG.getConstant(SSECC, MVT::i8));
10466 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10467 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10468 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10472 if (Cond.getOpcode() == ISD::SETCC) {
10473 SDValue NewCond = LowerSETCC(Cond, DAG);
10474 if (NewCond.getNode())
10478 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10479 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10480 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10481 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10482 if (Cond.getOpcode() == X86ISD::SETCC &&
10483 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10484 isZero(Cond.getOperand(1).getOperand(1))) {
10485 SDValue Cmp = Cond.getOperand(1);
10487 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10489 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10490 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10491 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10493 SDValue CmpOp0 = Cmp.getOperand(0);
10494 // Apply further optimizations for special cases
10495 // (select (x != 0), -1, 0) -> neg & sbb
10496 // (select (x == 0), 0, -1) -> neg & sbb
10497 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10498 if (YC->isNullValue() &&
10499 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10500 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10501 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10502 DAG.getConstant(0, CmpOp0.getValueType()),
10504 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10505 DAG.getConstant(X86::COND_B, MVT::i8),
10506 SDValue(Neg.getNode(), 1));
10510 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10511 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10512 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10514 SDValue Res = // Res = 0 or -1.
10515 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10516 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10518 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10519 Res = DAG.getNOT(DL, Res, Res.getValueType());
10521 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10522 if (N2C == 0 || !N2C->isNullValue())
10523 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10528 // Look past (and (setcc_carry (cmp ...)), 1).
10529 if (Cond.getOpcode() == ISD::AND &&
10530 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10531 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10532 if (C && C->getAPIntValue() == 1)
10533 Cond = Cond.getOperand(0);
10536 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10537 // setting operand in place of the X86ISD::SETCC.
10538 unsigned CondOpcode = Cond.getOpcode();
10539 if (CondOpcode == X86ISD::SETCC ||
10540 CondOpcode == X86ISD::SETCC_CARRY) {
10541 CC = Cond.getOperand(0);
10543 SDValue Cmp = Cond.getOperand(1);
10544 unsigned Opc = Cmp.getOpcode();
10545 MVT VT = Op.getSimpleValueType();
10547 bool IllegalFPCMov = false;
10548 if (VT.isFloatingPoint() && !VT.isVector() &&
10549 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10550 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10552 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10553 Opc == X86ISD::BT) { // FIXME
10557 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10558 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10559 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10560 Cond.getOperand(0).getValueType() != MVT::i8)) {
10561 SDValue LHS = Cond.getOperand(0);
10562 SDValue RHS = Cond.getOperand(1);
10563 unsigned X86Opcode;
10566 switch (CondOpcode) {
10567 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10568 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10569 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10570 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10571 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10572 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10573 default: llvm_unreachable("unexpected overflowing operator");
10575 if (CondOpcode == ISD::UMULO)
10576 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10579 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10581 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10583 if (CondOpcode == ISD::UMULO)
10584 Cond = X86Op.getValue(2);
10586 Cond = X86Op.getValue(1);
10588 CC = DAG.getConstant(X86Cond, MVT::i8);
10593 // Look pass the truncate if the high bits are known zero.
10594 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10595 Cond = Cond.getOperand(0);
10597 // We know the result of AND is compared against zero. Try to match
10599 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10600 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10601 if (NewSetCC.getNode()) {
10602 CC = NewSetCC.getOperand(0);
10603 Cond = NewSetCC.getOperand(1);
10610 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10611 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10614 // a < b ? -1 : 0 -> RES = ~setcc_carry
10615 // a < b ? 0 : -1 -> RES = setcc_carry
10616 // a >= b ? -1 : 0 -> RES = setcc_carry
10617 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10618 if (Cond.getOpcode() == X86ISD::SUB) {
10619 Cond = ConvertCmpIfNecessary(Cond, DAG);
10620 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10622 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10623 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10624 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10625 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10626 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10627 return DAG.getNOT(DL, Res, Res.getValueType());
10632 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10633 // widen the cmov and push the truncate through. This avoids introducing a new
10634 // branch during isel and doesn't add any extensions.
10635 if (Op.getValueType() == MVT::i8 &&
10636 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10637 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10638 if (T1.getValueType() == T2.getValueType() &&
10639 // Blacklist CopyFromReg to avoid partial register stalls.
10640 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10641 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10642 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10643 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10647 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10648 // condition is true.
10649 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10650 SDValue Ops[] = { Op2, Op1, CC, Cond };
10651 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10654 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10655 MVT VT = Op->getSimpleValueType(0);
10656 SDValue In = Op->getOperand(0);
10657 MVT InVT = In.getSimpleValueType();
10660 unsigned int NumElts = VT.getVectorNumElements();
10661 if (NumElts != 8 && NumElts != 16)
10664 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10665 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10667 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10668 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10670 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10671 Constant *C = ConstantInt::get(*DAG.getContext(),
10672 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10674 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10675 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10676 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10677 MachinePointerInfo::getConstantPool(),
10678 false, false, false, Alignment);
10679 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10680 if (VT.is512BitVector())
10682 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10685 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10686 SelectionDAG &DAG) {
10687 MVT VT = Op->getSimpleValueType(0);
10688 SDValue In = Op->getOperand(0);
10689 MVT InVT = In.getSimpleValueType();
10692 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10693 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10695 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10696 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10697 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10700 if (Subtarget->hasInt256())
10701 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10703 // Optimize vectors in AVX mode
10704 // Sign extend v8i16 to v8i32 and
10707 // Divide input vector into two parts
10708 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10709 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10710 // concat the vectors to original VT
10712 unsigned NumElems = InVT.getVectorNumElements();
10713 SDValue Undef = DAG.getUNDEF(InVT);
10715 SmallVector<int,8> ShufMask1(NumElems, -1);
10716 for (unsigned i = 0; i != NumElems/2; ++i)
10719 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10721 SmallVector<int,8> ShufMask2(NumElems, -1);
10722 for (unsigned i = 0; i != NumElems/2; ++i)
10723 ShufMask2[i] = i + NumElems/2;
10725 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10727 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10728 VT.getVectorNumElements()/2);
10730 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10731 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10733 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10736 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10737 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10738 // from the AND / OR.
10739 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10740 Opc = Op.getOpcode();
10741 if (Opc != ISD::OR && Opc != ISD::AND)
10743 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10744 Op.getOperand(0).hasOneUse() &&
10745 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10746 Op.getOperand(1).hasOneUse());
10749 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10750 // 1 and that the SETCC node has a single use.
10751 static bool isXor1OfSetCC(SDValue Op) {
10752 if (Op.getOpcode() != ISD::XOR)
10754 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10755 if (N1C && N1C->getAPIntValue() == 1) {
10756 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10757 Op.getOperand(0).hasOneUse();
10762 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10763 bool addTest = true;
10764 SDValue Chain = Op.getOperand(0);
10765 SDValue Cond = Op.getOperand(1);
10766 SDValue Dest = Op.getOperand(2);
10769 bool Inverted = false;
10771 if (Cond.getOpcode() == ISD::SETCC) {
10772 // Check for setcc([su]{add,sub,mul}o == 0).
10773 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10774 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10775 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10776 Cond.getOperand(0).getResNo() == 1 &&
10777 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10778 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10779 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10780 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10781 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10782 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10784 Cond = Cond.getOperand(0);
10786 SDValue NewCond = LowerSETCC(Cond, DAG);
10787 if (NewCond.getNode())
10792 // FIXME: LowerXALUO doesn't handle these!!
10793 else if (Cond.getOpcode() == X86ISD::ADD ||
10794 Cond.getOpcode() == X86ISD::SUB ||
10795 Cond.getOpcode() == X86ISD::SMUL ||
10796 Cond.getOpcode() == X86ISD::UMUL)
10797 Cond = LowerXALUO(Cond, DAG);
10800 // Look pass (and (setcc_carry (cmp ...)), 1).
10801 if (Cond.getOpcode() == ISD::AND &&
10802 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10803 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10804 if (C && C->getAPIntValue() == 1)
10805 Cond = Cond.getOperand(0);
10808 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10809 // setting operand in place of the X86ISD::SETCC.
10810 unsigned CondOpcode = Cond.getOpcode();
10811 if (CondOpcode == X86ISD::SETCC ||
10812 CondOpcode == X86ISD::SETCC_CARRY) {
10813 CC = Cond.getOperand(0);
10815 SDValue Cmp = Cond.getOperand(1);
10816 unsigned Opc = Cmp.getOpcode();
10817 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10818 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10822 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10826 // These can only come from an arithmetic instruction with overflow,
10827 // e.g. SADDO, UADDO.
10828 Cond = Cond.getNode()->getOperand(1);
10834 CondOpcode = Cond.getOpcode();
10835 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10836 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10837 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10838 Cond.getOperand(0).getValueType() != MVT::i8)) {
10839 SDValue LHS = Cond.getOperand(0);
10840 SDValue RHS = Cond.getOperand(1);
10841 unsigned X86Opcode;
10844 // Keep this in sync with LowerXALUO, otherwise we might create redundant
10845 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10847 switch (CondOpcode) {
10848 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10850 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10852 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10855 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10856 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10858 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10860 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10863 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10864 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10865 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10866 default: llvm_unreachable("unexpected overflowing operator");
10869 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10870 if (CondOpcode == ISD::UMULO)
10871 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10874 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10876 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10878 if (CondOpcode == ISD::UMULO)
10879 Cond = X86Op.getValue(2);
10881 Cond = X86Op.getValue(1);
10883 CC = DAG.getConstant(X86Cond, MVT::i8);
10887 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10888 SDValue Cmp = Cond.getOperand(0).getOperand(1);
10889 if (CondOpc == ISD::OR) {
10890 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10891 // two branches instead of an explicit OR instruction with a
10893 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10894 isX86LogicalCmp(Cmp)) {
10895 CC = Cond.getOperand(0).getOperand(0);
10896 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10897 Chain, Dest, CC, Cmp);
10898 CC = Cond.getOperand(1).getOperand(0);
10902 } else { // ISD::AND
10903 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10904 // two branches instead of an explicit AND instruction with a
10905 // separate test. However, we only do this if this block doesn't
10906 // have a fall-through edge, because this requires an explicit
10907 // jmp when the condition is false.
10908 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10909 isX86LogicalCmp(Cmp) &&
10910 Op.getNode()->hasOneUse()) {
10911 X86::CondCode CCode =
10912 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10913 CCode = X86::GetOppositeBranchCondition(CCode);
10914 CC = DAG.getConstant(CCode, MVT::i8);
10915 SDNode *User = *Op.getNode()->use_begin();
10916 // Look for an unconditional branch following this conditional branch.
10917 // We need this because we need to reverse the successors in order
10918 // to implement FCMP_OEQ.
10919 if (User->getOpcode() == ISD::BR) {
10920 SDValue FalseBB = User->getOperand(1);
10922 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10923 assert(NewBR == User);
10927 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10928 Chain, Dest, CC, Cmp);
10929 X86::CondCode CCode =
10930 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10931 CCode = X86::GetOppositeBranchCondition(CCode);
10932 CC = DAG.getConstant(CCode, MVT::i8);
10938 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10939 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10940 // It should be transformed during dag combiner except when the condition
10941 // is set by a arithmetics with overflow node.
10942 X86::CondCode CCode =
10943 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10944 CCode = X86::GetOppositeBranchCondition(CCode);
10945 CC = DAG.getConstant(CCode, MVT::i8);
10946 Cond = Cond.getOperand(0).getOperand(1);
10948 } else if (Cond.getOpcode() == ISD::SETCC &&
10949 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10950 // For FCMP_OEQ, we can emit
10951 // two branches instead of an explicit AND instruction with a
10952 // separate test. However, we only do this if this block doesn't
10953 // have a fall-through edge, because this requires an explicit
10954 // jmp when the condition is false.
10955 if (Op.getNode()->hasOneUse()) {
10956 SDNode *User = *Op.getNode()->use_begin();
10957 // Look for an unconditional branch following this conditional branch.
10958 // We need this because we need to reverse the successors in order
10959 // to implement FCMP_OEQ.
10960 if (User->getOpcode() == ISD::BR) {
10961 SDValue FalseBB = User->getOperand(1);
10963 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10964 assert(NewBR == User);
10968 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10969 Cond.getOperand(0), Cond.getOperand(1));
10970 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10971 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10972 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10973 Chain, Dest, CC, Cmp);
10974 CC = DAG.getConstant(X86::COND_P, MVT::i8);
10979 } else if (Cond.getOpcode() == ISD::SETCC &&
10980 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10981 // For FCMP_UNE, we can emit
10982 // two branches instead of an explicit AND instruction with a
10983 // separate test. However, we only do this if this block doesn't
10984 // have a fall-through edge, because this requires an explicit
10985 // jmp when the condition is false.
10986 if (Op.getNode()->hasOneUse()) {
10987 SDNode *User = *Op.getNode()->use_begin();
10988 // Look for an unconditional branch following this conditional branch.
10989 // We need this because we need to reverse the successors in order
10990 // to implement FCMP_UNE.
10991 if (User->getOpcode() == ISD::BR) {
10992 SDValue FalseBB = User->getOperand(1);
10994 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10995 assert(NewBR == User);
10998 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10999 Cond.getOperand(0), Cond.getOperand(1));
11000 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11001 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11002 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11003 Chain, Dest, CC, Cmp);
11004 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11014 // Look pass the truncate if the high bits are known zero.
11015 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11016 Cond = Cond.getOperand(0);
11018 // We know the result of AND is compared against zero. Try to match
11020 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11021 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11022 if (NewSetCC.getNode()) {
11023 CC = NewSetCC.getOperand(0);
11024 Cond = NewSetCC.getOperand(1);
11031 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11032 Cond = EmitTest(Cond, X86::COND_NE, DAG);
11034 Cond = ConvertCmpIfNecessary(Cond, DAG);
11035 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11036 Chain, Dest, CC, Cond);
11039 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11040 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11041 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11042 // that the guard pages used by the OS virtual memory manager are allocated in
11043 // correct sequence.
11045 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11046 SelectionDAG &DAG) const {
11047 assert((Subtarget->isOSWindows() ||
11048 getTargetMachine().Options.EnableSegmentedStacks) &&
11049 "This should be used only on Windows targets or when segmented stacks "
11051 assert(!Subtarget->isTargetMacho() && "Not implemented");
11055 SDValue Chain = Op.getOperand(0);
11056 SDValue Size = Op.getOperand(1);
11057 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11058 EVT VT = Op.getNode()->getValueType(0);
11060 bool Is64Bit = Subtarget->is64Bit();
11061 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11063 if (getTargetMachine().Options.EnableSegmentedStacks) {
11064 MachineFunction &MF = DAG.getMachineFunction();
11065 MachineRegisterInfo &MRI = MF.getRegInfo();
11068 // The 64 bit implementation of segmented stacks needs to clobber both r10
11069 // r11. This makes it impossible to use it along with nested parameters.
11070 const Function *F = MF.getFunction();
11072 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11074 if (I->hasNestAttr())
11075 report_fatal_error("Cannot use segmented stacks with functions that "
11076 "have nested arguments.");
11079 const TargetRegisterClass *AddrRegClass =
11080 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11081 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11082 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11083 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11084 DAG.getRegister(Vreg, SPTy));
11085 SDValue Ops1[2] = { Value, Chain };
11086 return DAG.getMergeValues(Ops1, 2, dl);
11089 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11091 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11092 Flag = Chain.getValue(1);
11093 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11095 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11097 const X86RegisterInfo *RegInfo =
11098 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11099 unsigned SPReg = RegInfo->getStackRegister();
11100 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11101 Chain = SP.getValue(1);
11104 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11105 DAG.getConstant(-(uint64_t)Align, VT));
11106 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11109 SDValue Ops1[2] = { SP, Chain };
11110 return DAG.getMergeValues(Ops1, 2, dl);
11114 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11115 MachineFunction &MF = DAG.getMachineFunction();
11116 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11118 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11121 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11122 // vastart just stores the address of the VarArgsFrameIndex slot into the
11123 // memory location argument.
11124 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11126 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11127 MachinePointerInfo(SV), false, false, 0);
11131 // gp_offset (0 - 6 * 8)
11132 // fp_offset (48 - 48 + 8 * 16)
11133 // overflow_arg_area (point to parameters coming in memory).
11135 SmallVector<SDValue, 8> MemOps;
11136 SDValue FIN = Op.getOperand(1);
11138 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11139 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11141 FIN, MachinePointerInfo(SV), false, false, 0);
11142 MemOps.push_back(Store);
11145 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11146 FIN, DAG.getIntPtrConstant(4));
11147 Store = DAG.getStore(Op.getOperand(0), DL,
11148 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11150 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11151 MemOps.push_back(Store);
11153 // Store ptr to overflow_arg_area
11154 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11155 FIN, DAG.getIntPtrConstant(4));
11156 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11158 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11159 MachinePointerInfo(SV, 8),
11161 MemOps.push_back(Store);
11163 // Store ptr to reg_save_area.
11164 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11165 FIN, DAG.getIntPtrConstant(8));
11166 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11168 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11169 MachinePointerInfo(SV, 16), false, false, 0);
11170 MemOps.push_back(Store);
11171 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11172 &MemOps[0], MemOps.size());
11175 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11176 assert(Subtarget->is64Bit() &&
11177 "LowerVAARG only handles 64-bit va_arg!");
11178 assert((Subtarget->isTargetLinux() ||
11179 Subtarget->isTargetDarwin()) &&
11180 "Unhandled target in LowerVAARG");
11181 assert(Op.getNode()->getNumOperands() == 4);
11182 SDValue Chain = Op.getOperand(0);
11183 SDValue SrcPtr = Op.getOperand(1);
11184 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11185 unsigned Align = Op.getConstantOperandVal(3);
11188 EVT ArgVT = Op.getNode()->getValueType(0);
11189 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11190 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11193 // Decide which area this value should be read from.
11194 // TODO: Implement the AMD64 ABI in its entirety. This simple
11195 // selection mechanism works only for the basic types.
11196 if (ArgVT == MVT::f80) {
11197 llvm_unreachable("va_arg for f80 not yet implemented");
11198 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11199 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11200 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11201 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11203 llvm_unreachable("Unhandled argument type in LowerVAARG");
11206 if (ArgMode == 2) {
11207 // Sanity Check: Make sure using fp_offset makes sense.
11208 assert(!getTargetMachine().Options.UseSoftFloat &&
11209 !(DAG.getMachineFunction()
11210 .getFunction()->getAttributes()
11211 .hasAttribute(AttributeSet::FunctionIndex,
11212 Attribute::NoImplicitFloat)) &&
11213 Subtarget->hasSSE1());
11216 // Insert VAARG_64 node into the DAG
11217 // VAARG_64 returns two values: Variable Argument Address, Chain
11218 SmallVector<SDValue, 11> InstOps;
11219 InstOps.push_back(Chain);
11220 InstOps.push_back(SrcPtr);
11221 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11222 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11223 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11224 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11225 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11226 VTs, &InstOps[0], InstOps.size(),
11228 MachinePointerInfo(SV),
11230 /*Volatile=*/false,
11232 /*WriteMem=*/true);
11233 Chain = VAARG.getValue(1);
11235 // Load the next argument and return it
11236 return DAG.getLoad(ArgVT, dl,
11239 MachinePointerInfo(),
11240 false, false, false, 0);
11243 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11244 SelectionDAG &DAG) {
11245 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11246 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11247 SDValue Chain = Op.getOperand(0);
11248 SDValue DstPtr = Op.getOperand(1);
11249 SDValue SrcPtr = Op.getOperand(2);
11250 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11251 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11254 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11255 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11257 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11260 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11261 // amount is a constant. Takes immediate version of shift as input.
11262 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11263 SDValue SrcOp, uint64_t ShiftAmt,
11264 SelectionDAG &DAG) {
11265 MVT ElementType = VT.getVectorElementType();
11267 // Check for ShiftAmt >= element width
11268 if (ShiftAmt >= ElementType.getSizeInBits()) {
11269 if (Opc == X86ISD::VSRAI)
11270 ShiftAmt = ElementType.getSizeInBits() - 1;
11272 return DAG.getConstant(0, VT);
11275 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11276 && "Unknown target vector shift-by-constant node");
11278 // Fold this packed vector shift into a build vector if SrcOp is a
11279 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11280 if (VT == SrcOp.getSimpleValueType() &&
11281 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11282 SmallVector<SDValue, 8> Elts;
11283 unsigned NumElts = SrcOp->getNumOperands();
11284 ConstantSDNode *ND;
11287 default: llvm_unreachable(0);
11288 case X86ISD::VSHLI:
11289 for (unsigned i=0; i!=NumElts; ++i) {
11290 SDValue CurrentOp = SrcOp->getOperand(i);
11291 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11292 Elts.push_back(CurrentOp);
11295 ND = cast<ConstantSDNode>(CurrentOp);
11296 const APInt &C = ND->getAPIntValue();
11297 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11300 case X86ISD::VSRLI:
11301 for (unsigned i=0; i!=NumElts; ++i) {
11302 SDValue CurrentOp = SrcOp->getOperand(i);
11303 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11304 Elts.push_back(CurrentOp);
11307 ND = cast<ConstantSDNode>(CurrentOp);
11308 const APInt &C = ND->getAPIntValue();
11309 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11312 case X86ISD::VSRAI:
11313 for (unsigned i=0; i!=NumElts; ++i) {
11314 SDValue CurrentOp = SrcOp->getOperand(i);
11315 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11316 Elts.push_back(CurrentOp);
11319 ND = cast<ConstantSDNode>(CurrentOp);
11320 const APInt &C = ND->getAPIntValue();
11321 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11326 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11329 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11332 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11333 // may or may not be a constant. Takes immediate version of shift as input.
11334 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11335 SDValue SrcOp, SDValue ShAmt,
11336 SelectionDAG &DAG) {
11337 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11339 // Catch shift-by-constant.
11340 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11341 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11342 CShAmt->getZExtValue(), DAG);
11344 // Change opcode to non-immediate version
11346 default: llvm_unreachable("Unknown target vector shift node");
11347 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11348 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11349 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11352 // Need to build a vector containing shift amount
11353 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11356 ShOps[1] = DAG.getConstant(0, MVT::i32);
11357 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11358 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11360 // The return type has to be a 128-bit type with the same element
11361 // type as the input type.
11362 MVT EltVT = VT.getVectorElementType();
11363 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11365 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11366 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11369 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11371 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11373 default: return SDValue(); // Don't custom lower most intrinsics.
11374 // Comparison intrinsics.
11375 case Intrinsic::x86_sse_comieq_ss:
11376 case Intrinsic::x86_sse_comilt_ss:
11377 case Intrinsic::x86_sse_comile_ss:
11378 case Intrinsic::x86_sse_comigt_ss:
11379 case Intrinsic::x86_sse_comige_ss:
11380 case Intrinsic::x86_sse_comineq_ss:
11381 case Intrinsic::x86_sse_ucomieq_ss:
11382 case Intrinsic::x86_sse_ucomilt_ss:
11383 case Intrinsic::x86_sse_ucomile_ss:
11384 case Intrinsic::x86_sse_ucomigt_ss:
11385 case Intrinsic::x86_sse_ucomige_ss:
11386 case Intrinsic::x86_sse_ucomineq_ss:
11387 case Intrinsic::x86_sse2_comieq_sd:
11388 case Intrinsic::x86_sse2_comilt_sd:
11389 case Intrinsic::x86_sse2_comile_sd:
11390 case Intrinsic::x86_sse2_comigt_sd:
11391 case Intrinsic::x86_sse2_comige_sd:
11392 case Intrinsic::x86_sse2_comineq_sd:
11393 case Intrinsic::x86_sse2_ucomieq_sd:
11394 case Intrinsic::x86_sse2_ucomilt_sd:
11395 case Intrinsic::x86_sse2_ucomile_sd:
11396 case Intrinsic::x86_sse2_ucomigt_sd:
11397 case Intrinsic::x86_sse2_ucomige_sd:
11398 case Intrinsic::x86_sse2_ucomineq_sd: {
11402 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11403 case Intrinsic::x86_sse_comieq_ss:
11404 case Intrinsic::x86_sse2_comieq_sd:
11405 Opc = X86ISD::COMI;
11408 case Intrinsic::x86_sse_comilt_ss:
11409 case Intrinsic::x86_sse2_comilt_sd:
11410 Opc = X86ISD::COMI;
11413 case Intrinsic::x86_sse_comile_ss:
11414 case Intrinsic::x86_sse2_comile_sd:
11415 Opc = X86ISD::COMI;
11418 case Intrinsic::x86_sse_comigt_ss:
11419 case Intrinsic::x86_sse2_comigt_sd:
11420 Opc = X86ISD::COMI;
11423 case Intrinsic::x86_sse_comige_ss:
11424 case Intrinsic::x86_sse2_comige_sd:
11425 Opc = X86ISD::COMI;
11428 case Intrinsic::x86_sse_comineq_ss:
11429 case Intrinsic::x86_sse2_comineq_sd:
11430 Opc = X86ISD::COMI;
11433 case Intrinsic::x86_sse_ucomieq_ss:
11434 case Intrinsic::x86_sse2_ucomieq_sd:
11435 Opc = X86ISD::UCOMI;
11438 case Intrinsic::x86_sse_ucomilt_ss:
11439 case Intrinsic::x86_sse2_ucomilt_sd:
11440 Opc = X86ISD::UCOMI;
11443 case Intrinsic::x86_sse_ucomile_ss:
11444 case Intrinsic::x86_sse2_ucomile_sd:
11445 Opc = X86ISD::UCOMI;
11448 case Intrinsic::x86_sse_ucomigt_ss:
11449 case Intrinsic::x86_sse2_ucomigt_sd:
11450 Opc = X86ISD::UCOMI;
11453 case Intrinsic::x86_sse_ucomige_ss:
11454 case Intrinsic::x86_sse2_ucomige_sd:
11455 Opc = X86ISD::UCOMI;
11458 case Intrinsic::x86_sse_ucomineq_ss:
11459 case Intrinsic::x86_sse2_ucomineq_sd:
11460 Opc = X86ISD::UCOMI;
11465 SDValue LHS = Op.getOperand(1);
11466 SDValue RHS = Op.getOperand(2);
11467 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11468 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11469 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11470 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11471 DAG.getConstant(X86CC, MVT::i8), Cond);
11472 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11475 // Arithmetic intrinsics.
11476 case Intrinsic::x86_sse2_pmulu_dq:
11477 case Intrinsic::x86_avx2_pmulu_dq:
11478 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11479 Op.getOperand(1), Op.getOperand(2));
11481 // SSE2/AVX2 sub with unsigned saturation intrinsics
11482 case Intrinsic::x86_sse2_psubus_b:
11483 case Intrinsic::x86_sse2_psubus_w:
11484 case Intrinsic::x86_avx2_psubus_b:
11485 case Intrinsic::x86_avx2_psubus_w:
11486 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11487 Op.getOperand(1), Op.getOperand(2));
11489 // SSE3/AVX horizontal add/sub intrinsics
11490 case Intrinsic::x86_sse3_hadd_ps:
11491 case Intrinsic::x86_sse3_hadd_pd:
11492 case Intrinsic::x86_avx_hadd_ps_256:
11493 case Intrinsic::x86_avx_hadd_pd_256:
11494 case Intrinsic::x86_sse3_hsub_ps:
11495 case Intrinsic::x86_sse3_hsub_pd:
11496 case Intrinsic::x86_avx_hsub_ps_256:
11497 case Intrinsic::x86_avx_hsub_pd_256:
11498 case Intrinsic::x86_ssse3_phadd_w_128:
11499 case Intrinsic::x86_ssse3_phadd_d_128:
11500 case Intrinsic::x86_avx2_phadd_w:
11501 case Intrinsic::x86_avx2_phadd_d:
11502 case Intrinsic::x86_ssse3_phsub_w_128:
11503 case Intrinsic::x86_ssse3_phsub_d_128:
11504 case Intrinsic::x86_avx2_phsub_w:
11505 case Intrinsic::x86_avx2_phsub_d: {
11508 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11509 case Intrinsic::x86_sse3_hadd_ps:
11510 case Intrinsic::x86_sse3_hadd_pd:
11511 case Intrinsic::x86_avx_hadd_ps_256:
11512 case Intrinsic::x86_avx_hadd_pd_256:
11513 Opcode = X86ISD::FHADD;
11515 case Intrinsic::x86_sse3_hsub_ps:
11516 case Intrinsic::x86_sse3_hsub_pd:
11517 case Intrinsic::x86_avx_hsub_ps_256:
11518 case Intrinsic::x86_avx_hsub_pd_256:
11519 Opcode = X86ISD::FHSUB;
11521 case Intrinsic::x86_ssse3_phadd_w_128:
11522 case Intrinsic::x86_ssse3_phadd_d_128:
11523 case Intrinsic::x86_avx2_phadd_w:
11524 case Intrinsic::x86_avx2_phadd_d:
11525 Opcode = X86ISD::HADD;
11527 case Intrinsic::x86_ssse3_phsub_w_128:
11528 case Intrinsic::x86_ssse3_phsub_d_128:
11529 case Intrinsic::x86_avx2_phsub_w:
11530 case Intrinsic::x86_avx2_phsub_d:
11531 Opcode = X86ISD::HSUB;
11534 return DAG.getNode(Opcode, dl, Op.getValueType(),
11535 Op.getOperand(1), Op.getOperand(2));
11538 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11539 case Intrinsic::x86_sse2_pmaxu_b:
11540 case Intrinsic::x86_sse41_pmaxuw:
11541 case Intrinsic::x86_sse41_pmaxud:
11542 case Intrinsic::x86_avx2_pmaxu_b:
11543 case Intrinsic::x86_avx2_pmaxu_w:
11544 case Intrinsic::x86_avx2_pmaxu_d:
11545 case Intrinsic::x86_sse2_pminu_b:
11546 case Intrinsic::x86_sse41_pminuw:
11547 case Intrinsic::x86_sse41_pminud:
11548 case Intrinsic::x86_avx2_pminu_b:
11549 case Intrinsic::x86_avx2_pminu_w:
11550 case Intrinsic::x86_avx2_pminu_d:
11551 case Intrinsic::x86_sse41_pmaxsb:
11552 case Intrinsic::x86_sse2_pmaxs_w:
11553 case Intrinsic::x86_sse41_pmaxsd:
11554 case Intrinsic::x86_avx2_pmaxs_b:
11555 case Intrinsic::x86_avx2_pmaxs_w:
11556 case Intrinsic::x86_avx2_pmaxs_d:
11557 case Intrinsic::x86_sse41_pminsb:
11558 case Intrinsic::x86_sse2_pmins_w:
11559 case Intrinsic::x86_sse41_pminsd:
11560 case Intrinsic::x86_avx2_pmins_b:
11561 case Intrinsic::x86_avx2_pmins_w:
11562 case Intrinsic::x86_avx2_pmins_d: {
11565 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11566 case Intrinsic::x86_sse2_pmaxu_b:
11567 case Intrinsic::x86_sse41_pmaxuw:
11568 case Intrinsic::x86_sse41_pmaxud:
11569 case Intrinsic::x86_avx2_pmaxu_b:
11570 case Intrinsic::x86_avx2_pmaxu_w:
11571 case Intrinsic::x86_avx2_pmaxu_d:
11572 Opcode = X86ISD::UMAX;
11574 case Intrinsic::x86_sse2_pminu_b:
11575 case Intrinsic::x86_sse41_pminuw:
11576 case Intrinsic::x86_sse41_pminud:
11577 case Intrinsic::x86_avx2_pminu_b:
11578 case Intrinsic::x86_avx2_pminu_w:
11579 case Intrinsic::x86_avx2_pminu_d:
11580 Opcode = X86ISD::UMIN;
11582 case Intrinsic::x86_sse41_pmaxsb:
11583 case Intrinsic::x86_sse2_pmaxs_w:
11584 case Intrinsic::x86_sse41_pmaxsd:
11585 case Intrinsic::x86_avx2_pmaxs_b:
11586 case Intrinsic::x86_avx2_pmaxs_w:
11587 case Intrinsic::x86_avx2_pmaxs_d:
11588 Opcode = X86ISD::SMAX;
11590 case Intrinsic::x86_sse41_pminsb:
11591 case Intrinsic::x86_sse2_pmins_w:
11592 case Intrinsic::x86_sse41_pminsd:
11593 case Intrinsic::x86_avx2_pmins_b:
11594 case Intrinsic::x86_avx2_pmins_w:
11595 case Intrinsic::x86_avx2_pmins_d:
11596 Opcode = X86ISD::SMIN;
11599 return DAG.getNode(Opcode, dl, Op.getValueType(),
11600 Op.getOperand(1), Op.getOperand(2));
11603 // SSE/SSE2/AVX floating point max/min intrinsics.
11604 case Intrinsic::x86_sse_max_ps:
11605 case Intrinsic::x86_sse2_max_pd:
11606 case Intrinsic::x86_avx_max_ps_256:
11607 case Intrinsic::x86_avx_max_pd_256:
11608 case Intrinsic::x86_sse_min_ps:
11609 case Intrinsic::x86_sse2_min_pd:
11610 case Intrinsic::x86_avx_min_ps_256:
11611 case Intrinsic::x86_avx_min_pd_256: {
11614 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11615 case Intrinsic::x86_sse_max_ps:
11616 case Intrinsic::x86_sse2_max_pd:
11617 case Intrinsic::x86_avx_max_ps_256:
11618 case Intrinsic::x86_avx_max_pd_256:
11619 Opcode = X86ISD::FMAX;
11621 case Intrinsic::x86_sse_min_ps:
11622 case Intrinsic::x86_sse2_min_pd:
11623 case Intrinsic::x86_avx_min_ps_256:
11624 case Intrinsic::x86_avx_min_pd_256:
11625 Opcode = X86ISD::FMIN;
11628 return DAG.getNode(Opcode, dl, Op.getValueType(),
11629 Op.getOperand(1), Op.getOperand(2));
11632 // AVX2 variable shift intrinsics
11633 case Intrinsic::x86_avx2_psllv_d:
11634 case Intrinsic::x86_avx2_psllv_q:
11635 case Intrinsic::x86_avx2_psllv_d_256:
11636 case Intrinsic::x86_avx2_psllv_q_256:
11637 case Intrinsic::x86_avx2_psrlv_d:
11638 case Intrinsic::x86_avx2_psrlv_q:
11639 case Intrinsic::x86_avx2_psrlv_d_256:
11640 case Intrinsic::x86_avx2_psrlv_q_256:
11641 case Intrinsic::x86_avx2_psrav_d:
11642 case Intrinsic::x86_avx2_psrav_d_256: {
11645 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11646 case Intrinsic::x86_avx2_psllv_d:
11647 case Intrinsic::x86_avx2_psllv_q:
11648 case Intrinsic::x86_avx2_psllv_d_256:
11649 case Intrinsic::x86_avx2_psllv_q_256:
11652 case Intrinsic::x86_avx2_psrlv_d:
11653 case Intrinsic::x86_avx2_psrlv_q:
11654 case Intrinsic::x86_avx2_psrlv_d_256:
11655 case Intrinsic::x86_avx2_psrlv_q_256:
11658 case Intrinsic::x86_avx2_psrav_d:
11659 case Intrinsic::x86_avx2_psrav_d_256:
11663 return DAG.getNode(Opcode, dl, Op.getValueType(),
11664 Op.getOperand(1), Op.getOperand(2));
11667 case Intrinsic::x86_ssse3_pshuf_b_128:
11668 case Intrinsic::x86_avx2_pshuf_b:
11669 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11670 Op.getOperand(1), Op.getOperand(2));
11672 case Intrinsic::x86_ssse3_psign_b_128:
11673 case Intrinsic::x86_ssse3_psign_w_128:
11674 case Intrinsic::x86_ssse3_psign_d_128:
11675 case Intrinsic::x86_avx2_psign_b:
11676 case Intrinsic::x86_avx2_psign_w:
11677 case Intrinsic::x86_avx2_psign_d:
11678 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11679 Op.getOperand(1), Op.getOperand(2));
11681 case Intrinsic::x86_sse41_insertps:
11682 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11683 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11685 case Intrinsic::x86_avx_vperm2f128_ps_256:
11686 case Intrinsic::x86_avx_vperm2f128_pd_256:
11687 case Intrinsic::x86_avx_vperm2f128_si_256:
11688 case Intrinsic::x86_avx2_vperm2i128:
11689 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11690 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11692 case Intrinsic::x86_avx2_permd:
11693 case Intrinsic::x86_avx2_permps:
11694 // Operands intentionally swapped. Mask is last operand to intrinsic,
11695 // but second operand for node/instruction.
11696 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11697 Op.getOperand(2), Op.getOperand(1));
11699 case Intrinsic::x86_sse_sqrt_ps:
11700 case Intrinsic::x86_sse2_sqrt_pd:
11701 case Intrinsic::x86_avx_sqrt_ps_256:
11702 case Intrinsic::x86_avx_sqrt_pd_256:
11703 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11705 // ptest and testp intrinsics. The intrinsic these come from are designed to
11706 // return an integer value, not just an instruction so lower it to the ptest
11707 // or testp pattern and a setcc for the result.
11708 case Intrinsic::x86_sse41_ptestz:
11709 case Intrinsic::x86_sse41_ptestc:
11710 case Intrinsic::x86_sse41_ptestnzc:
11711 case Intrinsic::x86_avx_ptestz_256:
11712 case Intrinsic::x86_avx_ptestc_256:
11713 case Intrinsic::x86_avx_ptestnzc_256:
11714 case Intrinsic::x86_avx_vtestz_ps:
11715 case Intrinsic::x86_avx_vtestc_ps:
11716 case Intrinsic::x86_avx_vtestnzc_ps:
11717 case Intrinsic::x86_avx_vtestz_pd:
11718 case Intrinsic::x86_avx_vtestc_pd:
11719 case Intrinsic::x86_avx_vtestnzc_pd:
11720 case Intrinsic::x86_avx_vtestz_ps_256:
11721 case Intrinsic::x86_avx_vtestc_ps_256:
11722 case Intrinsic::x86_avx_vtestnzc_ps_256:
11723 case Intrinsic::x86_avx_vtestz_pd_256:
11724 case Intrinsic::x86_avx_vtestc_pd_256:
11725 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11726 bool IsTestPacked = false;
11729 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11730 case Intrinsic::x86_avx_vtestz_ps:
11731 case Intrinsic::x86_avx_vtestz_pd:
11732 case Intrinsic::x86_avx_vtestz_ps_256:
11733 case Intrinsic::x86_avx_vtestz_pd_256:
11734 IsTestPacked = true; // Fallthrough
11735 case Intrinsic::x86_sse41_ptestz:
11736 case Intrinsic::x86_avx_ptestz_256:
11738 X86CC = X86::COND_E;
11740 case Intrinsic::x86_avx_vtestc_ps:
11741 case Intrinsic::x86_avx_vtestc_pd:
11742 case Intrinsic::x86_avx_vtestc_ps_256:
11743 case Intrinsic::x86_avx_vtestc_pd_256:
11744 IsTestPacked = true; // Fallthrough
11745 case Intrinsic::x86_sse41_ptestc:
11746 case Intrinsic::x86_avx_ptestc_256:
11748 X86CC = X86::COND_B;
11750 case Intrinsic::x86_avx_vtestnzc_ps:
11751 case Intrinsic::x86_avx_vtestnzc_pd:
11752 case Intrinsic::x86_avx_vtestnzc_ps_256:
11753 case Intrinsic::x86_avx_vtestnzc_pd_256:
11754 IsTestPacked = true; // Fallthrough
11755 case Intrinsic::x86_sse41_ptestnzc:
11756 case Intrinsic::x86_avx_ptestnzc_256:
11758 X86CC = X86::COND_A;
11762 SDValue LHS = Op.getOperand(1);
11763 SDValue RHS = Op.getOperand(2);
11764 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11765 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11766 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11767 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11768 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11770 case Intrinsic::x86_avx512_kortestz_w:
11771 case Intrinsic::x86_avx512_kortestc_w: {
11772 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11773 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11774 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11775 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11776 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11777 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11778 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11781 // SSE/AVX shift intrinsics
11782 case Intrinsic::x86_sse2_psll_w:
11783 case Intrinsic::x86_sse2_psll_d:
11784 case Intrinsic::x86_sse2_psll_q:
11785 case Intrinsic::x86_avx2_psll_w:
11786 case Intrinsic::x86_avx2_psll_d:
11787 case Intrinsic::x86_avx2_psll_q:
11788 case Intrinsic::x86_sse2_psrl_w:
11789 case Intrinsic::x86_sse2_psrl_d:
11790 case Intrinsic::x86_sse2_psrl_q:
11791 case Intrinsic::x86_avx2_psrl_w:
11792 case Intrinsic::x86_avx2_psrl_d:
11793 case Intrinsic::x86_avx2_psrl_q:
11794 case Intrinsic::x86_sse2_psra_w:
11795 case Intrinsic::x86_sse2_psra_d:
11796 case Intrinsic::x86_avx2_psra_w:
11797 case Intrinsic::x86_avx2_psra_d: {
11800 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11801 case Intrinsic::x86_sse2_psll_w:
11802 case Intrinsic::x86_sse2_psll_d:
11803 case Intrinsic::x86_sse2_psll_q:
11804 case Intrinsic::x86_avx2_psll_w:
11805 case Intrinsic::x86_avx2_psll_d:
11806 case Intrinsic::x86_avx2_psll_q:
11807 Opcode = X86ISD::VSHL;
11809 case Intrinsic::x86_sse2_psrl_w:
11810 case Intrinsic::x86_sse2_psrl_d:
11811 case Intrinsic::x86_sse2_psrl_q:
11812 case Intrinsic::x86_avx2_psrl_w:
11813 case Intrinsic::x86_avx2_psrl_d:
11814 case Intrinsic::x86_avx2_psrl_q:
11815 Opcode = X86ISD::VSRL;
11817 case Intrinsic::x86_sse2_psra_w:
11818 case Intrinsic::x86_sse2_psra_d:
11819 case Intrinsic::x86_avx2_psra_w:
11820 case Intrinsic::x86_avx2_psra_d:
11821 Opcode = X86ISD::VSRA;
11824 return DAG.getNode(Opcode, dl, Op.getValueType(),
11825 Op.getOperand(1), Op.getOperand(2));
11828 // SSE/AVX immediate shift intrinsics
11829 case Intrinsic::x86_sse2_pslli_w:
11830 case Intrinsic::x86_sse2_pslli_d:
11831 case Intrinsic::x86_sse2_pslli_q:
11832 case Intrinsic::x86_avx2_pslli_w:
11833 case Intrinsic::x86_avx2_pslli_d:
11834 case Intrinsic::x86_avx2_pslli_q:
11835 case Intrinsic::x86_sse2_psrli_w:
11836 case Intrinsic::x86_sse2_psrli_d:
11837 case Intrinsic::x86_sse2_psrli_q:
11838 case Intrinsic::x86_avx2_psrli_w:
11839 case Intrinsic::x86_avx2_psrli_d:
11840 case Intrinsic::x86_avx2_psrli_q:
11841 case Intrinsic::x86_sse2_psrai_w:
11842 case Intrinsic::x86_sse2_psrai_d:
11843 case Intrinsic::x86_avx2_psrai_w:
11844 case Intrinsic::x86_avx2_psrai_d: {
11847 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11848 case Intrinsic::x86_sse2_pslli_w:
11849 case Intrinsic::x86_sse2_pslli_d:
11850 case Intrinsic::x86_sse2_pslli_q:
11851 case Intrinsic::x86_avx2_pslli_w:
11852 case Intrinsic::x86_avx2_pslli_d:
11853 case Intrinsic::x86_avx2_pslli_q:
11854 Opcode = X86ISD::VSHLI;
11856 case Intrinsic::x86_sse2_psrli_w:
11857 case Intrinsic::x86_sse2_psrli_d:
11858 case Intrinsic::x86_sse2_psrli_q:
11859 case Intrinsic::x86_avx2_psrli_w:
11860 case Intrinsic::x86_avx2_psrli_d:
11861 case Intrinsic::x86_avx2_psrli_q:
11862 Opcode = X86ISD::VSRLI;
11864 case Intrinsic::x86_sse2_psrai_w:
11865 case Intrinsic::x86_sse2_psrai_d:
11866 case Intrinsic::x86_avx2_psrai_w:
11867 case Intrinsic::x86_avx2_psrai_d:
11868 Opcode = X86ISD::VSRAI;
11871 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11872 Op.getOperand(1), Op.getOperand(2), DAG);
11875 case Intrinsic::x86_sse42_pcmpistria128:
11876 case Intrinsic::x86_sse42_pcmpestria128:
11877 case Intrinsic::x86_sse42_pcmpistric128:
11878 case Intrinsic::x86_sse42_pcmpestric128:
11879 case Intrinsic::x86_sse42_pcmpistrio128:
11880 case Intrinsic::x86_sse42_pcmpestrio128:
11881 case Intrinsic::x86_sse42_pcmpistris128:
11882 case Intrinsic::x86_sse42_pcmpestris128:
11883 case Intrinsic::x86_sse42_pcmpistriz128:
11884 case Intrinsic::x86_sse42_pcmpestriz128: {
11888 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11889 case Intrinsic::x86_sse42_pcmpistria128:
11890 Opcode = X86ISD::PCMPISTRI;
11891 X86CC = X86::COND_A;
11893 case Intrinsic::x86_sse42_pcmpestria128:
11894 Opcode = X86ISD::PCMPESTRI;
11895 X86CC = X86::COND_A;
11897 case Intrinsic::x86_sse42_pcmpistric128:
11898 Opcode = X86ISD::PCMPISTRI;
11899 X86CC = X86::COND_B;
11901 case Intrinsic::x86_sse42_pcmpestric128:
11902 Opcode = X86ISD::PCMPESTRI;
11903 X86CC = X86::COND_B;
11905 case Intrinsic::x86_sse42_pcmpistrio128:
11906 Opcode = X86ISD::PCMPISTRI;
11907 X86CC = X86::COND_O;
11909 case Intrinsic::x86_sse42_pcmpestrio128:
11910 Opcode = X86ISD::PCMPESTRI;
11911 X86CC = X86::COND_O;
11913 case Intrinsic::x86_sse42_pcmpistris128:
11914 Opcode = X86ISD::PCMPISTRI;
11915 X86CC = X86::COND_S;
11917 case Intrinsic::x86_sse42_pcmpestris128:
11918 Opcode = X86ISD::PCMPESTRI;
11919 X86CC = X86::COND_S;
11921 case Intrinsic::x86_sse42_pcmpistriz128:
11922 Opcode = X86ISD::PCMPISTRI;
11923 X86CC = X86::COND_E;
11925 case Intrinsic::x86_sse42_pcmpestriz128:
11926 Opcode = X86ISD::PCMPESTRI;
11927 X86CC = X86::COND_E;
11930 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11931 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11932 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11933 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11934 DAG.getConstant(X86CC, MVT::i8),
11935 SDValue(PCMP.getNode(), 1));
11936 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11939 case Intrinsic::x86_sse42_pcmpistri128:
11940 case Intrinsic::x86_sse42_pcmpestri128: {
11942 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11943 Opcode = X86ISD::PCMPISTRI;
11945 Opcode = X86ISD::PCMPESTRI;
11947 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11948 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11949 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11951 case Intrinsic::x86_fma_vfmadd_ps:
11952 case Intrinsic::x86_fma_vfmadd_pd:
11953 case Intrinsic::x86_fma_vfmsub_ps:
11954 case Intrinsic::x86_fma_vfmsub_pd:
11955 case Intrinsic::x86_fma_vfnmadd_ps:
11956 case Intrinsic::x86_fma_vfnmadd_pd:
11957 case Intrinsic::x86_fma_vfnmsub_ps:
11958 case Intrinsic::x86_fma_vfnmsub_pd:
11959 case Intrinsic::x86_fma_vfmaddsub_ps:
11960 case Intrinsic::x86_fma_vfmaddsub_pd:
11961 case Intrinsic::x86_fma_vfmsubadd_ps:
11962 case Intrinsic::x86_fma_vfmsubadd_pd:
11963 case Intrinsic::x86_fma_vfmadd_ps_256:
11964 case Intrinsic::x86_fma_vfmadd_pd_256:
11965 case Intrinsic::x86_fma_vfmsub_ps_256:
11966 case Intrinsic::x86_fma_vfmsub_pd_256:
11967 case Intrinsic::x86_fma_vfnmadd_ps_256:
11968 case Intrinsic::x86_fma_vfnmadd_pd_256:
11969 case Intrinsic::x86_fma_vfnmsub_ps_256:
11970 case Intrinsic::x86_fma_vfnmsub_pd_256:
11971 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11972 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11973 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11974 case Intrinsic::x86_fma_vfmsubadd_pd_256:
11975 case Intrinsic::x86_fma_vfmadd_ps_512:
11976 case Intrinsic::x86_fma_vfmadd_pd_512:
11977 case Intrinsic::x86_fma_vfmsub_ps_512:
11978 case Intrinsic::x86_fma_vfmsub_pd_512:
11979 case Intrinsic::x86_fma_vfnmadd_ps_512:
11980 case Intrinsic::x86_fma_vfnmadd_pd_512:
11981 case Intrinsic::x86_fma_vfnmsub_ps_512:
11982 case Intrinsic::x86_fma_vfnmsub_pd_512:
11983 case Intrinsic::x86_fma_vfmaddsub_ps_512:
11984 case Intrinsic::x86_fma_vfmaddsub_pd_512:
11985 case Intrinsic::x86_fma_vfmsubadd_ps_512:
11986 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11989 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11990 case Intrinsic::x86_fma_vfmadd_ps:
11991 case Intrinsic::x86_fma_vfmadd_pd:
11992 case Intrinsic::x86_fma_vfmadd_ps_256:
11993 case Intrinsic::x86_fma_vfmadd_pd_256:
11994 case Intrinsic::x86_fma_vfmadd_ps_512:
11995 case Intrinsic::x86_fma_vfmadd_pd_512:
11996 Opc = X86ISD::FMADD;
11998 case Intrinsic::x86_fma_vfmsub_ps:
11999 case Intrinsic::x86_fma_vfmsub_pd:
12000 case Intrinsic::x86_fma_vfmsub_ps_256:
12001 case Intrinsic::x86_fma_vfmsub_pd_256:
12002 case Intrinsic::x86_fma_vfmsub_ps_512:
12003 case Intrinsic::x86_fma_vfmsub_pd_512:
12004 Opc = X86ISD::FMSUB;
12006 case Intrinsic::x86_fma_vfnmadd_ps:
12007 case Intrinsic::x86_fma_vfnmadd_pd:
12008 case Intrinsic::x86_fma_vfnmadd_ps_256:
12009 case Intrinsic::x86_fma_vfnmadd_pd_256:
12010 case Intrinsic::x86_fma_vfnmadd_ps_512:
12011 case Intrinsic::x86_fma_vfnmadd_pd_512:
12012 Opc = X86ISD::FNMADD;
12014 case Intrinsic::x86_fma_vfnmsub_ps:
12015 case Intrinsic::x86_fma_vfnmsub_pd:
12016 case Intrinsic::x86_fma_vfnmsub_ps_256:
12017 case Intrinsic::x86_fma_vfnmsub_pd_256:
12018 case Intrinsic::x86_fma_vfnmsub_ps_512:
12019 case Intrinsic::x86_fma_vfnmsub_pd_512:
12020 Opc = X86ISD::FNMSUB;
12022 case Intrinsic::x86_fma_vfmaddsub_ps:
12023 case Intrinsic::x86_fma_vfmaddsub_pd:
12024 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12025 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12026 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12027 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12028 Opc = X86ISD::FMADDSUB;
12030 case Intrinsic::x86_fma_vfmsubadd_ps:
12031 case Intrinsic::x86_fma_vfmsubadd_pd:
12032 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12033 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12034 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12035 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12036 Opc = X86ISD::FMSUBADD;
12040 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12041 Op.getOperand(2), Op.getOperand(3));
12046 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12047 SDValue Base, SDValue Index,
12048 SDValue ScaleOp, SDValue Chain,
12049 const X86Subtarget * Subtarget) {
12051 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12052 assert(C && "Invalid scale type");
12053 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12054 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12055 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12056 Index.getSimpleValueType().getVectorNumElements());
12057 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12058 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12059 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12060 SDValue Segment = DAG.getRegister(0, MVT::i32);
12061 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12062 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12063 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12064 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12067 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12068 SDValue Src, SDValue Mask, SDValue Base,
12069 SDValue Index, SDValue ScaleOp, SDValue Chain,
12070 const X86Subtarget * Subtarget) {
12072 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12073 assert(C && "Invalid scale type");
12074 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12075 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12076 Index.getSimpleValueType().getVectorNumElements());
12077 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12078 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12079 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12080 SDValue Segment = DAG.getRegister(0, MVT::i32);
12081 if (Src.getOpcode() == ISD::UNDEF)
12082 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12083 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12084 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12085 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12086 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12089 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12090 SDValue Src, SDValue Base, SDValue Index,
12091 SDValue ScaleOp, SDValue Chain) {
12093 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12094 assert(C && "Invalid scale type");
12095 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12096 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12097 SDValue Segment = DAG.getRegister(0, MVT::i32);
12098 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12099 Index.getSimpleValueType().getVectorNumElements());
12100 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12101 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12102 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12103 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12104 return SDValue(Res, 1);
12107 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12108 SDValue Src, SDValue Mask, SDValue Base,
12109 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12111 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12112 assert(C && "Invalid scale type");
12113 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12114 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12115 SDValue Segment = DAG.getRegister(0, MVT::i32);
12116 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12117 Index.getSimpleValueType().getVectorNumElements());
12118 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12119 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12120 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12121 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12122 return SDValue(Res, 1);
12125 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12126 SelectionDAG &DAG) {
12128 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12130 default: return SDValue(); // Don't custom lower most intrinsics.
12132 // RDRAND/RDSEED intrinsics.
12133 case Intrinsic::x86_rdrand_16:
12134 case Intrinsic::x86_rdrand_32:
12135 case Intrinsic::x86_rdrand_64:
12136 case Intrinsic::x86_rdseed_16:
12137 case Intrinsic::x86_rdseed_32:
12138 case Intrinsic::x86_rdseed_64: {
12139 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12140 IntNo == Intrinsic::x86_rdseed_32 ||
12141 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12143 // Emit the node with the right value type.
12144 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12145 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12147 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12148 // Otherwise return the value from Rand, which is always 0, casted to i32.
12149 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12150 DAG.getConstant(1, Op->getValueType(1)),
12151 DAG.getConstant(X86::COND_B, MVT::i32),
12152 SDValue(Result.getNode(), 1) };
12153 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12154 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12155 Ops, array_lengthof(Ops));
12157 // Return { result, isValid, chain }.
12158 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12159 SDValue(Result.getNode(), 2));
12161 //int_gather(index, base, scale);
12162 case Intrinsic::x86_avx512_gather_qpd_512:
12163 case Intrinsic::x86_avx512_gather_qps_512:
12164 case Intrinsic::x86_avx512_gather_dpd_512:
12165 case Intrinsic::x86_avx512_gather_qpi_512:
12166 case Intrinsic::x86_avx512_gather_qpq_512:
12167 case Intrinsic::x86_avx512_gather_dpq_512:
12168 case Intrinsic::x86_avx512_gather_dps_512:
12169 case Intrinsic::x86_avx512_gather_dpi_512: {
12172 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12173 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12174 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12175 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12176 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12177 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12178 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12179 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12180 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12182 SDValue Chain = Op.getOperand(0);
12183 SDValue Index = Op.getOperand(2);
12184 SDValue Base = Op.getOperand(3);
12185 SDValue Scale = Op.getOperand(4);
12186 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12188 //int_gather_mask(v1, mask, index, base, scale);
12189 case Intrinsic::x86_avx512_gather_qps_mask_512:
12190 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12191 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12192 case Intrinsic::x86_avx512_gather_dps_mask_512:
12193 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12194 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12195 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12196 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12199 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12200 case Intrinsic::x86_avx512_gather_qps_mask_512:
12201 Opc = X86::VGATHERQPSZrm; break;
12202 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12203 Opc = X86::VGATHERQPDZrm; break;
12204 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12205 Opc = X86::VGATHERDPDZrm; break;
12206 case Intrinsic::x86_avx512_gather_dps_mask_512:
12207 Opc = X86::VGATHERDPSZrm; break;
12208 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12209 Opc = X86::VPGATHERQDZrm; break;
12210 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12211 Opc = X86::VPGATHERQQZrm; break;
12212 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12213 Opc = X86::VPGATHERDDZrm; break;
12214 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12215 Opc = X86::VPGATHERDQZrm; break;
12217 SDValue Chain = Op.getOperand(0);
12218 SDValue Src = Op.getOperand(2);
12219 SDValue Mask = Op.getOperand(3);
12220 SDValue Index = Op.getOperand(4);
12221 SDValue Base = Op.getOperand(5);
12222 SDValue Scale = Op.getOperand(6);
12223 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12226 //int_scatter(base, index, v1, scale);
12227 case Intrinsic::x86_avx512_scatter_qpd_512:
12228 case Intrinsic::x86_avx512_scatter_qps_512:
12229 case Intrinsic::x86_avx512_scatter_dpd_512:
12230 case Intrinsic::x86_avx512_scatter_qpi_512:
12231 case Intrinsic::x86_avx512_scatter_qpq_512:
12232 case Intrinsic::x86_avx512_scatter_dpq_512:
12233 case Intrinsic::x86_avx512_scatter_dps_512:
12234 case Intrinsic::x86_avx512_scatter_dpi_512: {
12237 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12238 case Intrinsic::x86_avx512_scatter_qpd_512:
12239 Opc = X86::VSCATTERQPDZmr; break;
12240 case Intrinsic::x86_avx512_scatter_qps_512:
12241 Opc = X86::VSCATTERQPSZmr; break;
12242 case Intrinsic::x86_avx512_scatter_dpd_512:
12243 Opc = X86::VSCATTERDPDZmr; break;
12244 case Intrinsic::x86_avx512_scatter_dps_512:
12245 Opc = X86::VSCATTERDPSZmr; break;
12246 case Intrinsic::x86_avx512_scatter_qpi_512:
12247 Opc = X86::VPSCATTERQDZmr; break;
12248 case Intrinsic::x86_avx512_scatter_qpq_512:
12249 Opc = X86::VPSCATTERQQZmr; break;
12250 case Intrinsic::x86_avx512_scatter_dpq_512:
12251 Opc = X86::VPSCATTERDQZmr; break;
12252 case Intrinsic::x86_avx512_scatter_dpi_512:
12253 Opc = X86::VPSCATTERDDZmr; break;
12255 SDValue Chain = Op.getOperand(0);
12256 SDValue Base = Op.getOperand(2);
12257 SDValue Index = Op.getOperand(3);
12258 SDValue Src = Op.getOperand(4);
12259 SDValue Scale = Op.getOperand(5);
12260 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12262 //int_scatter_mask(base, mask, index, v1, scale);
12263 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12264 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12265 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12266 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12267 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12268 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12269 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12270 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12273 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12274 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12275 Opc = X86::VSCATTERQPDZmr; break;
12276 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12277 Opc = X86::VSCATTERQPSZmr; break;
12278 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12279 Opc = X86::VSCATTERDPDZmr; break;
12280 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12281 Opc = X86::VSCATTERDPSZmr; break;
12282 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12283 Opc = X86::VPSCATTERQDZmr; break;
12284 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12285 Opc = X86::VPSCATTERQQZmr; break;
12286 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12287 Opc = X86::VPSCATTERDQZmr; break;
12288 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12289 Opc = X86::VPSCATTERDDZmr; break;
12291 SDValue Chain = Op.getOperand(0);
12292 SDValue Base = Op.getOperand(2);
12293 SDValue Mask = Op.getOperand(3);
12294 SDValue Index = Op.getOperand(4);
12295 SDValue Src = Op.getOperand(5);
12296 SDValue Scale = Op.getOperand(6);
12297 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12299 // XTEST intrinsics.
12300 case Intrinsic::x86_xtest: {
12301 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12302 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12303 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12304 DAG.getConstant(X86::COND_NE, MVT::i8),
12306 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12307 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12308 Ret, SDValue(InTrans.getNode(), 1));
12313 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12314 SelectionDAG &DAG) const {
12315 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12316 MFI->setReturnAddressIsTaken(true);
12318 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12321 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12323 EVT PtrVT = getPointerTy();
12326 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12327 const X86RegisterInfo *RegInfo =
12328 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12329 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12330 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12331 DAG.getNode(ISD::ADD, dl, PtrVT,
12332 FrameAddr, Offset),
12333 MachinePointerInfo(), false, false, false, 0);
12336 // Just load the return address.
12337 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12338 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12339 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12342 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12343 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12344 MFI->setFrameAddressIsTaken(true);
12346 EVT VT = Op.getValueType();
12347 SDLoc dl(Op); // FIXME probably not meaningful
12348 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12349 const X86RegisterInfo *RegInfo =
12350 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12351 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12352 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12353 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12354 "Invalid Frame Register!");
12355 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12357 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12358 MachinePointerInfo(),
12359 false, false, false, 0);
12363 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12364 SelectionDAG &DAG) const {
12365 const X86RegisterInfo *RegInfo =
12366 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12367 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12370 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12371 SDValue Chain = Op.getOperand(0);
12372 SDValue Offset = Op.getOperand(1);
12373 SDValue Handler = Op.getOperand(2);
12376 EVT PtrVT = getPointerTy();
12377 const X86RegisterInfo *RegInfo =
12378 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12379 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12380 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12381 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12382 "Invalid Frame Register!");
12383 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12384 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12386 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12387 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12388 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12389 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12391 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12393 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12394 DAG.getRegister(StoreAddrReg, PtrVT));
12397 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12398 SelectionDAG &DAG) const {
12400 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12401 DAG.getVTList(MVT::i32, MVT::Other),
12402 Op.getOperand(0), Op.getOperand(1));
12405 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12406 SelectionDAG &DAG) const {
12408 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12409 Op.getOperand(0), Op.getOperand(1));
12412 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12413 return Op.getOperand(0);
12416 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12417 SelectionDAG &DAG) const {
12418 SDValue Root = Op.getOperand(0);
12419 SDValue Trmp = Op.getOperand(1); // trampoline
12420 SDValue FPtr = Op.getOperand(2); // nested function
12421 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12424 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12425 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12427 if (Subtarget->is64Bit()) {
12428 SDValue OutChains[6];
12430 // Large code-model.
12431 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12432 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12434 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12435 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12437 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12439 // Load the pointer to the nested function into R11.
12440 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12441 SDValue Addr = Trmp;
12442 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12443 Addr, MachinePointerInfo(TrmpAddr),
12446 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12447 DAG.getConstant(2, MVT::i64));
12448 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12449 MachinePointerInfo(TrmpAddr, 2),
12452 // Load the 'nest' parameter value into R10.
12453 // R10 is specified in X86CallingConv.td
12454 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12455 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12456 DAG.getConstant(10, MVT::i64));
12457 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12458 Addr, MachinePointerInfo(TrmpAddr, 10),
12461 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12462 DAG.getConstant(12, MVT::i64));
12463 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12464 MachinePointerInfo(TrmpAddr, 12),
12467 // Jump to the nested function.
12468 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12469 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12470 DAG.getConstant(20, MVT::i64));
12471 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12472 Addr, MachinePointerInfo(TrmpAddr, 20),
12475 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12476 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12477 DAG.getConstant(22, MVT::i64));
12478 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12479 MachinePointerInfo(TrmpAddr, 22),
12482 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12484 const Function *Func =
12485 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12486 CallingConv::ID CC = Func->getCallingConv();
12491 llvm_unreachable("Unsupported calling convention");
12492 case CallingConv::C:
12493 case CallingConv::X86_StdCall: {
12494 // Pass 'nest' parameter in ECX.
12495 // Must be kept in sync with X86CallingConv.td
12496 NestReg = X86::ECX;
12498 // Check that ECX wasn't needed by an 'inreg' parameter.
12499 FunctionType *FTy = Func->getFunctionType();
12500 const AttributeSet &Attrs = Func->getAttributes();
12502 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12503 unsigned InRegCount = 0;
12506 for (FunctionType::param_iterator I = FTy->param_begin(),
12507 E = FTy->param_end(); I != E; ++I, ++Idx)
12508 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12509 // FIXME: should only count parameters that are lowered to integers.
12510 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12512 if (InRegCount > 2) {
12513 report_fatal_error("Nest register in use - reduce number of inreg"
12519 case CallingConv::X86_FastCall:
12520 case CallingConv::X86_ThisCall:
12521 case CallingConv::Fast:
12522 // Pass 'nest' parameter in EAX.
12523 // Must be kept in sync with X86CallingConv.td
12524 NestReg = X86::EAX;
12528 SDValue OutChains[4];
12529 SDValue Addr, Disp;
12531 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12532 DAG.getConstant(10, MVT::i32));
12533 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12535 // This is storing the opcode for MOV32ri.
12536 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12537 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12538 OutChains[0] = DAG.getStore(Root, dl,
12539 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12540 Trmp, MachinePointerInfo(TrmpAddr),
12543 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12544 DAG.getConstant(1, MVT::i32));
12545 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12546 MachinePointerInfo(TrmpAddr, 1),
12549 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12550 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12551 DAG.getConstant(5, MVT::i32));
12552 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12553 MachinePointerInfo(TrmpAddr, 5),
12556 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12557 DAG.getConstant(6, MVT::i32));
12558 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12559 MachinePointerInfo(TrmpAddr, 6),
12562 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12566 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12567 SelectionDAG &DAG) const {
12569 The rounding mode is in bits 11:10 of FPSR, and has the following
12571 00 Round to nearest
12576 FLT_ROUNDS, on the other hand, expects the following:
12583 To perform the conversion, we do:
12584 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12587 MachineFunction &MF = DAG.getMachineFunction();
12588 const TargetMachine &TM = MF.getTarget();
12589 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12590 unsigned StackAlignment = TFI.getStackAlignment();
12591 MVT VT = Op.getSimpleValueType();
12594 // Save FP Control Word to stack slot
12595 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12596 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12598 MachineMemOperand *MMO =
12599 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12600 MachineMemOperand::MOStore, 2, 2);
12602 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12603 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12604 DAG.getVTList(MVT::Other),
12605 Ops, array_lengthof(Ops), MVT::i16,
12608 // Load FP Control Word from stack slot
12609 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12610 MachinePointerInfo(), false, false, false, 0);
12612 // Transform as necessary
12614 DAG.getNode(ISD::SRL, DL, MVT::i16,
12615 DAG.getNode(ISD::AND, DL, MVT::i16,
12616 CWD, DAG.getConstant(0x800, MVT::i16)),
12617 DAG.getConstant(11, MVT::i8));
12619 DAG.getNode(ISD::SRL, DL, MVT::i16,
12620 DAG.getNode(ISD::AND, DL, MVT::i16,
12621 CWD, DAG.getConstant(0x400, MVT::i16)),
12622 DAG.getConstant(9, MVT::i8));
12625 DAG.getNode(ISD::AND, DL, MVT::i16,
12626 DAG.getNode(ISD::ADD, DL, MVT::i16,
12627 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12628 DAG.getConstant(1, MVT::i16)),
12629 DAG.getConstant(3, MVT::i16));
12631 return DAG.getNode((VT.getSizeInBits() < 16 ?
12632 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12635 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12636 MVT VT = Op.getSimpleValueType();
12638 unsigned NumBits = VT.getSizeInBits();
12641 Op = Op.getOperand(0);
12642 if (VT == MVT::i8) {
12643 // Zero extend to i32 since there is not an i8 bsr.
12645 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12648 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12649 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12650 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12652 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12655 DAG.getConstant(NumBits+NumBits-1, OpVT),
12656 DAG.getConstant(X86::COND_E, MVT::i8),
12659 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12661 // Finally xor with NumBits-1.
12662 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12665 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12669 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12670 MVT VT = Op.getSimpleValueType();
12672 unsigned NumBits = VT.getSizeInBits();
12675 Op = Op.getOperand(0);
12676 if (VT == MVT::i8) {
12677 // Zero extend to i32 since there is not an i8 bsr.
12679 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12682 // Issue a bsr (scan bits in reverse).
12683 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12684 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12686 // And xor with NumBits-1.
12687 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12690 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12694 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12695 MVT VT = Op.getSimpleValueType();
12696 unsigned NumBits = VT.getSizeInBits();
12698 Op = Op.getOperand(0);
12700 // Issue a bsf (scan bits forward) which also sets EFLAGS.
12701 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12702 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12704 // If src is zero (i.e. bsf sets ZF), returns NumBits.
12707 DAG.getConstant(NumBits, VT),
12708 DAG.getConstant(X86::COND_E, MVT::i8),
12711 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12714 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12715 // ones, and then concatenate the result back.
12716 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12717 MVT VT = Op.getSimpleValueType();
12719 assert(VT.is256BitVector() && VT.isInteger() &&
12720 "Unsupported value type for operation");
12722 unsigned NumElems = VT.getVectorNumElements();
12725 // Extract the LHS vectors
12726 SDValue LHS = Op.getOperand(0);
12727 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12728 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12730 // Extract the RHS vectors
12731 SDValue RHS = Op.getOperand(1);
12732 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12733 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12735 MVT EltVT = VT.getVectorElementType();
12736 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12738 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12739 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12740 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12743 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12744 assert(Op.getSimpleValueType().is256BitVector() &&
12745 Op.getSimpleValueType().isInteger() &&
12746 "Only handle AVX 256-bit vector integer operation");
12747 return Lower256IntArith(Op, DAG);
12750 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12751 assert(Op.getSimpleValueType().is256BitVector() &&
12752 Op.getSimpleValueType().isInteger() &&
12753 "Only handle AVX 256-bit vector integer operation");
12754 return Lower256IntArith(Op, DAG);
12757 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12758 SelectionDAG &DAG) {
12760 MVT VT = Op.getSimpleValueType();
12762 // Decompose 256-bit ops into smaller 128-bit ops.
12763 if (VT.is256BitVector() && !Subtarget->hasInt256())
12764 return Lower256IntArith(Op, DAG);
12766 SDValue A = Op.getOperand(0);
12767 SDValue B = Op.getOperand(1);
12769 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12770 if (VT == MVT::v4i32) {
12771 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12772 "Should not custom lower when pmuldq is available!");
12774 // Extract the odd parts.
12775 static const int UnpackMask[] = { 1, -1, 3, -1 };
12776 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12777 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12779 // Multiply the even parts.
12780 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12781 // Now multiply odd parts.
12782 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12784 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12785 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12787 // Merge the two vectors back together with a shuffle. This expands into 2
12789 static const int ShufMask[] = { 0, 4, 2, 6 };
12790 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12793 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12794 "Only know how to lower V2I64/V4I64/V8I64 multiply");
12796 // Ahi = psrlqi(a, 32);
12797 // Bhi = psrlqi(b, 32);
12799 // AloBlo = pmuludq(a, b);
12800 // AloBhi = pmuludq(a, Bhi);
12801 // AhiBlo = pmuludq(Ahi, b);
12803 // AloBhi = psllqi(AloBhi, 32);
12804 // AhiBlo = psllqi(AhiBlo, 32);
12805 // return AloBlo + AloBhi + AhiBlo;
12807 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12808 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12810 // Bit cast to 32-bit vectors for MULUDQ
12811 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12812 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12813 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12814 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12815 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12816 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12818 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12819 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12820 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12822 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12823 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12825 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12826 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12829 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12830 MVT VT = Op.getSimpleValueType();
12831 MVT EltTy = VT.getVectorElementType();
12832 unsigned NumElts = VT.getVectorNumElements();
12833 SDValue N0 = Op.getOperand(0);
12836 // Lower sdiv X, pow2-const.
12837 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12841 APInt SplatValue, SplatUndef;
12842 unsigned SplatBitSize;
12844 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12846 EltTy.getSizeInBits() < SplatBitSize)
12849 if ((SplatValue != 0) &&
12850 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12851 unsigned Lg2 = SplatValue.countTrailingZeros();
12852 // Splat the sign bit.
12853 SmallVector<SDValue, 16> Sz(NumElts,
12854 DAG.getConstant(EltTy.getSizeInBits() - 1,
12856 SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12857 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12859 // Add (N0 < 0) ? abs2 - 1 : 0;
12860 SmallVector<SDValue, 16> Amt(NumElts,
12861 DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12863 SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12864 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12866 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12867 SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12868 SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12869 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12872 // If we're dividing by a positive value, we're done. Otherwise, we must
12873 // negate the result.
12874 if (SplatValue.isNonNegative())
12877 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12878 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12879 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12884 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12885 const X86Subtarget *Subtarget) {
12886 MVT VT = Op.getSimpleValueType();
12888 SDValue R = Op.getOperand(0);
12889 SDValue Amt = Op.getOperand(1);
12891 // Optimize shl/srl/sra with constant shift amount.
12892 if (isSplatVector(Amt.getNode())) {
12893 SDValue SclrAmt = Amt->getOperand(0);
12894 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12895 uint64_t ShiftAmt = C->getZExtValue();
12897 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12898 (Subtarget->hasInt256() &&
12899 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12900 (Subtarget->hasAVX512() &&
12901 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12902 if (Op.getOpcode() == ISD::SHL)
12903 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12905 if (Op.getOpcode() == ISD::SRL)
12906 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12908 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12909 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12913 if (VT == MVT::v16i8) {
12914 if (Op.getOpcode() == ISD::SHL) {
12915 // Make a large shift.
12916 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12917 MVT::v8i16, R, ShiftAmt,
12919 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12920 // Zero out the rightmost bits.
12921 SmallVector<SDValue, 16> V(16,
12922 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12924 return DAG.getNode(ISD::AND, dl, VT, SHL,
12925 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12927 if (Op.getOpcode() == ISD::SRL) {
12928 // Make a large shift.
12929 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12930 MVT::v8i16, R, ShiftAmt,
12932 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12933 // Zero out the leftmost bits.
12934 SmallVector<SDValue, 16> V(16,
12935 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12937 return DAG.getNode(ISD::AND, dl, VT, SRL,
12938 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12940 if (Op.getOpcode() == ISD::SRA) {
12941 if (ShiftAmt == 7) {
12942 // R s>> 7 === R s< 0
12943 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12944 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12947 // R s>> a === ((R u>> a) ^ m) - m
12948 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12949 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12951 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12952 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12953 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12956 llvm_unreachable("Unknown shift opcode.");
12959 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12960 if (Op.getOpcode() == ISD::SHL) {
12961 // Make a large shift.
12962 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12963 MVT::v16i16, R, ShiftAmt,
12965 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12966 // Zero out the rightmost bits.
12967 SmallVector<SDValue, 32> V(32,
12968 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12970 return DAG.getNode(ISD::AND, dl, VT, SHL,
12971 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12973 if (Op.getOpcode() == ISD::SRL) {
12974 // Make a large shift.
12975 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12976 MVT::v16i16, R, ShiftAmt,
12978 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12979 // Zero out the leftmost bits.
12980 SmallVector<SDValue, 32> V(32,
12981 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12983 return DAG.getNode(ISD::AND, dl, VT, SRL,
12984 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12986 if (Op.getOpcode() == ISD::SRA) {
12987 if (ShiftAmt == 7) {
12988 // R s>> 7 === R s< 0
12989 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12990 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12993 // R s>> a === ((R u>> a) ^ m) - m
12994 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12995 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12997 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12998 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12999 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13002 llvm_unreachable("Unknown shift opcode.");
13007 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13008 if (!Subtarget->is64Bit() &&
13009 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13010 Amt.getOpcode() == ISD::BITCAST &&
13011 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13012 Amt = Amt.getOperand(0);
13013 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13014 VT.getVectorNumElements();
13015 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13016 uint64_t ShiftAmt = 0;
13017 for (unsigned i = 0; i != Ratio; ++i) {
13018 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13022 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13024 // Check remaining shift amounts.
13025 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13026 uint64_t ShAmt = 0;
13027 for (unsigned j = 0; j != Ratio; ++j) {
13028 ConstantSDNode *C =
13029 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13033 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13035 if (ShAmt != ShiftAmt)
13038 switch (Op.getOpcode()) {
13040 llvm_unreachable("Unknown shift opcode!");
13042 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13045 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13048 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13056 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13057 const X86Subtarget* Subtarget) {
13058 MVT VT = Op.getSimpleValueType();
13060 SDValue R = Op.getOperand(0);
13061 SDValue Amt = Op.getOperand(1);
13063 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13064 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13065 (Subtarget->hasInt256() &&
13066 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13067 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13068 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13070 EVT EltVT = VT.getVectorElementType();
13072 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13073 unsigned NumElts = VT.getVectorNumElements();
13075 for (i = 0; i != NumElts; ++i) {
13076 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13080 for (j = i; j != NumElts; ++j) {
13081 SDValue Arg = Amt.getOperand(j);
13082 if (Arg.getOpcode() == ISD::UNDEF) continue;
13083 if (Arg != Amt.getOperand(i))
13086 if (i != NumElts && j == NumElts)
13087 BaseShAmt = Amt.getOperand(i);
13089 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13090 Amt = Amt.getOperand(0);
13091 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13092 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13093 SDValue InVec = Amt.getOperand(0);
13094 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13095 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13097 for (; i != NumElts; ++i) {
13098 SDValue Arg = InVec.getOperand(i);
13099 if (Arg.getOpcode() == ISD::UNDEF) continue;
13103 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13104 if (ConstantSDNode *C =
13105 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13106 unsigned SplatIdx =
13107 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13108 if (C->getZExtValue() == SplatIdx)
13109 BaseShAmt = InVec.getOperand(1);
13112 if (BaseShAmt.getNode() == 0)
13113 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13114 DAG.getIntPtrConstant(0));
13118 if (BaseShAmt.getNode()) {
13119 if (EltVT.bitsGT(MVT::i32))
13120 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13121 else if (EltVT.bitsLT(MVT::i32))
13122 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13124 switch (Op.getOpcode()) {
13126 llvm_unreachable("Unknown shift opcode!");
13128 switch (VT.SimpleTy) {
13129 default: return SDValue();
13138 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13141 switch (VT.SimpleTy) {
13142 default: return SDValue();
13149 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13152 switch (VT.SimpleTy) {
13153 default: return SDValue();
13162 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13168 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13169 if (!Subtarget->is64Bit() &&
13170 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13171 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13172 Amt.getOpcode() == ISD::BITCAST &&
13173 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13174 Amt = Amt.getOperand(0);
13175 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13176 VT.getVectorNumElements();
13177 std::vector<SDValue> Vals(Ratio);
13178 for (unsigned i = 0; i != Ratio; ++i)
13179 Vals[i] = Amt.getOperand(i);
13180 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13181 for (unsigned j = 0; j != Ratio; ++j)
13182 if (Vals[j] != Amt.getOperand(i + j))
13185 switch (Op.getOpcode()) {
13187 llvm_unreachable("Unknown shift opcode!");
13189 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13191 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13193 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13200 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13201 SelectionDAG &DAG) {
13203 MVT VT = Op.getSimpleValueType();
13205 SDValue R = Op.getOperand(0);
13206 SDValue Amt = Op.getOperand(1);
13209 if (!Subtarget->hasSSE2())
13212 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13216 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13220 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13222 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13223 if (Subtarget->hasInt256()) {
13224 if (Op.getOpcode() == ISD::SRL &&
13225 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13226 VT == MVT::v4i64 || VT == MVT::v8i32))
13228 if (Op.getOpcode() == ISD::SHL &&
13229 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13230 VT == MVT::v4i64 || VT == MVT::v8i32))
13232 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13236 // If possible, lower this packed shift into a vector multiply instead of
13237 // expanding it into a sequence of scalar shifts.
13238 // Do this only if the vector shift count is a constant build_vector.
13239 if (Op.getOpcode() == ISD::SHL &&
13240 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13241 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13242 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13243 SmallVector<SDValue, 8> Elts;
13244 EVT SVT = VT.getScalarType();
13245 unsigned SVTBits = SVT.getSizeInBits();
13246 const APInt &One = APInt(SVTBits, 1);
13247 unsigned NumElems = VT.getVectorNumElements();
13249 for (unsigned i=0; i !=NumElems; ++i) {
13250 SDValue Op = Amt->getOperand(i);
13251 if (Op->getOpcode() == ISD::UNDEF) {
13252 Elts.push_back(Op);
13256 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13257 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13258 uint64_t ShAmt = C.getZExtValue();
13259 if (ShAmt >= SVTBits) {
13260 Elts.push_back(DAG.getUNDEF(SVT));
13263 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13265 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13266 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13269 // Lower SHL with variable shift amount.
13270 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13271 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13273 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13274 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13275 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13276 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13279 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13280 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13283 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13284 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13286 // Turn 'a' into a mask suitable for VSELECT
13287 SDValue VSelM = DAG.getConstant(0x80, VT);
13288 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13289 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13291 SDValue CM1 = DAG.getConstant(0x0f, VT);
13292 SDValue CM2 = DAG.getConstant(0x3f, VT);
13294 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13295 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13296 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13297 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13298 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13301 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13302 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13303 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13305 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13306 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13307 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13308 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13309 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13312 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13313 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13314 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13316 // return VSELECT(r, r+r, a);
13317 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13318 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13322 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13323 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13324 // solution better.
13325 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13326 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13328 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13329 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13330 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13331 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13332 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13335 // Decompose 256-bit shifts into smaller 128-bit shifts.
13336 if (VT.is256BitVector()) {
13337 unsigned NumElems = VT.getVectorNumElements();
13338 MVT EltVT = VT.getVectorElementType();
13339 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13341 // Extract the two vectors
13342 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13343 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13345 // Recreate the shift amount vectors
13346 SDValue Amt1, Amt2;
13347 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13348 // Constant shift amount
13349 SmallVector<SDValue, 4> Amt1Csts;
13350 SmallVector<SDValue, 4> Amt2Csts;
13351 for (unsigned i = 0; i != NumElems/2; ++i)
13352 Amt1Csts.push_back(Amt->getOperand(i));
13353 for (unsigned i = NumElems/2; i != NumElems; ++i)
13354 Amt2Csts.push_back(Amt->getOperand(i));
13356 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13357 &Amt1Csts[0], NumElems/2);
13358 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13359 &Amt2Csts[0], NumElems/2);
13361 // Variable shift amount
13362 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13363 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13366 // Issue new vector shifts for the smaller types
13367 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13368 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13370 // Concatenate the result back
13371 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13377 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13378 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13379 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13380 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13381 // has only one use.
13382 SDNode *N = Op.getNode();
13383 SDValue LHS = N->getOperand(0);
13384 SDValue RHS = N->getOperand(1);
13385 unsigned BaseOp = 0;
13388 switch (Op.getOpcode()) {
13389 default: llvm_unreachable("Unknown ovf instruction!");
13391 // A subtract of one will be selected as a INC. Note that INC doesn't
13392 // set CF, so we can't do this for UADDO.
13393 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13395 BaseOp = X86ISD::INC;
13396 Cond = X86::COND_O;
13399 BaseOp = X86ISD::ADD;
13400 Cond = X86::COND_O;
13403 BaseOp = X86ISD::ADD;
13404 Cond = X86::COND_B;
13407 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13408 // set CF, so we can't do this for USUBO.
13409 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13411 BaseOp = X86ISD::DEC;
13412 Cond = X86::COND_O;
13415 BaseOp = X86ISD::SUB;
13416 Cond = X86::COND_O;
13419 BaseOp = X86ISD::SUB;
13420 Cond = X86::COND_B;
13423 BaseOp = X86ISD::SMUL;
13424 Cond = X86::COND_O;
13426 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13427 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13429 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13432 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13433 DAG.getConstant(X86::COND_O, MVT::i32),
13434 SDValue(Sum.getNode(), 2));
13436 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13440 // Also sets EFLAGS.
13441 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13442 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13445 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13446 DAG.getConstant(Cond, MVT::i32),
13447 SDValue(Sum.getNode(), 1));
13449 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13452 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13453 SelectionDAG &DAG) const {
13455 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13456 MVT VT = Op.getSimpleValueType();
13458 if (!Subtarget->hasSSE2() || !VT.isVector())
13461 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13462 ExtraVT.getScalarType().getSizeInBits();
13464 switch (VT.SimpleTy) {
13465 default: return SDValue();
13468 if (!Subtarget->hasFp256())
13470 if (!Subtarget->hasInt256()) {
13471 // needs to be split
13472 unsigned NumElems = VT.getVectorNumElements();
13474 // Extract the LHS vectors
13475 SDValue LHS = Op.getOperand(0);
13476 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13477 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13479 MVT EltVT = VT.getVectorElementType();
13480 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13482 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13483 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13484 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13486 SDValue Extra = DAG.getValueType(ExtraVT);
13488 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13489 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13491 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13496 SDValue Op0 = Op.getOperand(0);
13497 SDValue Op00 = Op0.getOperand(0);
13499 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13500 if (Op0.getOpcode() == ISD::BITCAST &&
13501 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13502 // (sext (vzext x)) -> (vsext x)
13503 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13504 if (Tmp1.getNode()) {
13505 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13506 // This folding is only valid when the in-reg type is a vector of i8,
13508 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13509 ExtraEltVT == MVT::i32) {
13510 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13511 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13512 "This optimization is invalid without a VZEXT.");
13513 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13519 // If the above didn't work, then just use Shift-Left + Shift-Right.
13520 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13522 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13528 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13529 SelectionDAG &DAG) {
13531 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13532 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13533 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13534 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13536 // The only fence that needs an instruction is a sequentially-consistent
13537 // cross-thread fence.
13538 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13539 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13540 // no-sse2). There isn't any reason to disable it if the target processor
13542 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13543 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13545 SDValue Chain = Op.getOperand(0);
13546 SDValue Zero = DAG.getConstant(0, MVT::i32);
13548 DAG.getRegister(X86::ESP, MVT::i32), // Base
13549 DAG.getTargetConstant(1, MVT::i8), // Scale
13550 DAG.getRegister(0, MVT::i32), // Index
13551 DAG.getTargetConstant(0, MVT::i32), // Disp
13552 DAG.getRegister(0, MVT::i32), // Segment.
13556 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13557 return SDValue(Res, 0);
13560 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13561 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13564 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13565 SelectionDAG &DAG) {
13566 MVT T = Op.getSimpleValueType();
13570 switch(T.SimpleTy) {
13571 default: llvm_unreachable("Invalid value type!");
13572 case MVT::i8: Reg = X86::AL; size = 1; break;
13573 case MVT::i16: Reg = X86::AX; size = 2; break;
13574 case MVT::i32: Reg = X86::EAX; size = 4; break;
13576 assert(Subtarget->is64Bit() && "Node not type legal!");
13577 Reg = X86::RAX; size = 8;
13580 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13581 Op.getOperand(2), SDValue());
13582 SDValue Ops[] = { cpIn.getValue(0),
13585 DAG.getTargetConstant(size, MVT::i8),
13586 cpIn.getValue(1) };
13587 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13588 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13589 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13590 Ops, array_lengthof(Ops), T, MMO);
13592 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13596 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13597 SelectionDAG &DAG) {
13598 assert(Subtarget->is64Bit() && "Result not type legalized?");
13599 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13600 SDValue TheChain = Op.getOperand(0);
13602 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13603 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13604 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13606 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13607 DAG.getConstant(32, MVT::i8));
13609 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13612 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13615 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13616 SelectionDAG &DAG) {
13617 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13618 MVT DstVT = Op.getSimpleValueType();
13619 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13620 Subtarget->hasMMX() && "Unexpected custom BITCAST");
13621 assert((DstVT == MVT::i64 ||
13622 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13623 "Unexpected custom BITCAST");
13624 // i64 <=> MMX conversions are Legal.
13625 if (SrcVT==MVT::i64 && DstVT.isVector())
13627 if (DstVT==MVT::i64 && SrcVT.isVector())
13629 // MMX <=> MMX conversions are Legal.
13630 if (SrcVT.isVector() && DstVT.isVector())
13632 // All other conversions need to be expanded.
13636 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13637 SDNode *Node = Op.getNode();
13639 EVT T = Node->getValueType(0);
13640 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13641 DAG.getConstant(0, T), Node->getOperand(2));
13642 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13643 cast<AtomicSDNode>(Node)->getMemoryVT(),
13644 Node->getOperand(0),
13645 Node->getOperand(1), negOp,
13646 cast<AtomicSDNode>(Node)->getSrcValue(),
13647 cast<AtomicSDNode>(Node)->getAlignment(),
13648 cast<AtomicSDNode>(Node)->getOrdering(),
13649 cast<AtomicSDNode>(Node)->getSynchScope());
13652 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13653 SDNode *Node = Op.getNode();
13655 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13657 // Convert seq_cst store -> xchg
13658 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13659 // FIXME: On 32-bit, store -> fist or movq would be more efficient
13660 // (The only way to get a 16-byte store is cmpxchg16b)
13661 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13662 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13663 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13664 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13665 cast<AtomicSDNode>(Node)->getMemoryVT(),
13666 Node->getOperand(0),
13667 Node->getOperand(1), Node->getOperand(2),
13668 cast<AtomicSDNode>(Node)->getMemOperand(),
13669 cast<AtomicSDNode>(Node)->getOrdering(),
13670 cast<AtomicSDNode>(Node)->getSynchScope());
13671 return Swap.getValue(1);
13673 // Other atomic stores have a simple pattern.
13677 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13678 EVT VT = Op.getNode()->getSimpleValueType(0);
13680 // Let legalize expand this if it isn't a legal type yet.
13681 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13684 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13687 bool ExtraOp = false;
13688 switch (Op.getOpcode()) {
13689 default: llvm_unreachable("Invalid code");
13690 case ISD::ADDC: Opc = X86ISD::ADD; break;
13691 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13692 case ISD::SUBC: Opc = X86ISD::SUB; break;
13693 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13697 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13699 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13700 Op.getOperand(1), Op.getOperand(2));
13703 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13704 SelectionDAG &DAG) {
13705 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13707 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13708 // which returns the values as { float, float } (in XMM0) or
13709 // { double, double } (which is returned in XMM0, XMM1).
13711 SDValue Arg = Op.getOperand(0);
13712 EVT ArgVT = Arg.getValueType();
13713 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13715 TargetLowering::ArgListTy Args;
13716 TargetLowering::ArgListEntry Entry;
13720 Entry.isSExt = false;
13721 Entry.isZExt = false;
13722 Args.push_back(Entry);
13724 bool isF64 = ArgVT == MVT::f64;
13725 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13726 // the small struct {f32, f32} is returned in (eax, edx). For f64,
13727 // the results are returned via SRet in memory.
13728 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
13729 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13730 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13732 Type *RetTy = isF64
13733 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13734 : (Type*)VectorType::get(ArgTy, 4);
13736 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13737 false, false, false, false, 0,
13738 CallingConv::C, /*isTaillCall=*/false,
13739 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13740 Callee, Args, DAG, dl);
13741 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13744 // Returned in xmm0 and xmm1.
13745 return CallResult.first;
13747 // Returned in bits 0:31 and 32:64 xmm0.
13748 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13749 CallResult.first, DAG.getIntPtrConstant(0));
13750 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13751 CallResult.first, DAG.getIntPtrConstant(1));
13752 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13753 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13756 /// LowerOperation - Provide custom lowering hooks for some operations.
13758 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13759 switch (Op.getOpcode()) {
13760 default: llvm_unreachable("Should not custom lower this!");
13761 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
13762 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13763 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
13764 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
13765 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
13766 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
13767 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
13768 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
13769 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13770 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
13771 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13772 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13773 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
13774 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
13775 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
13776 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
13777 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
13778 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
13779 case ISD::SHL_PARTS:
13780 case ISD::SRA_PARTS:
13781 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
13782 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
13783 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
13784 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
13785 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
13786 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13787 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
13788 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
13789 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
13790 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
13791 case ISD::FABS: return LowerFABS(Op, DAG);
13792 case ISD::FNEG: return LowerFNEG(Op, DAG);
13793 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
13794 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
13795 case ISD::SETCC: return LowerSETCC(Op, DAG);
13796 case ISD::SELECT: return LowerSELECT(Op, DAG);
13797 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
13798 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
13799 case ISD::VASTART: return LowerVASTART(Op, DAG);
13800 case ISD::VAARG: return LowerVAARG(Op, DAG);
13801 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
13802 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13803 case ISD::INTRINSIC_VOID:
13804 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13805 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
13806 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
13807 case ISD::FRAME_TO_ARGS_OFFSET:
13808 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13809 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13810 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
13811 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
13812 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
13813 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
13814 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
13815 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
13816 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
13817 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13818 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
13819 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
13822 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
13828 case ISD::UMULO: return LowerXALUO(Op, DAG);
13829 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13830 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
13834 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13835 case ISD::ADD: return LowerADD(Op, DAG);
13836 case ISD::SUB: return LowerSUB(Op, DAG);
13837 case ISD::SDIV: return LowerSDIV(Op, DAG);
13838 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
13842 static void ReplaceATOMIC_LOAD(SDNode *Node,
13843 SmallVectorImpl<SDValue> &Results,
13844 SelectionDAG &DAG) {
13846 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13848 // Convert wide load -> cmpxchg8b/cmpxchg16b
13849 // FIXME: On 32-bit, load -> fild or movq would be more efficient
13850 // (The only way to get a 16-byte load is cmpxchg16b)
13851 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13852 SDValue Zero = DAG.getConstant(0, VT);
13853 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13854 Node->getOperand(0),
13855 Node->getOperand(1), Zero, Zero,
13856 cast<AtomicSDNode>(Node)->getMemOperand(),
13857 cast<AtomicSDNode>(Node)->getOrdering(),
13858 cast<AtomicSDNode>(Node)->getOrdering(),
13859 cast<AtomicSDNode>(Node)->getSynchScope());
13860 Results.push_back(Swap.getValue(0));
13861 Results.push_back(Swap.getValue(1));
13865 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13866 SelectionDAG &DAG, unsigned NewOp) {
13868 assert (Node->getValueType(0) == MVT::i64 &&
13869 "Only know how to expand i64 atomics");
13871 SDValue Chain = Node->getOperand(0);
13872 SDValue In1 = Node->getOperand(1);
13873 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13874 Node->getOperand(2), DAG.getIntPtrConstant(0));
13875 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13876 Node->getOperand(2), DAG.getIntPtrConstant(1));
13877 SDValue Ops[] = { Chain, In1, In2L, In2H };
13878 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13880 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13881 cast<MemSDNode>(Node)->getMemOperand());
13882 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13883 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13884 Results.push_back(Result.getValue(2));
13887 /// ReplaceNodeResults - Replace a node with an illegal result type
13888 /// with a new node built out of custom code.
13889 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13890 SmallVectorImpl<SDValue>&Results,
13891 SelectionDAG &DAG) const {
13893 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13894 switch (N->getOpcode()) {
13896 llvm_unreachable("Do not know how to custom type legalize this operation!");
13897 case ISD::SIGN_EXTEND_INREG:
13902 // We don't want to expand or promote these.
13904 case ISD::FP_TO_SINT:
13905 case ISD::FP_TO_UINT: {
13906 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13908 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13911 std::pair<SDValue,SDValue> Vals =
13912 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13913 SDValue FIST = Vals.first, StackSlot = Vals.second;
13914 if (FIST.getNode() != 0) {
13915 EVT VT = N->getValueType(0);
13916 // Return a load from the stack slot.
13917 if (StackSlot.getNode() != 0)
13918 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13919 MachinePointerInfo(),
13920 false, false, false, 0));
13922 Results.push_back(FIST);
13926 case ISD::UINT_TO_FP: {
13927 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13928 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13929 N->getValueType(0) != MVT::v2f32)
13931 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13933 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13935 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13936 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13937 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13938 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13939 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13940 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13943 case ISD::FP_ROUND: {
13944 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13946 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13947 Results.push_back(V);
13950 case ISD::READCYCLECOUNTER: {
13951 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13952 SDValue TheChain = N->getOperand(0);
13953 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13954 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13956 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13958 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13959 SDValue Ops[] = { eax, edx };
13960 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13961 array_lengthof(Ops)));
13962 Results.push_back(edx.getValue(1));
13965 case ISD::ATOMIC_CMP_SWAP: {
13966 EVT T = N->getValueType(0);
13967 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13968 bool Regs64bit = T == MVT::i128;
13969 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13970 SDValue cpInL, cpInH;
13971 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13972 DAG.getConstant(0, HalfT));
13973 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13974 DAG.getConstant(1, HalfT));
13975 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13976 Regs64bit ? X86::RAX : X86::EAX,
13978 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13979 Regs64bit ? X86::RDX : X86::EDX,
13980 cpInH, cpInL.getValue(1));
13981 SDValue swapInL, swapInH;
13982 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13983 DAG.getConstant(0, HalfT));
13984 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13985 DAG.getConstant(1, HalfT));
13986 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13987 Regs64bit ? X86::RBX : X86::EBX,
13988 swapInL, cpInH.getValue(1));
13989 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13990 Regs64bit ? X86::RCX : X86::ECX,
13991 swapInH, swapInL.getValue(1));
13992 SDValue Ops[] = { swapInH.getValue(0),
13994 swapInH.getValue(1) };
13995 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13996 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13997 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13998 X86ISD::LCMPXCHG8_DAG;
13999 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14000 Ops, array_lengthof(Ops), T, MMO);
14001 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14002 Regs64bit ? X86::RAX : X86::EAX,
14003 HalfT, Result.getValue(1));
14004 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14005 Regs64bit ? X86::RDX : X86::EDX,
14006 HalfT, cpOutL.getValue(2));
14007 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14008 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14009 Results.push_back(cpOutH.getValue(1));
14012 case ISD::ATOMIC_LOAD_ADD:
14013 case ISD::ATOMIC_LOAD_AND:
14014 case ISD::ATOMIC_LOAD_NAND:
14015 case ISD::ATOMIC_LOAD_OR:
14016 case ISD::ATOMIC_LOAD_SUB:
14017 case ISD::ATOMIC_LOAD_XOR:
14018 case ISD::ATOMIC_LOAD_MAX:
14019 case ISD::ATOMIC_LOAD_MIN:
14020 case ISD::ATOMIC_LOAD_UMAX:
14021 case ISD::ATOMIC_LOAD_UMIN:
14022 case ISD::ATOMIC_SWAP: {
14024 switch (N->getOpcode()) {
14025 default: llvm_unreachable("Unexpected opcode");
14026 case ISD::ATOMIC_LOAD_ADD:
14027 Opc = X86ISD::ATOMADD64_DAG;
14029 case ISD::ATOMIC_LOAD_AND:
14030 Opc = X86ISD::ATOMAND64_DAG;
14032 case ISD::ATOMIC_LOAD_NAND:
14033 Opc = X86ISD::ATOMNAND64_DAG;
14035 case ISD::ATOMIC_LOAD_OR:
14036 Opc = X86ISD::ATOMOR64_DAG;
14038 case ISD::ATOMIC_LOAD_SUB:
14039 Opc = X86ISD::ATOMSUB64_DAG;
14041 case ISD::ATOMIC_LOAD_XOR:
14042 Opc = X86ISD::ATOMXOR64_DAG;
14044 case ISD::ATOMIC_LOAD_MAX:
14045 Opc = X86ISD::ATOMMAX64_DAG;
14047 case ISD::ATOMIC_LOAD_MIN:
14048 Opc = X86ISD::ATOMMIN64_DAG;
14050 case ISD::ATOMIC_LOAD_UMAX:
14051 Opc = X86ISD::ATOMUMAX64_DAG;
14053 case ISD::ATOMIC_LOAD_UMIN:
14054 Opc = X86ISD::ATOMUMIN64_DAG;
14056 case ISD::ATOMIC_SWAP:
14057 Opc = X86ISD::ATOMSWAP64_DAG;
14060 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14063 case ISD::ATOMIC_LOAD:
14064 ReplaceATOMIC_LOAD(N, Results, DAG);
14068 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14070 default: return NULL;
14071 case X86ISD::BSF: return "X86ISD::BSF";
14072 case X86ISD::BSR: return "X86ISD::BSR";
14073 case X86ISD::SHLD: return "X86ISD::SHLD";
14074 case X86ISD::SHRD: return "X86ISD::SHRD";
14075 case X86ISD::FAND: return "X86ISD::FAND";
14076 case X86ISD::FANDN: return "X86ISD::FANDN";
14077 case X86ISD::FOR: return "X86ISD::FOR";
14078 case X86ISD::FXOR: return "X86ISD::FXOR";
14079 case X86ISD::FSRL: return "X86ISD::FSRL";
14080 case X86ISD::FILD: return "X86ISD::FILD";
14081 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14082 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14083 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14084 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14085 case X86ISD::FLD: return "X86ISD::FLD";
14086 case X86ISD::FST: return "X86ISD::FST";
14087 case X86ISD::CALL: return "X86ISD::CALL";
14088 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14089 case X86ISD::BT: return "X86ISD::BT";
14090 case X86ISD::CMP: return "X86ISD::CMP";
14091 case X86ISD::COMI: return "X86ISD::COMI";
14092 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14093 case X86ISD::CMPM: return "X86ISD::CMPM";
14094 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14095 case X86ISD::SETCC: return "X86ISD::SETCC";
14096 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14097 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14098 case X86ISD::CMOV: return "X86ISD::CMOV";
14099 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14100 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14101 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14102 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14103 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14104 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14105 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14106 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14107 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14108 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14109 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14110 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14111 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14112 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14113 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14114 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14115 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14116 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14117 case X86ISD::HADD: return "X86ISD::HADD";
14118 case X86ISD::HSUB: return "X86ISD::HSUB";
14119 case X86ISD::FHADD: return "X86ISD::FHADD";
14120 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14121 case X86ISD::UMAX: return "X86ISD::UMAX";
14122 case X86ISD::UMIN: return "X86ISD::UMIN";
14123 case X86ISD::SMAX: return "X86ISD::SMAX";
14124 case X86ISD::SMIN: return "X86ISD::SMIN";
14125 case X86ISD::FMAX: return "X86ISD::FMAX";
14126 case X86ISD::FMIN: return "X86ISD::FMIN";
14127 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14128 case X86ISD::FMINC: return "X86ISD::FMINC";
14129 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14130 case X86ISD::FRCP: return "X86ISD::FRCP";
14131 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14132 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14133 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14134 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14135 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14136 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14137 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14138 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14139 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14140 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14141 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14142 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14143 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14144 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14145 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14146 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14147 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14148 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14149 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14150 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14151 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14152 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14153 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14154 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14155 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14156 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14157 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14158 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14159 case X86ISD::VSHL: return "X86ISD::VSHL";
14160 case X86ISD::VSRL: return "X86ISD::VSRL";
14161 case X86ISD::VSRA: return "X86ISD::VSRA";
14162 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14163 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14164 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14165 case X86ISD::CMPP: return "X86ISD::CMPP";
14166 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14167 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14168 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14169 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14170 case X86ISD::ADD: return "X86ISD::ADD";
14171 case X86ISD::SUB: return "X86ISD::SUB";
14172 case X86ISD::ADC: return "X86ISD::ADC";
14173 case X86ISD::SBB: return "X86ISD::SBB";
14174 case X86ISD::SMUL: return "X86ISD::SMUL";
14175 case X86ISD::UMUL: return "X86ISD::UMUL";
14176 case X86ISD::INC: return "X86ISD::INC";
14177 case X86ISD::DEC: return "X86ISD::DEC";
14178 case X86ISD::OR: return "X86ISD::OR";
14179 case X86ISD::XOR: return "X86ISD::XOR";
14180 case X86ISD::AND: return "X86ISD::AND";
14181 case X86ISD::BZHI: return "X86ISD::BZHI";
14182 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14183 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14184 case X86ISD::PTEST: return "X86ISD::PTEST";
14185 case X86ISD::TESTP: return "X86ISD::TESTP";
14186 case X86ISD::TESTM: return "X86ISD::TESTM";
14187 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14188 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14189 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14190 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14191 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14192 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14193 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14194 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14195 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14196 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14197 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14198 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14199 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14200 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14201 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14202 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14203 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14204 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14205 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14206 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14207 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14208 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14209 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14210 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14211 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14212 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14213 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14214 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14215 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14216 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14217 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14218 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14219 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14220 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14221 case X86ISD::SAHF: return "X86ISD::SAHF";
14222 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14223 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14224 case X86ISD::FMADD: return "X86ISD::FMADD";
14225 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14226 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14227 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14228 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14229 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14230 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14231 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14232 case X86ISD::XTEST: return "X86ISD::XTEST";
14236 // isLegalAddressingMode - Return true if the addressing mode represented
14237 // by AM is legal for this target, for a load/store of the specified type.
14238 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14240 // X86 supports extremely general addressing modes.
14241 CodeModel::Model M = getTargetMachine().getCodeModel();
14242 Reloc::Model R = getTargetMachine().getRelocationModel();
14244 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14245 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14250 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14252 // If a reference to this global requires an extra load, we can't fold it.
14253 if (isGlobalStubReference(GVFlags))
14256 // If BaseGV requires a register for the PIC base, we cannot also have a
14257 // BaseReg specified.
14258 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14261 // If lower 4G is not available, then we must use rip-relative addressing.
14262 if ((M != CodeModel::Small || R != Reloc::Static) &&
14263 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14267 switch (AM.Scale) {
14273 // These scales always work.
14278 // These scales are formed with basereg+scalereg. Only accept if there is
14283 default: // Other stuff never works.
14290 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14291 unsigned Bits = Ty->getScalarSizeInBits();
14293 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14294 // particularly cheaper than those without.
14298 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14299 // variable shifts just as cheap as scalar ones.
14300 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14303 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14304 // fully general vector.
14308 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14309 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14311 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14312 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14313 return NumBits1 > NumBits2;
14316 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14317 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14320 if (!isTypeLegal(EVT::getEVT(Ty1)))
14323 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14325 // Assuming the caller doesn't have a zeroext or signext return parameter,
14326 // truncation all the way down to i1 is valid.
14330 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14331 return isInt<32>(Imm);
14334 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14335 // Can also use sub to handle negated immediates.
14336 return isInt<32>(Imm);
14339 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14340 if (!VT1.isInteger() || !VT2.isInteger())
14342 unsigned NumBits1 = VT1.getSizeInBits();
14343 unsigned NumBits2 = VT2.getSizeInBits();
14344 return NumBits1 > NumBits2;
14347 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14348 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14349 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14352 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14353 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14354 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14357 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14358 EVT VT1 = Val.getValueType();
14359 if (isZExtFree(VT1, VT2))
14362 if (Val.getOpcode() != ISD::LOAD)
14365 if (!VT1.isSimple() || !VT1.isInteger() ||
14366 !VT2.isSimple() || !VT2.isInteger())
14369 switch (VT1.getSimpleVT().SimpleTy) {
14374 // X86 has 8, 16, and 32-bit zero-extending loads.
14382 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14383 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14386 VT = VT.getScalarType();
14388 if (!VT.isSimple())
14391 switch (VT.getSimpleVT().SimpleTy) {
14402 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14403 // i16 instructions are longer (0x66 prefix) and potentially slower.
14404 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14407 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14408 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14409 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14410 /// are assumed to be legal.
14412 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14414 if (!VT.isSimple())
14417 MVT SVT = VT.getSimpleVT();
14419 // Very little shuffling can be done for 64-bit vectors right now.
14420 if (VT.getSizeInBits() == 64)
14423 // FIXME: pshufb, blends, shifts.
14424 return (SVT.getVectorNumElements() == 2 ||
14425 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14426 isMOVLMask(M, SVT) ||
14427 isSHUFPMask(M, SVT) ||
14428 isPSHUFDMask(M, SVT) ||
14429 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14430 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14431 isPALIGNRMask(M, SVT, Subtarget) ||
14432 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14433 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14434 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14435 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14439 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14441 if (!VT.isSimple())
14444 MVT SVT = VT.getSimpleVT();
14445 unsigned NumElts = SVT.getVectorNumElements();
14446 // FIXME: This collection of masks seems suspect.
14449 if (NumElts == 4 && SVT.is128BitVector()) {
14450 return (isMOVLMask(Mask, SVT) ||
14451 isCommutedMOVLMask(Mask, SVT, true) ||
14452 isSHUFPMask(Mask, SVT) ||
14453 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14458 //===----------------------------------------------------------------------===//
14459 // X86 Scheduler Hooks
14460 //===----------------------------------------------------------------------===//
14462 /// Utility function to emit xbegin specifying the start of an RTM region.
14463 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14464 const TargetInstrInfo *TII) {
14465 DebugLoc DL = MI->getDebugLoc();
14467 const BasicBlock *BB = MBB->getBasicBlock();
14468 MachineFunction::iterator I = MBB;
14471 // For the v = xbegin(), we generate
14482 MachineBasicBlock *thisMBB = MBB;
14483 MachineFunction *MF = MBB->getParent();
14484 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14485 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14486 MF->insert(I, mainMBB);
14487 MF->insert(I, sinkMBB);
14489 // Transfer the remainder of BB and its successor edges to sinkMBB.
14490 sinkMBB->splice(sinkMBB->begin(), MBB,
14491 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14492 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14496 // # fallthrough to mainMBB
14497 // # abortion to sinkMBB
14498 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14499 thisMBB->addSuccessor(mainMBB);
14500 thisMBB->addSuccessor(sinkMBB);
14504 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14505 mainMBB->addSuccessor(sinkMBB);
14508 // EAX is live into the sinkMBB
14509 sinkMBB->addLiveIn(X86::EAX);
14510 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14511 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14514 MI->eraseFromParent();
14518 // Get CMPXCHG opcode for the specified data type.
14519 static unsigned getCmpXChgOpcode(EVT VT) {
14520 switch (VT.getSimpleVT().SimpleTy) {
14521 case MVT::i8: return X86::LCMPXCHG8;
14522 case MVT::i16: return X86::LCMPXCHG16;
14523 case MVT::i32: return X86::LCMPXCHG32;
14524 case MVT::i64: return X86::LCMPXCHG64;
14528 llvm_unreachable("Invalid operand size!");
14531 // Get LOAD opcode for the specified data type.
14532 static unsigned getLoadOpcode(EVT VT) {
14533 switch (VT.getSimpleVT().SimpleTy) {
14534 case MVT::i8: return X86::MOV8rm;
14535 case MVT::i16: return X86::MOV16rm;
14536 case MVT::i32: return X86::MOV32rm;
14537 case MVT::i64: return X86::MOV64rm;
14541 llvm_unreachable("Invalid operand size!");
14544 // Get opcode of the non-atomic one from the specified atomic instruction.
14545 static unsigned getNonAtomicOpcode(unsigned Opc) {
14547 case X86::ATOMAND8: return X86::AND8rr;
14548 case X86::ATOMAND16: return X86::AND16rr;
14549 case X86::ATOMAND32: return X86::AND32rr;
14550 case X86::ATOMAND64: return X86::AND64rr;
14551 case X86::ATOMOR8: return X86::OR8rr;
14552 case X86::ATOMOR16: return X86::OR16rr;
14553 case X86::ATOMOR32: return X86::OR32rr;
14554 case X86::ATOMOR64: return X86::OR64rr;
14555 case X86::ATOMXOR8: return X86::XOR8rr;
14556 case X86::ATOMXOR16: return X86::XOR16rr;
14557 case X86::ATOMXOR32: return X86::XOR32rr;
14558 case X86::ATOMXOR64: return X86::XOR64rr;
14560 llvm_unreachable("Unhandled atomic-load-op opcode!");
14563 // Get opcode of the non-atomic one from the specified atomic instruction with
14565 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14566 unsigned &ExtraOpc) {
14568 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14569 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14570 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14571 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14572 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14573 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14574 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14575 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14576 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14577 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14578 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14579 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14580 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14581 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14582 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14583 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14584 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14585 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14586 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14587 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14589 llvm_unreachable("Unhandled atomic-load-op opcode!");
14592 // Get opcode of the non-atomic one from the specified atomic instruction for
14593 // 64-bit data type on 32-bit target.
14594 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14596 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14597 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14598 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14599 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14600 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14601 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14602 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14603 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14604 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14605 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14607 llvm_unreachable("Unhandled atomic-load-op opcode!");
14610 // Get opcode of the non-atomic one from the specified atomic instruction for
14611 // 64-bit data type on 32-bit target with extra opcode.
14612 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14614 unsigned &ExtraOpc) {
14616 case X86::ATOMNAND6432:
14617 ExtraOpc = X86::NOT32r;
14618 HiOpc = X86::AND32rr;
14619 return X86::AND32rr;
14621 llvm_unreachable("Unhandled atomic-load-op opcode!");
14624 // Get pseudo CMOV opcode from the specified data type.
14625 static unsigned getPseudoCMOVOpc(EVT VT) {
14626 switch (VT.getSimpleVT().SimpleTy) {
14627 case MVT::i8: return X86::CMOV_GR8;
14628 case MVT::i16: return X86::CMOV_GR16;
14629 case MVT::i32: return X86::CMOV_GR32;
14633 llvm_unreachable("Unknown CMOV opcode!");
14636 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14637 // They will be translated into a spin-loop or compare-exchange loop from
14640 // dst = atomic-fetch-op MI.addr, MI.val
14646 // t1 = LOAD MI.addr
14648 // t4 = phi(t1, t3 / loop)
14649 // t2 = OP MI.val, t4
14651 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14657 MachineBasicBlock *
14658 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14659 MachineBasicBlock *MBB) const {
14660 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14661 DebugLoc DL = MI->getDebugLoc();
14663 MachineFunction *MF = MBB->getParent();
14664 MachineRegisterInfo &MRI = MF->getRegInfo();
14666 const BasicBlock *BB = MBB->getBasicBlock();
14667 MachineFunction::iterator I = MBB;
14670 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14671 "Unexpected number of operands");
14673 assert(MI->hasOneMemOperand() &&
14674 "Expected atomic-load-op to have one memoperand");
14676 // Memory Reference
14677 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14678 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14680 unsigned DstReg, SrcReg;
14681 unsigned MemOpndSlot;
14683 unsigned CurOp = 0;
14685 DstReg = MI->getOperand(CurOp++).getReg();
14686 MemOpndSlot = CurOp;
14687 CurOp += X86::AddrNumOperands;
14688 SrcReg = MI->getOperand(CurOp++).getReg();
14690 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14691 MVT::SimpleValueType VT = *RC->vt_begin();
14692 unsigned t1 = MRI.createVirtualRegister(RC);
14693 unsigned t2 = MRI.createVirtualRegister(RC);
14694 unsigned t3 = MRI.createVirtualRegister(RC);
14695 unsigned t4 = MRI.createVirtualRegister(RC);
14696 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14698 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14699 unsigned LOADOpc = getLoadOpcode(VT);
14701 // For the atomic load-arith operator, we generate
14704 // t1 = LOAD [MI.addr]
14706 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
14707 // t1 = OP MI.val, EAX
14709 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14715 MachineBasicBlock *thisMBB = MBB;
14716 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14717 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14718 MF->insert(I, mainMBB);
14719 MF->insert(I, sinkMBB);
14721 MachineInstrBuilder MIB;
14723 // Transfer the remainder of BB and its successor edges to sinkMBB.
14724 sinkMBB->splice(sinkMBB->begin(), MBB,
14725 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14726 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14729 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14730 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14731 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14733 NewMO.setIsKill(false);
14734 MIB.addOperand(NewMO);
14736 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14737 unsigned flags = (*MMOI)->getFlags();
14738 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14739 MachineMemOperand *MMO =
14740 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14741 (*MMOI)->getSize(),
14742 (*MMOI)->getBaseAlignment(),
14743 (*MMOI)->getTBAAInfo(),
14744 (*MMOI)->getRanges());
14745 MIB.addMemOperand(MMO);
14748 thisMBB->addSuccessor(mainMBB);
14751 MachineBasicBlock *origMainMBB = mainMBB;
14754 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14755 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14757 unsigned Opc = MI->getOpcode();
14760 llvm_unreachable("Unhandled atomic-load-op opcode!");
14761 case X86::ATOMAND8:
14762 case X86::ATOMAND16:
14763 case X86::ATOMAND32:
14764 case X86::ATOMAND64:
14766 case X86::ATOMOR16:
14767 case X86::ATOMOR32:
14768 case X86::ATOMOR64:
14769 case X86::ATOMXOR8:
14770 case X86::ATOMXOR16:
14771 case X86::ATOMXOR32:
14772 case X86::ATOMXOR64: {
14773 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14774 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14778 case X86::ATOMNAND8:
14779 case X86::ATOMNAND16:
14780 case X86::ATOMNAND32:
14781 case X86::ATOMNAND64: {
14782 unsigned Tmp = MRI.createVirtualRegister(RC);
14784 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14785 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14787 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14790 case X86::ATOMMAX8:
14791 case X86::ATOMMAX16:
14792 case X86::ATOMMAX32:
14793 case X86::ATOMMAX64:
14794 case X86::ATOMMIN8:
14795 case X86::ATOMMIN16:
14796 case X86::ATOMMIN32:
14797 case X86::ATOMMIN64:
14798 case X86::ATOMUMAX8:
14799 case X86::ATOMUMAX16:
14800 case X86::ATOMUMAX32:
14801 case X86::ATOMUMAX64:
14802 case X86::ATOMUMIN8:
14803 case X86::ATOMUMIN16:
14804 case X86::ATOMUMIN32:
14805 case X86::ATOMUMIN64: {
14807 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14809 BuildMI(mainMBB, DL, TII->get(CMPOpc))
14813 if (Subtarget->hasCMov()) {
14814 if (VT != MVT::i8) {
14816 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14820 // Promote i8 to i32 to use CMOV32
14821 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14822 const TargetRegisterClass *RC32 =
14823 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14824 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14825 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14826 unsigned Tmp = MRI.createVirtualRegister(RC32);
14828 unsigned Undef = MRI.createVirtualRegister(RC32);
14829 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14831 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14834 .addImm(X86::sub_8bit);
14835 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14838 .addImm(X86::sub_8bit);
14840 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14844 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14845 .addReg(Tmp, 0, X86::sub_8bit);
14848 // Use pseudo select and lower them.
14849 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14850 "Invalid atomic-load-op transformation!");
14851 unsigned SelOpc = getPseudoCMOVOpc(VT);
14852 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14853 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14854 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14855 .addReg(SrcReg).addReg(t4)
14857 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14858 // Replace the original PHI node as mainMBB is changed after CMOV
14860 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14861 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14862 Phi->eraseFromParent();
14868 // Copy PhyReg back from virtual register.
14869 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14872 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14873 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14874 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14876 NewMO.setIsKill(false);
14877 MIB.addOperand(NewMO);
14880 MIB.setMemRefs(MMOBegin, MMOEnd);
14882 // Copy PhyReg back to virtual register.
14883 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14886 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14888 mainMBB->addSuccessor(origMainMBB);
14889 mainMBB->addSuccessor(sinkMBB);
14892 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14893 TII->get(TargetOpcode::COPY), DstReg)
14896 MI->eraseFromParent();
14900 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14901 // instructions. They will be translated into a spin-loop or compare-exchange
14905 // dst = atomic-fetch-op MI.addr, MI.val
14911 // t1L = LOAD [MI.addr + 0]
14912 // t1H = LOAD [MI.addr + 4]
14914 // t4L = phi(t1L, t3L / loop)
14915 // t4H = phi(t1H, t3H / loop)
14916 // t2L = OP MI.val.lo, t4L
14917 // t2H = OP MI.val.hi, t4H
14922 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14930 MachineBasicBlock *
14931 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14932 MachineBasicBlock *MBB) const {
14933 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14934 DebugLoc DL = MI->getDebugLoc();
14936 MachineFunction *MF = MBB->getParent();
14937 MachineRegisterInfo &MRI = MF->getRegInfo();
14939 const BasicBlock *BB = MBB->getBasicBlock();
14940 MachineFunction::iterator I = MBB;
14943 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14944 "Unexpected number of operands");
14946 assert(MI->hasOneMemOperand() &&
14947 "Expected atomic-load-op32 to have one memoperand");
14949 // Memory Reference
14950 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14951 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14953 unsigned DstLoReg, DstHiReg;
14954 unsigned SrcLoReg, SrcHiReg;
14955 unsigned MemOpndSlot;
14957 unsigned CurOp = 0;
14959 DstLoReg = MI->getOperand(CurOp++).getReg();
14960 DstHiReg = MI->getOperand(CurOp++).getReg();
14961 MemOpndSlot = CurOp;
14962 CurOp += X86::AddrNumOperands;
14963 SrcLoReg = MI->getOperand(CurOp++).getReg();
14964 SrcHiReg = MI->getOperand(CurOp++).getReg();
14966 const TargetRegisterClass *RC = &X86::GR32RegClass;
14967 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14969 unsigned t1L = MRI.createVirtualRegister(RC);
14970 unsigned t1H = MRI.createVirtualRegister(RC);
14971 unsigned t2L = MRI.createVirtualRegister(RC);
14972 unsigned t2H = MRI.createVirtualRegister(RC);
14973 unsigned t3L = MRI.createVirtualRegister(RC);
14974 unsigned t3H = MRI.createVirtualRegister(RC);
14975 unsigned t4L = MRI.createVirtualRegister(RC);
14976 unsigned t4H = MRI.createVirtualRegister(RC);
14978 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14979 unsigned LOADOpc = X86::MOV32rm;
14981 // For the atomic load-arith operator, we generate
14984 // t1L = LOAD [MI.addr + 0]
14985 // t1H = LOAD [MI.addr + 4]
14987 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
14988 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
14989 // t2L = OP MI.val.lo, t4L
14990 // t2H = OP MI.val.hi, t4H
14993 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15001 MachineBasicBlock *thisMBB = MBB;
15002 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15003 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15004 MF->insert(I, mainMBB);
15005 MF->insert(I, sinkMBB);
15007 MachineInstrBuilder MIB;
15009 // Transfer the remainder of BB and its successor edges to sinkMBB.
15010 sinkMBB->splice(sinkMBB->begin(), MBB,
15011 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15012 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15016 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15017 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15018 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15020 NewMO.setIsKill(false);
15021 MIB.addOperand(NewMO);
15023 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15024 unsigned flags = (*MMOI)->getFlags();
15025 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15026 MachineMemOperand *MMO =
15027 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15028 (*MMOI)->getSize(),
15029 (*MMOI)->getBaseAlignment(),
15030 (*MMOI)->getTBAAInfo(),
15031 (*MMOI)->getRanges());
15032 MIB.addMemOperand(MMO);
15034 MachineInstr *LowMI = MIB;
15037 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15038 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15039 if (i == X86::AddrDisp) {
15040 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15042 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15044 NewMO.setIsKill(false);
15045 MIB.addOperand(NewMO);
15048 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15050 thisMBB->addSuccessor(mainMBB);
15053 MachineBasicBlock *origMainMBB = mainMBB;
15056 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15057 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15058 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15059 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15061 unsigned Opc = MI->getOpcode();
15064 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15065 case X86::ATOMAND6432:
15066 case X86::ATOMOR6432:
15067 case X86::ATOMXOR6432:
15068 case X86::ATOMADD6432:
15069 case X86::ATOMSUB6432: {
15071 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15072 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15074 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15078 case X86::ATOMNAND6432: {
15079 unsigned HiOpc, NOTOpc;
15080 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15081 unsigned TmpL = MRI.createVirtualRegister(RC);
15082 unsigned TmpH = MRI.createVirtualRegister(RC);
15083 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15085 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15087 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15088 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15091 case X86::ATOMMAX6432:
15092 case X86::ATOMMIN6432:
15093 case X86::ATOMUMAX6432:
15094 case X86::ATOMUMIN6432: {
15096 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15097 unsigned cL = MRI.createVirtualRegister(RC8);
15098 unsigned cH = MRI.createVirtualRegister(RC8);
15099 unsigned cL32 = MRI.createVirtualRegister(RC);
15100 unsigned cH32 = MRI.createVirtualRegister(RC);
15101 unsigned cc = MRI.createVirtualRegister(RC);
15102 // cl := cmp src_lo, lo
15103 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15104 .addReg(SrcLoReg).addReg(t4L);
15105 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15106 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15107 // ch := cmp src_hi, hi
15108 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15109 .addReg(SrcHiReg).addReg(t4H);
15110 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15111 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15112 // cc := if (src_hi == hi) ? cl : ch;
15113 if (Subtarget->hasCMov()) {
15114 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15115 .addReg(cH32).addReg(cL32);
15117 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15118 .addReg(cH32).addReg(cL32)
15119 .addImm(X86::COND_E);
15120 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15122 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15123 if (Subtarget->hasCMov()) {
15124 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15125 .addReg(SrcLoReg).addReg(t4L);
15126 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15127 .addReg(SrcHiReg).addReg(t4H);
15129 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15130 .addReg(SrcLoReg).addReg(t4L)
15131 .addImm(X86::COND_NE);
15132 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15133 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15134 // 2nd CMOV lowering.
15135 mainMBB->addLiveIn(X86::EFLAGS);
15136 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15137 .addReg(SrcHiReg).addReg(t4H)
15138 .addImm(X86::COND_NE);
15139 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15140 // Replace the original PHI node as mainMBB is changed after CMOV
15142 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15143 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15144 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15145 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15146 PhiL->eraseFromParent();
15147 PhiH->eraseFromParent();
15151 case X86::ATOMSWAP6432: {
15153 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15154 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15155 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15160 // Copy EDX:EAX back from HiReg:LoReg
15161 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15162 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15163 // Copy ECX:EBX from t1H:t1L
15164 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15165 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15167 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15168 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15169 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15171 NewMO.setIsKill(false);
15172 MIB.addOperand(NewMO);
15174 MIB.setMemRefs(MMOBegin, MMOEnd);
15176 // Copy EDX:EAX back to t3H:t3L
15177 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15178 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15180 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15182 mainMBB->addSuccessor(origMainMBB);
15183 mainMBB->addSuccessor(sinkMBB);
15186 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15187 TII->get(TargetOpcode::COPY), DstLoReg)
15189 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15190 TII->get(TargetOpcode::COPY), DstHiReg)
15193 MI->eraseFromParent();
15197 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15198 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15199 // in the .td file.
15200 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15201 const TargetInstrInfo *TII) {
15203 switch (MI->getOpcode()) {
15204 default: llvm_unreachable("illegal opcode!");
15205 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15206 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15207 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15208 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15209 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15210 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15211 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15212 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15215 DebugLoc dl = MI->getDebugLoc();
15216 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15218 unsigned NumArgs = MI->getNumOperands();
15219 for (unsigned i = 1; i < NumArgs; ++i) {
15220 MachineOperand &Op = MI->getOperand(i);
15221 if (!(Op.isReg() && Op.isImplicit()))
15222 MIB.addOperand(Op);
15224 if (MI->hasOneMemOperand())
15225 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15227 BuildMI(*BB, MI, dl,
15228 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15229 .addReg(X86::XMM0);
15231 MI->eraseFromParent();
15235 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15236 // defs in an instruction pattern
15237 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15238 const TargetInstrInfo *TII) {
15240 switch (MI->getOpcode()) {
15241 default: llvm_unreachable("illegal opcode!");
15242 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15243 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15244 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15245 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15246 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15247 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15248 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15249 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15252 DebugLoc dl = MI->getDebugLoc();
15253 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15255 unsigned NumArgs = MI->getNumOperands(); // remove the results
15256 for (unsigned i = 1; i < NumArgs; ++i) {
15257 MachineOperand &Op = MI->getOperand(i);
15258 if (!(Op.isReg() && Op.isImplicit()))
15259 MIB.addOperand(Op);
15261 if (MI->hasOneMemOperand())
15262 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15264 BuildMI(*BB, MI, dl,
15265 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15268 MI->eraseFromParent();
15272 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15273 const TargetInstrInfo *TII,
15274 const X86Subtarget* Subtarget) {
15275 DebugLoc dl = MI->getDebugLoc();
15277 // Address into RAX/EAX, other two args into ECX, EDX.
15278 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15279 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15280 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15281 for (int i = 0; i < X86::AddrNumOperands; ++i)
15282 MIB.addOperand(MI->getOperand(i));
15284 unsigned ValOps = X86::AddrNumOperands;
15285 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15286 .addReg(MI->getOperand(ValOps).getReg());
15287 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15288 .addReg(MI->getOperand(ValOps+1).getReg());
15290 // The instruction doesn't actually take any operands though.
15291 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15293 MI->eraseFromParent(); // The pseudo is gone now.
15297 MachineBasicBlock *
15298 X86TargetLowering::EmitVAARG64WithCustomInserter(
15300 MachineBasicBlock *MBB) const {
15301 // Emit va_arg instruction on X86-64.
15303 // Operands to this pseudo-instruction:
15304 // 0 ) Output : destination address (reg)
15305 // 1-5) Input : va_list address (addr, i64mem)
15306 // 6 ) ArgSize : Size (in bytes) of vararg type
15307 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15308 // 8 ) Align : Alignment of type
15309 // 9 ) EFLAGS (implicit-def)
15311 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15312 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15314 unsigned DestReg = MI->getOperand(0).getReg();
15315 MachineOperand &Base = MI->getOperand(1);
15316 MachineOperand &Scale = MI->getOperand(2);
15317 MachineOperand &Index = MI->getOperand(3);
15318 MachineOperand &Disp = MI->getOperand(4);
15319 MachineOperand &Segment = MI->getOperand(5);
15320 unsigned ArgSize = MI->getOperand(6).getImm();
15321 unsigned ArgMode = MI->getOperand(7).getImm();
15322 unsigned Align = MI->getOperand(8).getImm();
15324 // Memory Reference
15325 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15326 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15327 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15329 // Machine Information
15330 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15331 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15332 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15333 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15334 DebugLoc DL = MI->getDebugLoc();
15336 // struct va_list {
15339 // i64 overflow_area (address)
15340 // i64 reg_save_area (address)
15342 // sizeof(va_list) = 24
15343 // alignment(va_list) = 8
15345 unsigned TotalNumIntRegs = 6;
15346 unsigned TotalNumXMMRegs = 8;
15347 bool UseGPOffset = (ArgMode == 1);
15348 bool UseFPOffset = (ArgMode == 2);
15349 unsigned MaxOffset = TotalNumIntRegs * 8 +
15350 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15352 /* Align ArgSize to a multiple of 8 */
15353 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15354 bool NeedsAlign = (Align > 8);
15356 MachineBasicBlock *thisMBB = MBB;
15357 MachineBasicBlock *overflowMBB;
15358 MachineBasicBlock *offsetMBB;
15359 MachineBasicBlock *endMBB;
15361 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15362 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15363 unsigned OffsetReg = 0;
15365 if (!UseGPOffset && !UseFPOffset) {
15366 // If we only pull from the overflow region, we don't create a branch.
15367 // We don't need to alter control flow.
15368 OffsetDestReg = 0; // unused
15369 OverflowDestReg = DestReg;
15372 overflowMBB = thisMBB;
15375 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15376 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15377 // If not, pull from overflow_area. (branch to overflowMBB)
15382 // offsetMBB overflowMBB
15387 // Registers for the PHI in endMBB
15388 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15389 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15391 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15392 MachineFunction *MF = MBB->getParent();
15393 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15394 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15395 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15397 MachineFunction::iterator MBBIter = MBB;
15400 // Insert the new basic blocks
15401 MF->insert(MBBIter, offsetMBB);
15402 MF->insert(MBBIter, overflowMBB);
15403 MF->insert(MBBIter, endMBB);
15405 // Transfer the remainder of MBB and its successor edges to endMBB.
15406 endMBB->splice(endMBB->begin(), thisMBB,
15407 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15408 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15410 // Make offsetMBB and overflowMBB successors of thisMBB
15411 thisMBB->addSuccessor(offsetMBB);
15412 thisMBB->addSuccessor(overflowMBB);
15414 // endMBB is a successor of both offsetMBB and overflowMBB
15415 offsetMBB->addSuccessor(endMBB);
15416 overflowMBB->addSuccessor(endMBB);
15418 // Load the offset value into a register
15419 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15420 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15424 .addDisp(Disp, UseFPOffset ? 4 : 0)
15425 .addOperand(Segment)
15426 .setMemRefs(MMOBegin, MMOEnd);
15428 // Check if there is enough room left to pull this argument.
15429 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15431 .addImm(MaxOffset + 8 - ArgSizeA8);
15433 // Branch to "overflowMBB" if offset >= max
15434 // Fall through to "offsetMBB" otherwise
15435 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15436 .addMBB(overflowMBB);
15439 // In offsetMBB, emit code to use the reg_save_area.
15441 assert(OffsetReg != 0);
15443 // Read the reg_save_area address.
15444 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15445 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15450 .addOperand(Segment)
15451 .setMemRefs(MMOBegin, MMOEnd);
15453 // Zero-extend the offset
15454 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15455 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15458 .addImm(X86::sub_32bit);
15460 // Add the offset to the reg_save_area to get the final address.
15461 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15462 .addReg(OffsetReg64)
15463 .addReg(RegSaveReg);
15465 // Compute the offset for the next argument
15466 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15467 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15469 .addImm(UseFPOffset ? 16 : 8);
15471 // Store it back into the va_list.
15472 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15476 .addDisp(Disp, UseFPOffset ? 4 : 0)
15477 .addOperand(Segment)
15478 .addReg(NextOffsetReg)
15479 .setMemRefs(MMOBegin, MMOEnd);
15482 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15487 // Emit code to use overflow area
15490 // Load the overflow_area address into a register.
15491 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15492 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15497 .addOperand(Segment)
15498 .setMemRefs(MMOBegin, MMOEnd);
15500 // If we need to align it, do so. Otherwise, just copy the address
15501 // to OverflowDestReg.
15503 // Align the overflow address
15504 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15505 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15507 // aligned_addr = (addr + (align-1)) & ~(align-1)
15508 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15509 .addReg(OverflowAddrReg)
15512 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15514 .addImm(~(uint64_t)(Align-1));
15516 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15517 .addReg(OverflowAddrReg);
15520 // Compute the next overflow address after this argument.
15521 // (the overflow address should be kept 8-byte aligned)
15522 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15523 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15524 .addReg(OverflowDestReg)
15525 .addImm(ArgSizeA8);
15527 // Store the new overflow address.
15528 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15533 .addOperand(Segment)
15534 .addReg(NextAddrReg)
15535 .setMemRefs(MMOBegin, MMOEnd);
15537 // If we branched, emit the PHI to the front of endMBB.
15539 BuildMI(*endMBB, endMBB->begin(), DL,
15540 TII->get(X86::PHI), DestReg)
15541 .addReg(OffsetDestReg).addMBB(offsetMBB)
15542 .addReg(OverflowDestReg).addMBB(overflowMBB);
15545 // Erase the pseudo instruction
15546 MI->eraseFromParent();
15551 MachineBasicBlock *
15552 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15554 MachineBasicBlock *MBB) const {
15555 // Emit code to save XMM registers to the stack. The ABI says that the
15556 // number of registers to save is given in %al, so it's theoretically
15557 // possible to do an indirect jump trick to avoid saving all of them,
15558 // however this code takes a simpler approach and just executes all
15559 // of the stores if %al is non-zero. It's less code, and it's probably
15560 // easier on the hardware branch predictor, and stores aren't all that
15561 // expensive anyway.
15563 // Create the new basic blocks. One block contains all the XMM stores,
15564 // and one block is the final destination regardless of whether any
15565 // stores were performed.
15566 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15567 MachineFunction *F = MBB->getParent();
15568 MachineFunction::iterator MBBIter = MBB;
15570 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15571 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15572 F->insert(MBBIter, XMMSaveMBB);
15573 F->insert(MBBIter, EndMBB);
15575 // Transfer the remainder of MBB and its successor edges to EndMBB.
15576 EndMBB->splice(EndMBB->begin(), MBB,
15577 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15578 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15580 // The original block will now fall through to the XMM save block.
15581 MBB->addSuccessor(XMMSaveMBB);
15582 // The XMMSaveMBB will fall through to the end block.
15583 XMMSaveMBB->addSuccessor(EndMBB);
15585 // Now add the instructions.
15586 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15587 DebugLoc DL = MI->getDebugLoc();
15589 unsigned CountReg = MI->getOperand(0).getReg();
15590 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15591 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15593 if (!Subtarget->isTargetWin64()) {
15594 // If %al is 0, branch around the XMM save block.
15595 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15596 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15597 MBB->addSuccessor(EndMBB);
15600 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15601 // that was just emitted, but clearly shouldn't be "saved".
15602 assert((MI->getNumOperands() <= 3 ||
15603 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15604 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15605 && "Expected last argument to be EFLAGS");
15606 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15607 // In the XMM save block, save all the XMM argument registers.
15608 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15609 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15610 MachineMemOperand *MMO =
15611 F->getMachineMemOperand(
15612 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15613 MachineMemOperand::MOStore,
15614 /*Size=*/16, /*Align=*/16);
15615 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15616 .addFrameIndex(RegSaveFrameIndex)
15617 .addImm(/*Scale=*/1)
15618 .addReg(/*IndexReg=*/0)
15619 .addImm(/*Disp=*/Offset)
15620 .addReg(/*Segment=*/0)
15621 .addReg(MI->getOperand(i).getReg())
15622 .addMemOperand(MMO);
15625 MI->eraseFromParent(); // The pseudo instruction is gone now.
15630 // The EFLAGS operand of SelectItr might be missing a kill marker
15631 // because there were multiple uses of EFLAGS, and ISel didn't know
15632 // which to mark. Figure out whether SelectItr should have had a
15633 // kill marker, and set it if it should. Returns the correct kill
15635 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15636 MachineBasicBlock* BB,
15637 const TargetRegisterInfo* TRI) {
15638 // Scan forward through BB for a use/def of EFLAGS.
15639 MachineBasicBlock::iterator miI(std::next(SelectItr));
15640 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15641 const MachineInstr& mi = *miI;
15642 if (mi.readsRegister(X86::EFLAGS))
15644 if (mi.definesRegister(X86::EFLAGS))
15645 break; // Should have kill-flag - update below.
15648 // If we hit the end of the block, check whether EFLAGS is live into a
15650 if (miI == BB->end()) {
15651 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15652 sEnd = BB->succ_end();
15653 sItr != sEnd; ++sItr) {
15654 MachineBasicBlock* succ = *sItr;
15655 if (succ->isLiveIn(X86::EFLAGS))
15660 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15661 // out. SelectMI should have a kill flag on EFLAGS.
15662 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15666 MachineBasicBlock *
15667 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15668 MachineBasicBlock *BB) const {
15669 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15670 DebugLoc DL = MI->getDebugLoc();
15672 // To "insert" a SELECT_CC instruction, we actually have to insert the
15673 // diamond control-flow pattern. The incoming instruction knows the
15674 // destination vreg to set, the condition code register to branch on, the
15675 // true/false values to select between, and a branch opcode to use.
15676 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15677 MachineFunction::iterator It = BB;
15683 // cmpTY ccX, r1, r2
15685 // fallthrough --> copy0MBB
15686 MachineBasicBlock *thisMBB = BB;
15687 MachineFunction *F = BB->getParent();
15688 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15689 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15690 F->insert(It, copy0MBB);
15691 F->insert(It, sinkMBB);
15693 // If the EFLAGS register isn't dead in the terminator, then claim that it's
15694 // live into the sink and copy blocks.
15695 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15696 if (!MI->killsRegister(X86::EFLAGS) &&
15697 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15698 copy0MBB->addLiveIn(X86::EFLAGS);
15699 sinkMBB->addLiveIn(X86::EFLAGS);
15702 // Transfer the remainder of BB and its successor edges to sinkMBB.
15703 sinkMBB->splice(sinkMBB->begin(), BB,
15704 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15705 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15707 // Add the true and fallthrough blocks as its successors.
15708 BB->addSuccessor(copy0MBB);
15709 BB->addSuccessor(sinkMBB);
15711 // Create the conditional branch instruction.
15713 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15714 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15717 // %FalseValue = ...
15718 // # fallthrough to sinkMBB
15719 copy0MBB->addSuccessor(sinkMBB);
15722 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15724 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15725 TII->get(X86::PHI), MI->getOperand(0).getReg())
15726 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15727 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15729 MI->eraseFromParent(); // The pseudo instruction is gone now.
15733 MachineBasicBlock *
15734 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15735 bool Is64Bit) const {
15736 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15737 DebugLoc DL = MI->getDebugLoc();
15738 MachineFunction *MF = BB->getParent();
15739 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15741 assert(getTargetMachine().Options.EnableSegmentedStacks);
15743 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15744 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15747 // ... [Till the alloca]
15748 // If stacklet is not large enough, jump to mallocMBB
15751 // Allocate by subtracting from RSP
15752 // Jump to continueMBB
15755 // Allocate by call to runtime
15759 // [rest of original BB]
15762 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15763 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15764 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15766 MachineRegisterInfo &MRI = MF->getRegInfo();
15767 const TargetRegisterClass *AddrRegClass =
15768 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15770 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15771 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15772 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15773 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15774 sizeVReg = MI->getOperand(1).getReg(),
15775 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15777 MachineFunction::iterator MBBIter = BB;
15780 MF->insert(MBBIter, bumpMBB);
15781 MF->insert(MBBIter, mallocMBB);
15782 MF->insert(MBBIter, continueMBB);
15784 continueMBB->splice(continueMBB->begin(), BB,
15785 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15786 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15788 // Add code to the main basic block to check if the stack limit has been hit,
15789 // and if so, jump to mallocMBB otherwise to bumpMBB.
15790 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15791 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15792 .addReg(tmpSPVReg).addReg(sizeVReg);
15793 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15794 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15795 .addReg(SPLimitVReg);
15796 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15798 // bumpMBB simply decreases the stack pointer, since we know the current
15799 // stacklet has enough space.
15800 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15801 .addReg(SPLimitVReg);
15802 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15803 .addReg(SPLimitVReg);
15804 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15806 // Calls into a routine in libgcc to allocate more space from the heap.
15807 const uint32_t *RegMask =
15808 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15810 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15812 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15813 .addExternalSymbol("__morestack_allocate_stack_space")
15814 .addRegMask(RegMask)
15815 .addReg(X86::RDI, RegState::Implicit)
15816 .addReg(X86::RAX, RegState::ImplicitDefine);
15818 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15820 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15821 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15822 .addExternalSymbol("__morestack_allocate_stack_space")
15823 .addRegMask(RegMask)
15824 .addReg(X86::EAX, RegState::ImplicitDefine);
15828 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15831 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15832 .addReg(Is64Bit ? X86::RAX : X86::EAX);
15833 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15835 // Set up the CFG correctly.
15836 BB->addSuccessor(bumpMBB);
15837 BB->addSuccessor(mallocMBB);
15838 mallocMBB->addSuccessor(continueMBB);
15839 bumpMBB->addSuccessor(continueMBB);
15841 // Take care of the PHI nodes.
15842 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15843 MI->getOperand(0).getReg())
15844 .addReg(mallocPtrVReg).addMBB(mallocMBB)
15845 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15847 // Delete the original pseudo instruction.
15848 MI->eraseFromParent();
15851 return continueMBB;
15854 MachineBasicBlock *
15855 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15856 MachineBasicBlock *BB) const {
15857 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15858 DebugLoc DL = MI->getDebugLoc();
15860 assert(!Subtarget->isTargetMacho());
15862 // The lowering is pretty easy: we're just emitting the call to _alloca. The
15863 // non-trivial part is impdef of ESP.
15865 if (Subtarget->isTargetWin64()) {
15866 if (Subtarget->isTargetCygMing()) {
15867 // ___chkstk(Mingw64):
15868 // Clobbers R10, R11, RAX and EFLAGS.
15870 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15871 .addExternalSymbol("___chkstk")
15872 .addReg(X86::RAX, RegState::Implicit)
15873 .addReg(X86::RSP, RegState::Implicit)
15874 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15875 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15876 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15878 // __chkstk(MSVCRT): does not update stack pointer.
15879 // Clobbers R10, R11 and EFLAGS.
15880 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15881 .addExternalSymbol("__chkstk")
15882 .addReg(X86::RAX, RegState::Implicit)
15883 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15884 // RAX has the offset to be subtracted from RSP.
15885 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15890 const char *StackProbeSymbol =
15891 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
15893 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15894 .addExternalSymbol(StackProbeSymbol)
15895 .addReg(X86::EAX, RegState::Implicit)
15896 .addReg(X86::ESP, RegState::Implicit)
15897 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15898 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15899 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15902 MI->eraseFromParent(); // The pseudo instruction is gone now.
15906 MachineBasicBlock *
15907 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15908 MachineBasicBlock *BB) const {
15909 // This is pretty easy. We're taking the value that we received from
15910 // our load from the relocation, sticking it in either RDI (x86-64)
15911 // or EAX and doing an indirect call. The return value will then
15912 // be in the normal return register.
15913 const X86InstrInfo *TII
15914 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15915 DebugLoc DL = MI->getDebugLoc();
15916 MachineFunction *F = BB->getParent();
15918 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15919 assert(MI->getOperand(3).isGlobal() && "This should be a global");
15921 // Get a register mask for the lowered call.
15922 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15923 // proper register mask.
15924 const uint32_t *RegMask =
15925 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15926 if (Subtarget->is64Bit()) {
15927 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15928 TII->get(X86::MOV64rm), X86::RDI)
15930 .addImm(0).addReg(0)
15931 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15932 MI->getOperand(3).getTargetFlags())
15934 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15935 addDirectMem(MIB, X86::RDI);
15936 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15937 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15938 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15939 TII->get(X86::MOV32rm), X86::EAX)
15941 .addImm(0).addReg(0)
15942 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15943 MI->getOperand(3).getTargetFlags())
15945 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15946 addDirectMem(MIB, X86::EAX);
15947 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15949 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15950 TII->get(X86::MOV32rm), X86::EAX)
15951 .addReg(TII->getGlobalBaseReg(F))
15952 .addImm(0).addReg(0)
15953 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15954 MI->getOperand(3).getTargetFlags())
15956 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15957 addDirectMem(MIB, X86::EAX);
15958 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15961 MI->eraseFromParent(); // The pseudo instruction is gone now.
15965 MachineBasicBlock *
15966 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15967 MachineBasicBlock *MBB) const {
15968 DebugLoc DL = MI->getDebugLoc();
15969 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15971 MachineFunction *MF = MBB->getParent();
15972 MachineRegisterInfo &MRI = MF->getRegInfo();
15974 const BasicBlock *BB = MBB->getBasicBlock();
15975 MachineFunction::iterator I = MBB;
15978 // Memory Reference
15979 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15980 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15983 unsigned MemOpndSlot = 0;
15985 unsigned CurOp = 0;
15987 DstReg = MI->getOperand(CurOp++).getReg();
15988 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15989 assert(RC->hasType(MVT::i32) && "Invalid destination!");
15990 unsigned mainDstReg = MRI.createVirtualRegister(RC);
15991 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15993 MemOpndSlot = CurOp;
15995 MVT PVT = getPointerTy();
15996 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15997 "Invalid Pointer Size!");
15999 // For v = setjmp(buf), we generate
16002 // buf[LabelOffset] = restoreMBB
16003 // SjLjSetup restoreMBB
16009 // v = phi(main, restore)
16014 MachineBasicBlock *thisMBB = MBB;
16015 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16016 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16017 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16018 MF->insert(I, mainMBB);
16019 MF->insert(I, sinkMBB);
16020 MF->push_back(restoreMBB);
16022 MachineInstrBuilder MIB;
16024 // Transfer the remainder of BB and its successor edges to sinkMBB.
16025 sinkMBB->splice(sinkMBB->begin(), MBB,
16026 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16027 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16030 unsigned PtrStoreOpc = 0;
16031 unsigned LabelReg = 0;
16032 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16033 Reloc::Model RM = getTargetMachine().getRelocationModel();
16034 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16035 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16037 // Prepare IP either in reg or imm.
16038 if (!UseImmLabel) {
16039 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16040 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16041 LabelReg = MRI.createVirtualRegister(PtrRC);
16042 if (Subtarget->is64Bit()) {
16043 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16047 .addMBB(restoreMBB)
16050 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16051 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16052 .addReg(XII->getGlobalBaseReg(MF))
16055 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16059 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16061 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16062 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16063 if (i == X86::AddrDisp)
16064 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16066 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16069 MIB.addReg(LabelReg);
16071 MIB.addMBB(restoreMBB);
16072 MIB.setMemRefs(MMOBegin, MMOEnd);
16074 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16075 .addMBB(restoreMBB);
16077 const X86RegisterInfo *RegInfo =
16078 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16079 MIB.addRegMask(RegInfo->getNoPreservedMask());
16080 thisMBB->addSuccessor(mainMBB);
16081 thisMBB->addSuccessor(restoreMBB);
16085 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16086 mainMBB->addSuccessor(sinkMBB);
16089 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16090 TII->get(X86::PHI), DstReg)
16091 .addReg(mainDstReg).addMBB(mainMBB)
16092 .addReg(restoreDstReg).addMBB(restoreMBB);
16095 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16096 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16097 restoreMBB->addSuccessor(sinkMBB);
16099 MI->eraseFromParent();
16103 MachineBasicBlock *
16104 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16105 MachineBasicBlock *MBB) const {
16106 DebugLoc DL = MI->getDebugLoc();
16107 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16109 MachineFunction *MF = MBB->getParent();
16110 MachineRegisterInfo &MRI = MF->getRegInfo();
16112 // Memory Reference
16113 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16114 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16116 MVT PVT = getPointerTy();
16117 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16118 "Invalid Pointer Size!");
16120 const TargetRegisterClass *RC =
16121 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16122 unsigned Tmp = MRI.createVirtualRegister(RC);
16123 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16124 const X86RegisterInfo *RegInfo =
16125 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16126 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16127 unsigned SP = RegInfo->getStackRegister();
16129 MachineInstrBuilder MIB;
16131 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16132 const int64_t SPOffset = 2 * PVT.getStoreSize();
16134 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16135 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16138 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16139 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16140 MIB.addOperand(MI->getOperand(i));
16141 MIB.setMemRefs(MMOBegin, MMOEnd);
16143 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16144 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16145 if (i == X86::AddrDisp)
16146 MIB.addDisp(MI->getOperand(i), LabelOffset);
16148 MIB.addOperand(MI->getOperand(i));
16150 MIB.setMemRefs(MMOBegin, MMOEnd);
16152 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16153 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16154 if (i == X86::AddrDisp)
16155 MIB.addDisp(MI->getOperand(i), SPOffset);
16157 MIB.addOperand(MI->getOperand(i));
16159 MIB.setMemRefs(MMOBegin, MMOEnd);
16161 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16163 MI->eraseFromParent();
16167 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16168 // accumulator loops. Writing back to the accumulator allows the coalescer
16169 // to remove extra copies in the loop.
16170 MachineBasicBlock *
16171 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16172 MachineBasicBlock *MBB) const {
16173 MachineOperand &AddendOp = MI->getOperand(3);
16175 // Bail out early if the addend isn't a register - we can't switch these.
16176 if (!AddendOp.isReg())
16179 MachineFunction &MF = *MBB->getParent();
16180 MachineRegisterInfo &MRI = MF.getRegInfo();
16182 // Check whether the addend is defined by a PHI:
16183 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16184 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16185 if (!AddendDef.isPHI())
16188 // Look for the following pattern:
16190 // %addend = phi [%entry, 0], [%loop, %result]
16192 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16196 // %addend = phi [%entry, 0], [%loop, %result]
16198 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16200 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16201 assert(AddendDef.getOperand(i).isReg());
16202 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16203 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16204 if (&PHISrcInst == MI) {
16205 // Found a matching instruction.
16206 unsigned NewFMAOpc = 0;
16207 switch (MI->getOpcode()) {
16208 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16209 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16210 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16211 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16212 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16213 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16214 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16215 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16216 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16217 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16218 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16219 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16220 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16221 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16222 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16223 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16224 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16225 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16226 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16227 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16228 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16229 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16230 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16231 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16232 default: llvm_unreachable("Unrecognized FMA variant.");
16235 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16236 MachineInstrBuilder MIB =
16237 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16238 .addOperand(MI->getOperand(0))
16239 .addOperand(MI->getOperand(3))
16240 .addOperand(MI->getOperand(2))
16241 .addOperand(MI->getOperand(1));
16242 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16243 MI->eraseFromParent();
16250 MachineBasicBlock *
16251 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16252 MachineBasicBlock *BB) const {
16253 switch (MI->getOpcode()) {
16254 default: llvm_unreachable("Unexpected instr type to insert");
16255 case X86::TAILJMPd64:
16256 case X86::TAILJMPr64:
16257 case X86::TAILJMPm64:
16258 llvm_unreachable("TAILJMP64 would not be touched here.");
16259 case X86::TCRETURNdi64:
16260 case X86::TCRETURNri64:
16261 case X86::TCRETURNmi64:
16263 case X86::WIN_ALLOCA:
16264 return EmitLoweredWinAlloca(MI, BB);
16265 case X86::SEG_ALLOCA_32:
16266 return EmitLoweredSegAlloca(MI, BB, false);
16267 case X86::SEG_ALLOCA_64:
16268 return EmitLoweredSegAlloca(MI, BB, true);
16269 case X86::TLSCall_32:
16270 case X86::TLSCall_64:
16271 return EmitLoweredTLSCall(MI, BB);
16272 case X86::CMOV_GR8:
16273 case X86::CMOV_FR32:
16274 case X86::CMOV_FR64:
16275 case X86::CMOV_V4F32:
16276 case X86::CMOV_V2F64:
16277 case X86::CMOV_V2I64:
16278 case X86::CMOV_V8F32:
16279 case X86::CMOV_V4F64:
16280 case X86::CMOV_V4I64:
16281 case X86::CMOV_V16F32:
16282 case X86::CMOV_V8F64:
16283 case X86::CMOV_V8I64:
16284 case X86::CMOV_GR16:
16285 case X86::CMOV_GR32:
16286 case X86::CMOV_RFP32:
16287 case X86::CMOV_RFP64:
16288 case X86::CMOV_RFP80:
16289 return EmitLoweredSelect(MI, BB);
16291 case X86::FP32_TO_INT16_IN_MEM:
16292 case X86::FP32_TO_INT32_IN_MEM:
16293 case X86::FP32_TO_INT64_IN_MEM:
16294 case X86::FP64_TO_INT16_IN_MEM:
16295 case X86::FP64_TO_INT32_IN_MEM:
16296 case X86::FP64_TO_INT64_IN_MEM:
16297 case X86::FP80_TO_INT16_IN_MEM:
16298 case X86::FP80_TO_INT32_IN_MEM:
16299 case X86::FP80_TO_INT64_IN_MEM: {
16300 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16301 DebugLoc DL = MI->getDebugLoc();
16303 // Change the floating point control register to use "round towards zero"
16304 // mode when truncating to an integer value.
16305 MachineFunction *F = BB->getParent();
16306 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16307 addFrameReference(BuildMI(*BB, MI, DL,
16308 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16310 // Load the old value of the high byte of the control word...
16312 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16313 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16316 // Set the high part to be round to zero...
16317 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16320 // Reload the modified control word now...
16321 addFrameReference(BuildMI(*BB, MI, DL,
16322 TII->get(X86::FLDCW16m)), CWFrameIdx);
16324 // Restore the memory image of control word to original value
16325 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16328 // Get the X86 opcode to use.
16330 switch (MI->getOpcode()) {
16331 default: llvm_unreachable("illegal opcode!");
16332 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16333 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16334 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16335 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16336 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16337 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16338 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16339 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16340 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16344 MachineOperand &Op = MI->getOperand(0);
16346 AM.BaseType = X86AddressMode::RegBase;
16347 AM.Base.Reg = Op.getReg();
16349 AM.BaseType = X86AddressMode::FrameIndexBase;
16350 AM.Base.FrameIndex = Op.getIndex();
16352 Op = MI->getOperand(1);
16354 AM.Scale = Op.getImm();
16355 Op = MI->getOperand(2);
16357 AM.IndexReg = Op.getImm();
16358 Op = MI->getOperand(3);
16359 if (Op.isGlobal()) {
16360 AM.GV = Op.getGlobal();
16362 AM.Disp = Op.getImm();
16364 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16365 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16367 // Reload the original control word now.
16368 addFrameReference(BuildMI(*BB, MI, DL,
16369 TII->get(X86::FLDCW16m)), CWFrameIdx);
16371 MI->eraseFromParent(); // The pseudo instruction is gone now.
16374 // String/text processing lowering.
16375 case X86::PCMPISTRM128REG:
16376 case X86::VPCMPISTRM128REG:
16377 case X86::PCMPISTRM128MEM:
16378 case X86::VPCMPISTRM128MEM:
16379 case X86::PCMPESTRM128REG:
16380 case X86::VPCMPESTRM128REG:
16381 case X86::PCMPESTRM128MEM:
16382 case X86::VPCMPESTRM128MEM:
16383 assert(Subtarget->hasSSE42() &&
16384 "Target must have SSE4.2 or AVX features enabled");
16385 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16387 // String/text processing lowering.
16388 case X86::PCMPISTRIREG:
16389 case X86::VPCMPISTRIREG:
16390 case X86::PCMPISTRIMEM:
16391 case X86::VPCMPISTRIMEM:
16392 case X86::PCMPESTRIREG:
16393 case X86::VPCMPESTRIREG:
16394 case X86::PCMPESTRIMEM:
16395 case X86::VPCMPESTRIMEM:
16396 assert(Subtarget->hasSSE42() &&
16397 "Target must have SSE4.2 or AVX features enabled");
16398 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16400 // Thread synchronization.
16402 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16406 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16408 // Atomic Lowering.
16409 case X86::ATOMAND8:
16410 case X86::ATOMAND16:
16411 case X86::ATOMAND32:
16412 case X86::ATOMAND64:
16415 case X86::ATOMOR16:
16416 case X86::ATOMOR32:
16417 case X86::ATOMOR64:
16419 case X86::ATOMXOR16:
16420 case X86::ATOMXOR8:
16421 case X86::ATOMXOR32:
16422 case X86::ATOMXOR64:
16424 case X86::ATOMNAND8:
16425 case X86::ATOMNAND16:
16426 case X86::ATOMNAND32:
16427 case X86::ATOMNAND64:
16429 case X86::ATOMMAX8:
16430 case X86::ATOMMAX16:
16431 case X86::ATOMMAX32:
16432 case X86::ATOMMAX64:
16434 case X86::ATOMMIN8:
16435 case X86::ATOMMIN16:
16436 case X86::ATOMMIN32:
16437 case X86::ATOMMIN64:
16439 case X86::ATOMUMAX8:
16440 case X86::ATOMUMAX16:
16441 case X86::ATOMUMAX32:
16442 case X86::ATOMUMAX64:
16444 case X86::ATOMUMIN8:
16445 case X86::ATOMUMIN16:
16446 case X86::ATOMUMIN32:
16447 case X86::ATOMUMIN64:
16448 return EmitAtomicLoadArith(MI, BB);
16450 // This group does 64-bit operations on a 32-bit host.
16451 case X86::ATOMAND6432:
16452 case X86::ATOMOR6432:
16453 case X86::ATOMXOR6432:
16454 case X86::ATOMNAND6432:
16455 case X86::ATOMADD6432:
16456 case X86::ATOMSUB6432:
16457 case X86::ATOMMAX6432:
16458 case X86::ATOMMIN6432:
16459 case X86::ATOMUMAX6432:
16460 case X86::ATOMUMIN6432:
16461 case X86::ATOMSWAP6432:
16462 return EmitAtomicLoadArith6432(MI, BB);
16464 case X86::VASTART_SAVE_XMM_REGS:
16465 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16467 case X86::VAARG_64:
16468 return EmitVAARG64WithCustomInserter(MI, BB);
16470 case X86::EH_SjLj_SetJmp32:
16471 case X86::EH_SjLj_SetJmp64:
16472 return emitEHSjLjSetJmp(MI, BB);
16474 case X86::EH_SjLj_LongJmp32:
16475 case X86::EH_SjLj_LongJmp64:
16476 return emitEHSjLjLongJmp(MI, BB);
16478 case TargetOpcode::STACKMAP:
16479 case TargetOpcode::PATCHPOINT:
16480 return emitPatchPoint(MI, BB);
16482 case X86::VFMADDPDr213r:
16483 case X86::VFMADDPSr213r:
16484 case X86::VFMADDSDr213r:
16485 case X86::VFMADDSSr213r:
16486 case X86::VFMSUBPDr213r:
16487 case X86::VFMSUBPSr213r:
16488 case X86::VFMSUBSDr213r:
16489 case X86::VFMSUBSSr213r:
16490 case X86::VFNMADDPDr213r:
16491 case X86::VFNMADDPSr213r:
16492 case X86::VFNMADDSDr213r:
16493 case X86::VFNMADDSSr213r:
16494 case X86::VFNMSUBPDr213r:
16495 case X86::VFNMSUBPSr213r:
16496 case X86::VFNMSUBSDr213r:
16497 case X86::VFNMSUBSSr213r:
16498 case X86::VFMADDPDr213rY:
16499 case X86::VFMADDPSr213rY:
16500 case X86::VFMSUBPDr213rY:
16501 case X86::VFMSUBPSr213rY:
16502 case X86::VFNMADDPDr213rY:
16503 case X86::VFNMADDPSr213rY:
16504 case X86::VFNMSUBPDr213rY:
16505 case X86::VFNMSUBPSr213rY:
16506 return emitFMA3Instr(MI, BB);
16510 //===----------------------------------------------------------------------===//
16511 // X86 Optimization Hooks
16512 //===----------------------------------------------------------------------===//
16514 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16517 const SelectionDAG &DAG,
16518 unsigned Depth) const {
16519 unsigned BitWidth = KnownZero.getBitWidth();
16520 unsigned Opc = Op.getOpcode();
16521 assert((Opc >= ISD::BUILTIN_OP_END ||
16522 Opc == ISD::INTRINSIC_WO_CHAIN ||
16523 Opc == ISD::INTRINSIC_W_CHAIN ||
16524 Opc == ISD::INTRINSIC_VOID) &&
16525 "Should use MaskedValueIsZero if you don't know whether Op"
16526 " is a target node!");
16528 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16542 // These nodes' second result is a boolean.
16543 if (Op.getResNo() == 0)
16546 case X86ISD::SETCC:
16547 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16549 case ISD::INTRINSIC_WO_CHAIN: {
16550 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16551 unsigned NumLoBits = 0;
16554 case Intrinsic::x86_sse_movmsk_ps:
16555 case Intrinsic::x86_avx_movmsk_ps_256:
16556 case Intrinsic::x86_sse2_movmsk_pd:
16557 case Intrinsic::x86_avx_movmsk_pd_256:
16558 case Intrinsic::x86_mmx_pmovmskb:
16559 case Intrinsic::x86_sse2_pmovmskb_128:
16560 case Intrinsic::x86_avx2_pmovmskb: {
16561 // High bits of movmskp{s|d}, pmovmskb are known zero.
16563 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16564 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16565 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16566 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16567 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16568 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16569 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16570 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16572 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16581 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16583 const SelectionDAG &,
16584 unsigned Depth) const {
16585 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16586 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16587 return Op.getValueType().getScalarType().getSizeInBits();
16593 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16594 /// node is a GlobalAddress + offset.
16595 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16596 const GlobalValue* &GA,
16597 int64_t &Offset) const {
16598 if (N->getOpcode() == X86ISD::Wrapper) {
16599 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16600 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16601 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16605 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16608 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16609 /// same as extracting the high 128-bit part of 256-bit vector and then
16610 /// inserting the result into the low part of a new 256-bit vector
16611 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16612 EVT VT = SVOp->getValueType(0);
16613 unsigned NumElems = VT.getVectorNumElements();
16615 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16616 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16617 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16618 SVOp->getMaskElt(j) >= 0)
16624 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16625 /// same as extracting the low 128-bit part of 256-bit vector and then
16626 /// inserting the result into the high part of a new 256-bit vector
16627 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16628 EVT VT = SVOp->getValueType(0);
16629 unsigned NumElems = VT.getVectorNumElements();
16631 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16632 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16633 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16634 SVOp->getMaskElt(j) >= 0)
16640 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16641 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16642 TargetLowering::DAGCombinerInfo &DCI,
16643 const X86Subtarget* Subtarget) {
16645 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16646 SDValue V1 = SVOp->getOperand(0);
16647 SDValue V2 = SVOp->getOperand(1);
16648 EVT VT = SVOp->getValueType(0);
16649 unsigned NumElems = VT.getVectorNumElements();
16651 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16652 V2.getOpcode() == ISD::CONCAT_VECTORS) {
16656 // V UNDEF BUILD_VECTOR UNDEF
16658 // CONCAT_VECTOR CONCAT_VECTOR
16661 // RESULT: V + zero extended
16663 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16664 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16665 V1.getOperand(1).getOpcode() != ISD::UNDEF)
16668 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16671 // To match the shuffle mask, the first half of the mask should
16672 // be exactly the first vector, and all the rest a splat with the
16673 // first element of the second one.
16674 for (unsigned i = 0; i != NumElems/2; ++i)
16675 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16676 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16679 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16680 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16681 if (Ld->hasNUsesOfValue(1, 0)) {
16682 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16683 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16685 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16686 array_lengthof(Ops),
16688 Ld->getPointerInfo(),
16689 Ld->getAlignment(),
16690 false/*isVolatile*/, true/*ReadMem*/,
16691 false/*WriteMem*/);
16693 // Make sure the newly-created LOAD is in the same position as Ld in
16694 // terms of dependency. We create a TokenFactor for Ld and ResNode,
16695 // and update uses of Ld's output chain to use the TokenFactor.
16696 if (Ld->hasAnyUseOfValue(1)) {
16697 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16698 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16699 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16700 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16701 SDValue(ResNode.getNode(), 1));
16704 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16708 // Emit a zeroed vector and insert the desired subvector on its
16710 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16711 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16712 return DCI.CombineTo(N, InsV);
16715 //===--------------------------------------------------------------------===//
16716 // Combine some shuffles into subvector extracts and inserts:
16719 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16720 if (isShuffleHigh128VectorInsertLow(SVOp)) {
16721 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16722 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16723 return DCI.CombineTo(N, InsV);
16726 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16727 if (isShuffleLow128VectorInsertHigh(SVOp)) {
16728 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16729 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16730 return DCI.CombineTo(N, InsV);
16736 /// PerformShuffleCombine - Performs several different shuffle combines.
16737 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16738 TargetLowering::DAGCombinerInfo &DCI,
16739 const X86Subtarget *Subtarget) {
16741 EVT VT = N->getValueType(0);
16743 // Don't create instructions with illegal types after legalize types has run.
16744 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16745 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16748 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16749 if (Subtarget->hasFp256() && VT.is256BitVector() &&
16750 N->getOpcode() == ISD::VECTOR_SHUFFLE)
16751 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16753 // Only handle 128 wide vector from here on.
16754 if (!VT.is128BitVector())
16757 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16758 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16759 // consecutive, non-overlapping, and in the right order.
16760 SmallVector<SDValue, 16> Elts;
16761 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16762 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16764 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16767 /// PerformTruncateCombine - Converts truncate operation to
16768 /// a sequence of vector shuffle operations.
16769 /// It is possible when we truncate 256-bit vector to 128-bit vector
16770 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16771 TargetLowering::DAGCombinerInfo &DCI,
16772 const X86Subtarget *Subtarget) {
16776 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16777 /// specific shuffle of a load can be folded into a single element load.
16778 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16779 /// shuffles have been customed lowered so we need to handle those here.
16780 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16781 TargetLowering::DAGCombinerInfo &DCI) {
16782 if (DCI.isBeforeLegalizeOps())
16785 SDValue InVec = N->getOperand(0);
16786 SDValue EltNo = N->getOperand(1);
16788 if (!isa<ConstantSDNode>(EltNo))
16791 EVT VT = InVec.getValueType();
16793 bool HasShuffleIntoBitcast = false;
16794 if (InVec.getOpcode() == ISD::BITCAST) {
16795 // Don't duplicate a load with other uses.
16796 if (!InVec.hasOneUse())
16798 EVT BCVT = InVec.getOperand(0).getValueType();
16799 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16801 InVec = InVec.getOperand(0);
16802 HasShuffleIntoBitcast = true;
16805 if (!isTargetShuffle(InVec.getOpcode()))
16808 // Don't duplicate a load with other uses.
16809 if (!InVec.hasOneUse())
16812 SmallVector<int, 16> ShuffleMask;
16814 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16818 // Select the input vector, guarding against out of range extract vector.
16819 unsigned NumElems = VT.getVectorNumElements();
16820 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16821 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16822 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16823 : InVec.getOperand(1);
16825 // If inputs to shuffle are the same for both ops, then allow 2 uses
16826 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16828 if (LdNode.getOpcode() == ISD::BITCAST) {
16829 // Don't duplicate a load with other uses.
16830 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16833 AllowedUses = 1; // only allow 1 load use if we have a bitcast
16834 LdNode = LdNode.getOperand(0);
16837 if (!ISD::isNormalLoad(LdNode.getNode()))
16840 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16842 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16845 if (HasShuffleIntoBitcast) {
16846 // If there's a bitcast before the shuffle, check if the load type and
16847 // alignment is valid.
16848 unsigned Align = LN0->getAlignment();
16849 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16850 unsigned NewAlign = TLI.getDataLayout()->
16851 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16853 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16857 // All checks match so transform back to vector_shuffle so that DAG combiner
16858 // can finish the job
16861 // Create shuffle node taking into account the case that its a unary shuffle
16862 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16863 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16864 InVec.getOperand(0), Shuffle,
16866 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16867 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16871 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16872 /// generation and convert it from being a bunch of shuffles and extracts
16873 /// to a simple store and scalar loads to extract the elements.
16874 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16875 TargetLowering::DAGCombinerInfo &DCI) {
16876 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16877 if (NewOp.getNode())
16880 SDValue InputVector = N->getOperand(0);
16882 // Detect whether we are trying to convert from mmx to i32 and the bitcast
16883 // from mmx to v2i32 has a single usage.
16884 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16885 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16886 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16887 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16888 N->getValueType(0),
16889 InputVector.getNode()->getOperand(0));
16891 // Only operate on vectors of 4 elements, where the alternative shuffling
16892 // gets to be more expensive.
16893 if (InputVector.getValueType() != MVT::v4i32)
16896 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16897 // single use which is a sign-extend or zero-extend, and all elements are
16899 SmallVector<SDNode *, 4> Uses;
16900 unsigned ExtractedElements = 0;
16901 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16902 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16903 if (UI.getUse().getResNo() != InputVector.getResNo())
16906 SDNode *Extract = *UI;
16907 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16910 if (Extract->getValueType(0) != MVT::i32)
16912 if (!Extract->hasOneUse())
16914 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16915 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16917 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16920 // Record which element was extracted.
16921 ExtractedElements |=
16922 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16924 Uses.push_back(Extract);
16927 // If not all the elements were used, this may not be worthwhile.
16928 if (ExtractedElements != 15)
16931 // Ok, we've now decided to do the transformation.
16932 SDLoc dl(InputVector);
16934 // Store the value to a temporary stack slot.
16935 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16936 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16937 MachinePointerInfo(), false, false, 0);
16939 // Replace each use (extract) with a load of the appropriate element.
16940 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16941 UE = Uses.end(); UI != UE; ++UI) {
16942 SDNode *Extract = *UI;
16944 // cOMpute the element's address.
16945 SDValue Idx = Extract->getOperand(1);
16947 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16948 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16949 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16950 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16952 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16953 StackPtr, OffsetVal);
16955 // Load the scalar.
16956 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16957 ScalarAddr, MachinePointerInfo(),
16958 false, false, false, 0);
16960 // Replace the exact with the load.
16961 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16964 // The replacement was made in place; don't return anything.
16968 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16969 static std::pair<unsigned, bool>
16970 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16971 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16972 if (!VT.isVector())
16973 return std::make_pair(0, false);
16975 bool NeedSplit = false;
16976 switch (VT.getSimpleVT().SimpleTy) {
16977 default: return std::make_pair(0, false);
16981 if (!Subtarget->hasAVX2())
16983 if (!Subtarget->hasAVX())
16984 return std::make_pair(0, false);
16989 if (!Subtarget->hasSSE2())
16990 return std::make_pair(0, false);
16993 // SSE2 has only a small subset of the operations.
16994 bool hasUnsigned = Subtarget->hasSSE41() ||
16995 (Subtarget->hasSSE2() && VT == MVT::v16i8);
16996 bool hasSigned = Subtarget->hasSSE41() ||
16997 (Subtarget->hasSSE2() && VT == MVT::v8i16);
16999 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17002 // Check for x CC y ? x : y.
17003 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17004 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17009 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17012 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17015 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17018 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17020 // Check for x CC y ? y : x -- a min/max with reversed arms.
17021 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17022 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17027 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17030 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17033 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17036 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17040 return std::make_pair(Opc, NeedSplit);
17043 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17045 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17046 TargetLowering::DAGCombinerInfo &DCI,
17047 const X86Subtarget *Subtarget) {
17049 SDValue Cond = N->getOperand(0);
17050 // Get the LHS/RHS of the select.
17051 SDValue LHS = N->getOperand(1);
17052 SDValue RHS = N->getOperand(2);
17053 EVT VT = LHS.getValueType();
17054 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17056 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17057 // instructions match the semantics of the common C idiom x<y?x:y but not
17058 // x<=y?x:y, because of how they handle negative zero (which can be
17059 // ignored in unsafe-math mode).
17060 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17061 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17062 (Subtarget->hasSSE2() ||
17063 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17064 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17066 unsigned Opcode = 0;
17067 // Check for x CC y ? x : y.
17068 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17069 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17073 // Converting this to a min would handle NaNs incorrectly, and swapping
17074 // the operands would cause it to handle comparisons between positive
17075 // and negative zero incorrectly.
17076 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17077 if (!DAG.getTarget().Options.UnsafeFPMath &&
17078 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17080 std::swap(LHS, RHS);
17082 Opcode = X86ISD::FMIN;
17085 // Converting this to a min would handle comparisons between positive
17086 // and negative zero incorrectly.
17087 if (!DAG.getTarget().Options.UnsafeFPMath &&
17088 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17090 Opcode = X86ISD::FMIN;
17093 // Converting this to a min would handle both negative zeros and NaNs
17094 // incorrectly, but we can swap the operands to fix both.
17095 std::swap(LHS, RHS);
17099 Opcode = X86ISD::FMIN;
17103 // Converting this to a max would handle comparisons between positive
17104 // and negative zero incorrectly.
17105 if (!DAG.getTarget().Options.UnsafeFPMath &&
17106 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17108 Opcode = X86ISD::FMAX;
17111 // Converting this to a max would handle NaNs incorrectly, and swapping
17112 // the operands would cause it to handle comparisons between positive
17113 // and negative zero incorrectly.
17114 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17115 if (!DAG.getTarget().Options.UnsafeFPMath &&
17116 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17118 std::swap(LHS, RHS);
17120 Opcode = X86ISD::FMAX;
17123 // Converting this to a max would handle both negative zeros and NaNs
17124 // incorrectly, but we can swap the operands to fix both.
17125 std::swap(LHS, RHS);
17129 Opcode = X86ISD::FMAX;
17132 // Check for x CC y ? y : x -- a min/max with reversed arms.
17133 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17134 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17138 // Converting this to a min would handle comparisons between positive
17139 // and negative zero incorrectly, and swapping the operands would
17140 // cause it to handle NaNs incorrectly.
17141 if (!DAG.getTarget().Options.UnsafeFPMath &&
17142 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17143 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17145 std::swap(LHS, RHS);
17147 Opcode = X86ISD::FMIN;
17150 // Converting this to a min would handle NaNs incorrectly.
17151 if (!DAG.getTarget().Options.UnsafeFPMath &&
17152 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17154 Opcode = X86ISD::FMIN;
17157 // Converting this to a min would handle both negative zeros and NaNs
17158 // incorrectly, but we can swap the operands to fix both.
17159 std::swap(LHS, RHS);
17163 Opcode = X86ISD::FMIN;
17167 // Converting this to a max would handle NaNs incorrectly.
17168 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17170 Opcode = X86ISD::FMAX;
17173 // Converting this to a max would handle comparisons between positive
17174 // and negative zero incorrectly, and swapping the operands would
17175 // cause it to handle NaNs incorrectly.
17176 if (!DAG.getTarget().Options.UnsafeFPMath &&
17177 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17178 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17180 std::swap(LHS, RHS);
17182 Opcode = X86ISD::FMAX;
17185 // Converting this to a max would handle both negative zeros and NaNs
17186 // incorrectly, but we can swap the operands to fix both.
17187 std::swap(LHS, RHS);
17191 Opcode = X86ISD::FMAX;
17197 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17200 EVT CondVT = Cond.getValueType();
17201 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17202 CondVT.getVectorElementType() == MVT::i1) {
17203 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17204 // lowering on AVX-512. In this case we convert it to
17205 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17206 // The same situation for all 128 and 256-bit vectors of i8 and i16
17207 EVT OpVT = LHS.getValueType();
17208 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17209 (OpVT.getVectorElementType() == MVT::i8 ||
17210 OpVT.getVectorElementType() == MVT::i16)) {
17211 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17212 DCI.AddToWorklist(Cond.getNode());
17213 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17216 // If this is a select between two integer constants, try to do some
17218 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17219 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17220 // Don't do this for crazy integer types.
17221 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17222 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17223 // so that TrueC (the true value) is larger than FalseC.
17224 bool NeedsCondInvert = false;
17226 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17227 // Efficiently invertible.
17228 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17229 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17230 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17231 NeedsCondInvert = true;
17232 std::swap(TrueC, FalseC);
17235 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17236 if (FalseC->getAPIntValue() == 0 &&
17237 TrueC->getAPIntValue().isPowerOf2()) {
17238 if (NeedsCondInvert) // Invert the condition if needed.
17239 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17240 DAG.getConstant(1, Cond.getValueType()));
17242 // Zero extend the condition if needed.
17243 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17245 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17246 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17247 DAG.getConstant(ShAmt, MVT::i8));
17250 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17251 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17252 if (NeedsCondInvert) // Invert the condition if needed.
17253 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17254 DAG.getConstant(1, Cond.getValueType()));
17256 // Zero extend the condition if needed.
17257 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17258 FalseC->getValueType(0), Cond);
17259 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17260 SDValue(FalseC, 0));
17263 // Optimize cases that will turn into an LEA instruction. This requires
17264 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17265 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17266 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17267 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17269 bool isFastMultiplier = false;
17271 switch ((unsigned char)Diff) {
17273 case 1: // result = add base, cond
17274 case 2: // result = lea base( , cond*2)
17275 case 3: // result = lea base(cond, cond*2)
17276 case 4: // result = lea base( , cond*4)
17277 case 5: // result = lea base(cond, cond*4)
17278 case 8: // result = lea base( , cond*8)
17279 case 9: // result = lea base(cond, cond*8)
17280 isFastMultiplier = true;
17285 if (isFastMultiplier) {
17286 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17287 if (NeedsCondInvert) // Invert the condition if needed.
17288 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17289 DAG.getConstant(1, Cond.getValueType()));
17291 // Zero extend the condition if needed.
17292 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17294 // Scale the condition by the difference.
17296 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17297 DAG.getConstant(Diff, Cond.getValueType()));
17299 // Add the base if non-zero.
17300 if (FalseC->getAPIntValue() != 0)
17301 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17302 SDValue(FalseC, 0));
17309 // Canonicalize max and min:
17310 // (x > y) ? x : y -> (x >= y) ? x : y
17311 // (x < y) ? x : y -> (x <= y) ? x : y
17312 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17313 // the need for an extra compare
17314 // against zero. e.g.
17315 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17317 // testl %edi, %edi
17319 // cmovgl %edi, %eax
17323 // cmovsl %eax, %edi
17324 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17325 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17326 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17327 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17332 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17333 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17334 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17335 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17340 // Early exit check
17341 if (!TLI.isTypeLegal(VT))
17344 // Match VSELECTs into subs with unsigned saturation.
17345 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17346 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17347 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17348 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17349 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17351 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17352 // left side invert the predicate to simplify logic below.
17354 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17356 CC = ISD::getSetCCInverse(CC, true);
17357 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17361 if (Other.getNode() && Other->getNumOperands() == 2 &&
17362 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17363 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17364 SDValue CondRHS = Cond->getOperand(1);
17366 // Look for a general sub with unsigned saturation first.
17367 // x >= y ? x-y : 0 --> subus x, y
17368 // x > y ? x-y : 0 --> subus x, y
17369 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17370 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17371 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17373 // If the RHS is a constant we have to reverse the const canonicalization.
17374 // x > C-1 ? x+-C : 0 --> subus x, C
17375 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17376 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17377 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17378 if (CondRHS.getConstantOperandVal(0) == -A-1)
17379 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17380 DAG.getConstant(-A, VT));
17383 // Another special case: If C was a sign bit, the sub has been
17384 // canonicalized into a xor.
17385 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17386 // it's safe to decanonicalize the xor?
17387 // x s< 0 ? x^C : 0 --> subus x, C
17388 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17389 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17390 isSplatVector(OpRHS.getNode())) {
17391 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17393 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17398 // Try to match a min/max vector operation.
17399 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17400 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17401 unsigned Opc = ret.first;
17402 bool NeedSplit = ret.second;
17404 if (Opc && NeedSplit) {
17405 unsigned NumElems = VT.getVectorNumElements();
17406 // Extract the LHS vectors
17407 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17408 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17410 // Extract the RHS vectors
17411 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17412 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17414 // Create min/max for each subvector
17415 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17416 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17418 // Merge the result
17419 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17421 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17424 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17425 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17426 // Check if SETCC has already been promoted
17427 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17428 // Check that condition value type matches vselect operand type
17431 assert(Cond.getValueType().isVector() &&
17432 "vector select expects a vector selector!");
17434 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17435 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17437 if (!TValIsAllOnes && !FValIsAllZeros) {
17438 // Try invert the condition if true value is not all 1s and false value
17440 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17441 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17443 if (TValIsAllZeros || FValIsAllOnes) {
17444 SDValue CC = Cond.getOperand(2);
17445 ISD::CondCode NewCC =
17446 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17447 Cond.getOperand(0).getValueType().isInteger());
17448 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17449 std::swap(LHS, RHS);
17450 TValIsAllOnes = FValIsAllOnes;
17451 FValIsAllZeros = TValIsAllZeros;
17455 if (TValIsAllOnes || FValIsAllZeros) {
17458 if (TValIsAllOnes && FValIsAllZeros)
17460 else if (TValIsAllOnes)
17461 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17462 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17463 else if (FValIsAllZeros)
17464 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17465 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17467 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17471 // Try to fold this VSELECT into a MOVSS/MOVSD
17472 if (N->getOpcode() == ISD::VSELECT &&
17473 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17474 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17475 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17476 bool CanFold = false;
17477 unsigned NumElems = Cond.getNumOperands();
17481 if (isZero(Cond.getOperand(0))) {
17484 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17485 // fold (vselect <0,-1> -> (movsd A, B)
17486 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17487 CanFold = isAllOnes(Cond.getOperand(i));
17488 } else if (isAllOnes(Cond.getOperand(0))) {
17492 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17493 // fold (vselect <-1,0> -> (movsd B, A)
17494 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17495 CanFold = isZero(Cond.getOperand(i));
17499 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17500 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17501 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17504 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17505 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17506 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17507 // (v2i64 (bitcast B)))))
17509 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17510 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17511 // (v2f64 (bitcast B)))))
17513 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17514 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17515 // (v2i64 (bitcast A)))))
17517 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17518 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17519 // (v2f64 (bitcast A)))))
17521 CanFold = (isZero(Cond.getOperand(0)) &&
17522 isZero(Cond.getOperand(1)) &&
17523 isAllOnes(Cond.getOperand(2)) &&
17524 isAllOnes(Cond.getOperand(3)));
17526 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17527 isAllOnes(Cond.getOperand(1)) &&
17528 isZero(Cond.getOperand(2)) &&
17529 isZero(Cond.getOperand(3))) {
17531 std::swap(LHS, RHS);
17535 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17536 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17537 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17538 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17540 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17546 // If we know that this node is legal then we know that it is going to be
17547 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17548 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17549 // to simplify previous instructions.
17550 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17551 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17552 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17554 // Don't optimize vector selects that map to mask-registers.
17558 // Check all uses of that condition operand to check whether it will be
17559 // consumed by non-BLEND instructions, which may depend on all bits are set
17561 for (SDNode::use_iterator I = Cond->use_begin(),
17562 E = Cond->use_end(); I != E; ++I)
17563 if (I->getOpcode() != ISD::VSELECT)
17564 // TODO: Add other opcodes eventually lowered into BLEND.
17567 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17568 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17570 APInt KnownZero, KnownOne;
17571 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17572 DCI.isBeforeLegalizeOps());
17573 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17574 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17575 DCI.CommitTargetLoweringOpt(TLO);
17581 // Check whether a boolean test is testing a boolean value generated by
17582 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17585 // Simplify the following patterns:
17586 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17587 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17588 // to (Op EFLAGS Cond)
17590 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17591 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17592 // to (Op EFLAGS !Cond)
17594 // where Op could be BRCOND or CMOV.
17596 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17597 // Quit if not CMP and SUB with its value result used.
17598 if (Cmp.getOpcode() != X86ISD::CMP &&
17599 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17602 // Quit if not used as a boolean value.
17603 if (CC != X86::COND_E && CC != X86::COND_NE)
17606 // Check CMP operands. One of them should be 0 or 1 and the other should be
17607 // an SetCC or extended from it.
17608 SDValue Op1 = Cmp.getOperand(0);
17609 SDValue Op2 = Cmp.getOperand(1);
17612 const ConstantSDNode* C = 0;
17613 bool needOppositeCond = (CC == X86::COND_E);
17614 bool checkAgainstTrue = false; // Is it a comparison against 1?
17616 if ((C = dyn_cast<ConstantSDNode>(Op1)))
17618 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17620 else // Quit if all operands are not constants.
17623 if (C->getZExtValue() == 1) {
17624 needOppositeCond = !needOppositeCond;
17625 checkAgainstTrue = true;
17626 } else if (C->getZExtValue() != 0)
17627 // Quit if the constant is neither 0 or 1.
17630 bool truncatedToBoolWithAnd = false;
17631 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17632 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17633 SetCC.getOpcode() == ISD::TRUNCATE ||
17634 SetCC.getOpcode() == ISD::AND) {
17635 if (SetCC.getOpcode() == ISD::AND) {
17637 ConstantSDNode *CS;
17638 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17639 CS->getZExtValue() == 1)
17641 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17642 CS->getZExtValue() == 1)
17646 SetCC = SetCC.getOperand(OpIdx);
17647 truncatedToBoolWithAnd = true;
17649 SetCC = SetCC.getOperand(0);
17652 switch (SetCC.getOpcode()) {
17653 case X86ISD::SETCC_CARRY:
17654 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17655 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17656 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17657 // truncated to i1 using 'and'.
17658 if (checkAgainstTrue && !truncatedToBoolWithAnd)
17660 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17661 "Invalid use of SETCC_CARRY!");
17663 case X86ISD::SETCC:
17664 // Set the condition code or opposite one if necessary.
17665 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17666 if (needOppositeCond)
17667 CC = X86::GetOppositeBranchCondition(CC);
17668 return SetCC.getOperand(1);
17669 case X86ISD::CMOV: {
17670 // Check whether false/true value has canonical one, i.e. 0 or 1.
17671 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17672 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17673 // Quit if true value is not a constant.
17676 // Quit if false value is not a constant.
17678 SDValue Op = SetCC.getOperand(0);
17679 // Skip 'zext' or 'trunc' node.
17680 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17681 Op.getOpcode() == ISD::TRUNCATE)
17682 Op = Op.getOperand(0);
17683 // A special case for rdrand/rdseed, where 0 is set if false cond is
17685 if ((Op.getOpcode() != X86ISD::RDRAND &&
17686 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17689 // Quit if false value is not the constant 0 or 1.
17690 bool FValIsFalse = true;
17691 if (FVal && FVal->getZExtValue() != 0) {
17692 if (FVal->getZExtValue() != 1)
17694 // If FVal is 1, opposite cond is needed.
17695 needOppositeCond = !needOppositeCond;
17696 FValIsFalse = false;
17698 // Quit if TVal is not the constant opposite of FVal.
17699 if (FValIsFalse && TVal->getZExtValue() != 1)
17701 if (!FValIsFalse && TVal->getZExtValue() != 0)
17703 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17704 if (needOppositeCond)
17705 CC = X86::GetOppositeBranchCondition(CC);
17706 return SetCC.getOperand(3);
17713 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17714 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17715 TargetLowering::DAGCombinerInfo &DCI,
17716 const X86Subtarget *Subtarget) {
17719 // If the flag operand isn't dead, don't touch this CMOV.
17720 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17723 SDValue FalseOp = N->getOperand(0);
17724 SDValue TrueOp = N->getOperand(1);
17725 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17726 SDValue Cond = N->getOperand(3);
17728 if (CC == X86::COND_E || CC == X86::COND_NE) {
17729 switch (Cond.getOpcode()) {
17733 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17734 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17735 return (CC == X86::COND_E) ? FalseOp : TrueOp;
17741 Flags = checkBoolTestSetCCCombine(Cond, CC);
17742 if (Flags.getNode() &&
17743 // Extra check as FCMOV only supports a subset of X86 cond.
17744 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17745 SDValue Ops[] = { FalseOp, TrueOp,
17746 DAG.getConstant(CC, MVT::i8), Flags };
17747 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17748 Ops, array_lengthof(Ops));
17751 // If this is a select between two integer constants, try to do some
17752 // optimizations. Note that the operands are ordered the opposite of SELECT
17754 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17755 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17756 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17757 // larger than FalseC (the false value).
17758 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17759 CC = X86::GetOppositeBranchCondition(CC);
17760 std::swap(TrueC, FalseC);
17761 std::swap(TrueOp, FalseOp);
17764 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
17765 // This is efficient for any integer data type (including i8/i16) and
17767 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17768 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17769 DAG.getConstant(CC, MVT::i8), Cond);
17771 // Zero extend the condition if needed.
17772 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17774 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17775 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17776 DAG.getConstant(ShAmt, MVT::i8));
17777 if (N->getNumValues() == 2) // Dead flag value?
17778 return DCI.CombineTo(N, Cond, SDValue());
17782 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
17783 // for any integer data type, including i8/i16.
17784 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17785 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17786 DAG.getConstant(CC, MVT::i8), Cond);
17788 // Zero extend the condition if needed.
17789 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17790 FalseC->getValueType(0), Cond);
17791 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17792 SDValue(FalseC, 0));
17794 if (N->getNumValues() == 2) // Dead flag value?
17795 return DCI.CombineTo(N, Cond, SDValue());
17799 // Optimize cases that will turn into an LEA instruction. This requires
17800 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17801 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17802 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17803 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17805 bool isFastMultiplier = false;
17807 switch ((unsigned char)Diff) {
17809 case 1: // result = add base, cond
17810 case 2: // result = lea base( , cond*2)
17811 case 3: // result = lea base(cond, cond*2)
17812 case 4: // result = lea base( , cond*4)
17813 case 5: // result = lea base(cond, cond*4)
17814 case 8: // result = lea base( , cond*8)
17815 case 9: // result = lea base(cond, cond*8)
17816 isFastMultiplier = true;
17821 if (isFastMultiplier) {
17822 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17823 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17824 DAG.getConstant(CC, MVT::i8), Cond);
17825 // Zero extend the condition if needed.
17826 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17828 // Scale the condition by the difference.
17830 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17831 DAG.getConstant(Diff, Cond.getValueType()));
17833 // Add the base if non-zero.
17834 if (FalseC->getAPIntValue() != 0)
17835 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17836 SDValue(FalseC, 0));
17837 if (N->getNumValues() == 2) // Dead flag value?
17838 return DCI.CombineTo(N, Cond, SDValue());
17845 // Handle these cases:
17846 // (select (x != c), e, c) -> select (x != c), e, x),
17847 // (select (x == c), c, e) -> select (x == c), x, e)
17848 // where the c is an integer constant, and the "select" is the combination
17849 // of CMOV and CMP.
17851 // The rationale for this change is that the conditional-move from a constant
17852 // needs two instructions, however, conditional-move from a register needs
17853 // only one instruction.
17855 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17856 // some instruction-combining opportunities. This opt needs to be
17857 // postponed as late as possible.
17859 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17860 // the DCI.xxxx conditions are provided to postpone the optimization as
17861 // late as possible.
17863 ConstantSDNode *CmpAgainst = 0;
17864 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17865 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17866 !isa<ConstantSDNode>(Cond.getOperand(0))) {
17868 if (CC == X86::COND_NE &&
17869 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17870 CC = X86::GetOppositeBranchCondition(CC);
17871 std::swap(TrueOp, FalseOp);
17874 if (CC == X86::COND_E &&
17875 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17876 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17877 DAG.getConstant(CC, MVT::i8), Cond };
17878 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17879 array_lengthof(Ops));
17887 /// PerformMulCombine - Optimize a single multiply with constant into two
17888 /// in order to implement it with two cheaper instructions, e.g.
17889 /// LEA + SHL, LEA + LEA.
17890 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17891 TargetLowering::DAGCombinerInfo &DCI) {
17892 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17895 EVT VT = N->getValueType(0);
17896 if (VT != MVT::i64)
17899 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17902 uint64_t MulAmt = C->getZExtValue();
17903 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17906 uint64_t MulAmt1 = 0;
17907 uint64_t MulAmt2 = 0;
17908 if ((MulAmt % 9) == 0) {
17910 MulAmt2 = MulAmt / 9;
17911 } else if ((MulAmt % 5) == 0) {
17913 MulAmt2 = MulAmt / 5;
17914 } else if ((MulAmt % 3) == 0) {
17916 MulAmt2 = MulAmt / 3;
17919 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17922 if (isPowerOf2_64(MulAmt2) &&
17923 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17924 // If second multiplifer is pow2, issue it first. We want the multiply by
17925 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17927 std::swap(MulAmt1, MulAmt2);
17930 if (isPowerOf2_64(MulAmt1))
17931 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17932 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17934 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17935 DAG.getConstant(MulAmt1, VT));
17937 if (isPowerOf2_64(MulAmt2))
17938 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17939 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17941 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17942 DAG.getConstant(MulAmt2, VT));
17944 // Do not add new nodes to DAG combiner worklist.
17945 DCI.CombineTo(N, NewMul, false);
17950 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17951 SDValue N0 = N->getOperand(0);
17952 SDValue N1 = N->getOperand(1);
17953 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17954 EVT VT = N0.getValueType();
17956 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17957 // since the result of setcc_c is all zero's or all ones.
17958 if (VT.isInteger() && !VT.isVector() &&
17959 N1C && N0.getOpcode() == ISD::AND &&
17960 N0.getOperand(1).getOpcode() == ISD::Constant) {
17961 SDValue N00 = N0.getOperand(0);
17962 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17963 ((N00.getOpcode() == ISD::ANY_EXTEND ||
17964 N00.getOpcode() == ISD::ZERO_EXTEND) &&
17965 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17966 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17967 APInt ShAmt = N1C->getAPIntValue();
17968 Mask = Mask.shl(ShAmt);
17970 return DAG.getNode(ISD::AND, SDLoc(N), VT,
17971 N00, DAG.getConstant(Mask, VT));
17975 // Hardware support for vector shifts is sparse which makes us scalarize the
17976 // vector operations in many cases. Also, on sandybridge ADD is faster than
17978 // (shl V, 1) -> add V,V
17979 if (isSplatVector(N1.getNode())) {
17980 assert(N0.getValueType().isVector() && "Invalid vector shift type");
17981 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17982 // We shift all of the values by one. In many cases we do not have
17983 // hardware support for this operation. This is better expressed as an ADD
17985 if (N1C && (1 == N1C->getZExtValue())) {
17986 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17993 /// \brief Returns a vector of 0s if the node in input is a vector logical
17994 /// shift by a constant amount which is known to be bigger than or equal
17995 /// to the vector element size in bits.
17996 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17997 const X86Subtarget *Subtarget) {
17998 EVT VT = N->getValueType(0);
18000 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18001 (!Subtarget->hasInt256() ||
18002 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18005 SDValue Amt = N->getOperand(1);
18007 if (isSplatVector(Amt.getNode())) {
18008 SDValue SclrAmt = Amt->getOperand(0);
18009 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18010 APInt ShiftAmt = C->getAPIntValue();
18011 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18013 // SSE2/AVX2 logical shifts always return a vector of 0s
18014 // if the shift amount is bigger than or equal to
18015 // the element size. The constant shift amount will be
18016 // encoded as a 8-bit immediate.
18017 if (ShiftAmt.trunc(8).uge(MaxAmount))
18018 return getZeroVector(VT, Subtarget, DAG, DL);
18025 /// PerformShiftCombine - Combine shifts.
18026 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18027 TargetLowering::DAGCombinerInfo &DCI,
18028 const X86Subtarget *Subtarget) {
18029 if (N->getOpcode() == ISD::SHL) {
18030 SDValue V = PerformSHLCombine(N, DAG);
18031 if (V.getNode()) return V;
18034 if (N->getOpcode() != ISD::SRA) {
18035 // Try to fold this logical shift into a zero vector.
18036 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18037 if (V.getNode()) return V;
18043 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18044 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18045 // and friends. Likewise for OR -> CMPNEQSS.
18046 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18047 TargetLowering::DAGCombinerInfo &DCI,
18048 const X86Subtarget *Subtarget) {
18051 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18052 // we're requiring SSE2 for both.
18053 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18054 SDValue N0 = N->getOperand(0);
18055 SDValue N1 = N->getOperand(1);
18056 SDValue CMP0 = N0->getOperand(1);
18057 SDValue CMP1 = N1->getOperand(1);
18060 // The SETCCs should both refer to the same CMP.
18061 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18064 SDValue CMP00 = CMP0->getOperand(0);
18065 SDValue CMP01 = CMP0->getOperand(1);
18066 EVT VT = CMP00.getValueType();
18068 if (VT == MVT::f32 || VT == MVT::f64) {
18069 bool ExpectingFlags = false;
18070 // Check for any users that want flags:
18071 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18072 !ExpectingFlags && UI != UE; ++UI)
18073 switch (UI->getOpcode()) {
18078 ExpectingFlags = true;
18080 case ISD::CopyToReg:
18081 case ISD::SIGN_EXTEND:
18082 case ISD::ZERO_EXTEND:
18083 case ISD::ANY_EXTEND:
18087 if (!ExpectingFlags) {
18088 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18089 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18091 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18092 X86::CondCode tmp = cc0;
18097 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18098 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18099 // FIXME: need symbolic constants for these magic numbers.
18100 // See X86ATTInstPrinter.cpp:printSSECC().
18101 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18102 if (Subtarget->hasAVX512()) {
18103 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18104 CMP01, DAG.getConstant(x86cc, MVT::i8));
18105 if (N->getValueType(0) != MVT::i1)
18106 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18110 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18111 CMP00.getValueType(), CMP00, CMP01,
18112 DAG.getConstant(x86cc, MVT::i8));
18114 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18115 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18117 if (is64BitFP && !Subtarget->is64Bit()) {
18118 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18119 // 64-bit integer, since that's not a legal type. Since
18120 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18121 // bits, but can do this little dance to extract the lowest 32 bits
18122 // and work with those going forward.
18123 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18125 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18127 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18128 Vector32, DAG.getIntPtrConstant(0));
18132 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18133 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18134 DAG.getConstant(1, IntVT));
18135 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18136 return OneBitOfTruth;
18144 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18145 /// so it can be folded inside ANDNP.
18146 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18147 EVT VT = N->getValueType(0);
18149 // Match direct AllOnes for 128 and 256-bit vectors
18150 if (ISD::isBuildVectorAllOnes(N))
18153 // Look through a bit convert.
18154 if (N->getOpcode() == ISD::BITCAST)
18155 N = N->getOperand(0).getNode();
18157 // Sometimes the operand may come from a insert_subvector building a 256-bit
18159 if (VT.is256BitVector() &&
18160 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18161 SDValue V1 = N->getOperand(0);
18162 SDValue V2 = N->getOperand(1);
18164 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18165 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18166 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18167 ISD::isBuildVectorAllOnes(V2.getNode()))
18174 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18175 // register. In most cases we actually compare or select YMM-sized registers
18176 // and mixing the two types creates horrible code. This method optimizes
18177 // some of the transition sequences.
18178 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18179 TargetLowering::DAGCombinerInfo &DCI,
18180 const X86Subtarget *Subtarget) {
18181 EVT VT = N->getValueType(0);
18182 if (!VT.is256BitVector())
18185 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18186 N->getOpcode() == ISD::ZERO_EXTEND ||
18187 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18189 SDValue Narrow = N->getOperand(0);
18190 EVT NarrowVT = Narrow->getValueType(0);
18191 if (!NarrowVT.is128BitVector())
18194 if (Narrow->getOpcode() != ISD::XOR &&
18195 Narrow->getOpcode() != ISD::AND &&
18196 Narrow->getOpcode() != ISD::OR)
18199 SDValue N0 = Narrow->getOperand(0);
18200 SDValue N1 = Narrow->getOperand(1);
18203 // The Left side has to be a trunc.
18204 if (N0.getOpcode() != ISD::TRUNCATE)
18207 // The type of the truncated inputs.
18208 EVT WideVT = N0->getOperand(0)->getValueType(0);
18212 // The right side has to be a 'trunc' or a constant vector.
18213 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18214 bool RHSConst = (isSplatVector(N1.getNode()) &&
18215 isa<ConstantSDNode>(N1->getOperand(0)));
18216 if (!RHSTrunc && !RHSConst)
18219 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18221 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18224 // Set N0 and N1 to hold the inputs to the new wide operation.
18225 N0 = N0->getOperand(0);
18227 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18228 N1->getOperand(0));
18229 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18230 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18231 } else if (RHSTrunc) {
18232 N1 = N1->getOperand(0);
18235 // Generate the wide operation.
18236 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18237 unsigned Opcode = N->getOpcode();
18239 case ISD::ANY_EXTEND:
18241 case ISD::ZERO_EXTEND: {
18242 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18243 APInt Mask = APInt::getAllOnesValue(InBits);
18244 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18245 return DAG.getNode(ISD::AND, DL, VT,
18246 Op, DAG.getConstant(Mask, VT));
18248 case ISD::SIGN_EXTEND:
18249 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18250 Op, DAG.getValueType(NarrowVT));
18252 llvm_unreachable("Unexpected opcode");
18256 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18257 TargetLowering::DAGCombinerInfo &DCI,
18258 const X86Subtarget *Subtarget) {
18259 EVT VT = N->getValueType(0);
18260 if (DCI.isBeforeLegalizeOps())
18263 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18267 // Create BEXTR and BZHI instructions
18268 // BZHI is X & ((1 << Y) - 1)
18269 // BEXTR is ((X >> imm) & (2**size-1))
18270 if (VT == MVT::i32 || VT == MVT::i64) {
18271 SDValue N0 = N->getOperand(0);
18272 SDValue N1 = N->getOperand(1);
18275 if (Subtarget->hasBMI2()) {
18276 // Check for (and (add (shl 1, Y), -1), X)
18277 if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
18278 SDValue N00 = N0.getOperand(0);
18279 if (N00.getOpcode() == ISD::SHL) {
18280 SDValue N001 = N00.getOperand(1);
18281 assert(N001.getValueType() == MVT::i8 && "unexpected type");
18282 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
18283 if (C && C->getZExtValue() == 1)
18284 return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
18288 // Check for (and X, (add (shl 1, Y), -1))
18289 if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
18290 SDValue N10 = N1.getOperand(0);
18291 if (N10.getOpcode() == ISD::SHL) {
18292 SDValue N101 = N10.getOperand(1);
18293 assert(N101.getValueType() == MVT::i8 && "unexpected type");
18294 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
18295 if (C && C->getZExtValue() == 1)
18296 return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
18301 // Check for BEXTR.
18302 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18303 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18304 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18305 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18306 if (MaskNode && ShiftNode) {
18307 uint64_t Mask = MaskNode->getZExtValue();
18308 uint64_t Shift = ShiftNode->getZExtValue();
18309 if (isMask_64(Mask)) {
18310 uint64_t MaskSize = CountPopulation_64(Mask);
18311 if (Shift + MaskSize <= VT.getSizeInBits())
18312 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18313 DAG.getConstant(Shift | (MaskSize << 8), VT));
18321 // Want to form ANDNP nodes:
18322 // 1) In the hopes of then easily combining them with OR and AND nodes
18323 // to form PBLEND/PSIGN.
18324 // 2) To match ANDN packed intrinsics
18325 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18328 SDValue N0 = N->getOperand(0);
18329 SDValue N1 = N->getOperand(1);
18332 // Check LHS for vnot
18333 if (N0.getOpcode() == ISD::XOR &&
18334 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18335 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18336 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18338 // Check RHS for vnot
18339 if (N1.getOpcode() == ISD::XOR &&
18340 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18341 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18342 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18347 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18348 TargetLowering::DAGCombinerInfo &DCI,
18349 const X86Subtarget *Subtarget) {
18350 if (DCI.isBeforeLegalizeOps())
18353 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18357 SDValue N0 = N->getOperand(0);
18358 SDValue N1 = N->getOperand(1);
18359 EVT VT = N->getValueType(0);
18361 // look for psign/blend
18362 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18363 if (!Subtarget->hasSSSE3() ||
18364 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18367 // Canonicalize pandn to RHS
18368 if (N0.getOpcode() == X86ISD::ANDNP)
18370 // or (and (m, y), (pandn m, x))
18371 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18372 SDValue Mask = N1.getOperand(0);
18373 SDValue X = N1.getOperand(1);
18375 if (N0.getOperand(0) == Mask)
18376 Y = N0.getOperand(1);
18377 if (N0.getOperand(1) == Mask)
18378 Y = N0.getOperand(0);
18380 // Check to see if the mask appeared in both the AND and ANDNP and
18384 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18385 // Look through mask bitcast.
18386 if (Mask.getOpcode() == ISD::BITCAST)
18387 Mask = Mask.getOperand(0);
18388 if (X.getOpcode() == ISD::BITCAST)
18389 X = X.getOperand(0);
18390 if (Y.getOpcode() == ISD::BITCAST)
18391 Y = Y.getOperand(0);
18393 EVT MaskVT = Mask.getValueType();
18395 // Validate that the Mask operand is a vector sra node.
18396 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18397 // there is no psrai.b
18398 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18399 unsigned SraAmt = ~0;
18400 if (Mask.getOpcode() == ISD::SRA) {
18401 SDValue Amt = Mask.getOperand(1);
18402 if (isSplatVector(Amt.getNode())) {
18403 SDValue SclrAmt = Amt->getOperand(0);
18404 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18405 SraAmt = C->getZExtValue();
18407 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18408 SDValue SraC = Mask.getOperand(1);
18409 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18411 if ((SraAmt + 1) != EltBits)
18416 // Now we know we at least have a plendvb with the mask val. See if
18417 // we can form a psignb/w/d.
18418 // psign = x.type == y.type == mask.type && y = sub(0, x);
18419 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18420 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18421 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18422 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18423 "Unsupported VT for PSIGN");
18424 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18425 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18427 // PBLENDVB only available on SSE 4.1
18428 if (!Subtarget->hasSSE41())
18431 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18433 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18434 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18435 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18436 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18437 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18441 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18444 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18445 MachineFunction &MF = DAG.getMachineFunction();
18446 bool OptForSize = MF.getFunction()->getAttributes().
18447 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18449 // SHLD/SHRD instructions have lower register pressure, but on some
18450 // platforms they have higher latency than the equivalent
18451 // series of shifts/or that would otherwise be generated.
18452 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18453 // have higher latencies and we are not optimizing for size.
18454 if (!OptForSize && Subtarget->isSHLDSlow())
18457 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18459 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18461 if (!N0.hasOneUse() || !N1.hasOneUse())
18464 SDValue ShAmt0 = N0.getOperand(1);
18465 if (ShAmt0.getValueType() != MVT::i8)
18467 SDValue ShAmt1 = N1.getOperand(1);
18468 if (ShAmt1.getValueType() != MVT::i8)
18470 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18471 ShAmt0 = ShAmt0.getOperand(0);
18472 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18473 ShAmt1 = ShAmt1.getOperand(0);
18476 unsigned Opc = X86ISD::SHLD;
18477 SDValue Op0 = N0.getOperand(0);
18478 SDValue Op1 = N1.getOperand(0);
18479 if (ShAmt0.getOpcode() == ISD::SUB) {
18480 Opc = X86ISD::SHRD;
18481 std::swap(Op0, Op1);
18482 std::swap(ShAmt0, ShAmt1);
18485 unsigned Bits = VT.getSizeInBits();
18486 if (ShAmt1.getOpcode() == ISD::SUB) {
18487 SDValue Sum = ShAmt1.getOperand(0);
18488 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18489 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18490 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18491 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18492 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18493 return DAG.getNode(Opc, DL, VT,
18495 DAG.getNode(ISD::TRUNCATE, DL,
18498 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18499 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18501 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18502 return DAG.getNode(Opc, DL, VT,
18503 N0.getOperand(0), N1.getOperand(0),
18504 DAG.getNode(ISD::TRUNCATE, DL,
18511 // Generate NEG and CMOV for integer abs.
18512 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18513 EVT VT = N->getValueType(0);
18515 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18516 // 8-bit integer abs to NEG and CMOV.
18517 if (VT.isInteger() && VT.getSizeInBits() == 8)
18520 SDValue N0 = N->getOperand(0);
18521 SDValue N1 = N->getOperand(1);
18524 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18525 // and change it to SUB and CMOV.
18526 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18527 N0.getOpcode() == ISD::ADD &&
18528 N0.getOperand(1) == N1 &&
18529 N1.getOpcode() == ISD::SRA &&
18530 N1.getOperand(0) == N0.getOperand(0))
18531 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18532 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18533 // Generate SUB & CMOV.
18534 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18535 DAG.getConstant(0, VT), N0.getOperand(0));
18537 SDValue Ops[] = { N0.getOperand(0), Neg,
18538 DAG.getConstant(X86::COND_GE, MVT::i8),
18539 SDValue(Neg.getNode(), 1) };
18540 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18541 Ops, array_lengthof(Ops));
18546 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18547 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18548 TargetLowering::DAGCombinerInfo &DCI,
18549 const X86Subtarget *Subtarget) {
18550 if (DCI.isBeforeLegalizeOps())
18553 if (Subtarget->hasCMov()) {
18554 SDValue RV = performIntegerAbsCombine(N, DAG);
18562 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18563 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18564 TargetLowering::DAGCombinerInfo &DCI,
18565 const X86Subtarget *Subtarget) {
18566 LoadSDNode *Ld = cast<LoadSDNode>(N);
18567 EVT RegVT = Ld->getValueType(0);
18568 EVT MemVT = Ld->getMemoryVT();
18570 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18571 unsigned RegSz = RegVT.getSizeInBits();
18573 // On Sandybridge unaligned 256bit loads are inefficient.
18574 ISD::LoadExtType Ext = Ld->getExtensionType();
18575 unsigned Alignment = Ld->getAlignment();
18576 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18577 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18578 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18579 unsigned NumElems = RegVT.getVectorNumElements();
18583 SDValue Ptr = Ld->getBasePtr();
18584 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18586 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18588 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18589 Ld->getPointerInfo(), Ld->isVolatile(),
18590 Ld->isNonTemporal(), Ld->isInvariant(),
18592 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18593 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18594 Ld->getPointerInfo(), Ld->isVolatile(),
18595 Ld->isNonTemporal(), Ld->isInvariant(),
18596 std::min(16U, Alignment));
18597 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18599 Load2.getValue(1));
18601 SDValue NewVec = DAG.getUNDEF(RegVT);
18602 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18603 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18604 return DCI.CombineTo(N, NewVec, TF, true);
18607 // If this is a vector EXT Load then attempt to optimize it using a
18608 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18609 // expansion is still better than scalar code.
18610 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18611 // emit a shuffle and a arithmetic shift.
18612 // TODO: It is possible to support ZExt by zeroing the undef values
18613 // during the shuffle phase or after the shuffle.
18614 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18615 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18616 assert(MemVT != RegVT && "Cannot extend to the same type");
18617 assert(MemVT.isVector() && "Must load a vector from memory");
18619 unsigned NumElems = RegVT.getVectorNumElements();
18620 unsigned MemSz = MemVT.getSizeInBits();
18621 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18623 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18626 // All sizes must be a power of two.
18627 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18630 // Attempt to load the original value using scalar loads.
18631 // Find the largest scalar type that divides the total loaded size.
18632 MVT SclrLoadTy = MVT::i8;
18633 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18634 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18635 MVT Tp = (MVT::SimpleValueType)tp;
18636 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18641 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18642 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18644 SclrLoadTy = MVT::f64;
18646 // Calculate the number of scalar loads that we need to perform
18647 // in order to load our vector from memory.
18648 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18649 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18652 unsigned loadRegZize = RegSz;
18653 if (Ext == ISD::SEXTLOAD && RegSz == 256)
18656 // Represent our vector as a sequence of elements which are the
18657 // largest scalar that we can load.
18658 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18659 loadRegZize/SclrLoadTy.getSizeInBits());
18661 // Represent the data using the same element type that is stored in
18662 // memory. In practice, we ''widen'' MemVT.
18664 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18665 loadRegZize/MemVT.getScalarType().getSizeInBits());
18667 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18668 "Invalid vector type");
18670 // We can't shuffle using an illegal type.
18671 if (!TLI.isTypeLegal(WideVecVT))
18674 SmallVector<SDValue, 8> Chains;
18675 SDValue Ptr = Ld->getBasePtr();
18676 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18677 TLI.getPointerTy());
18678 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18680 for (unsigned i = 0; i < NumLoads; ++i) {
18681 // Perform a single load.
18682 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18683 Ptr, Ld->getPointerInfo(),
18684 Ld->isVolatile(), Ld->isNonTemporal(),
18685 Ld->isInvariant(), Ld->getAlignment());
18686 Chains.push_back(ScalarLoad.getValue(1));
18687 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18688 // another round of DAGCombining.
18690 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18692 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18693 ScalarLoad, DAG.getIntPtrConstant(i));
18695 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18698 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18701 // Bitcast the loaded value to a vector of the original element type, in
18702 // the size of the target vector type.
18703 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18704 unsigned SizeRatio = RegSz/MemSz;
18706 if (Ext == ISD::SEXTLOAD) {
18707 // If we have SSE4.1 we can directly emit a VSEXT node.
18708 if (Subtarget->hasSSE41()) {
18709 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18710 return DCI.CombineTo(N, Sext, TF, true);
18713 // Otherwise we'll shuffle the small elements in the high bits of the
18714 // larger type and perform an arithmetic shift. If the shift is not legal
18715 // it's better to scalarize.
18716 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18719 // Redistribute the loaded elements into the different locations.
18720 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18721 for (unsigned i = 0; i != NumElems; ++i)
18722 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18724 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18725 DAG.getUNDEF(WideVecVT),
18728 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18730 // Build the arithmetic shift.
18731 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18732 MemVT.getVectorElementType().getSizeInBits();
18733 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18734 DAG.getConstant(Amt, RegVT));
18736 return DCI.CombineTo(N, Shuff, TF, true);
18739 // Redistribute the loaded elements into the different locations.
18740 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18741 for (unsigned i = 0; i != NumElems; ++i)
18742 ShuffleVec[i*SizeRatio] = i;
18744 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18745 DAG.getUNDEF(WideVecVT),
18748 // Bitcast to the requested type.
18749 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18750 // Replace the original load with the new sequence
18751 // and return the new chain.
18752 return DCI.CombineTo(N, Shuff, TF, true);
18758 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18759 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18760 const X86Subtarget *Subtarget) {
18761 StoreSDNode *St = cast<StoreSDNode>(N);
18762 EVT VT = St->getValue().getValueType();
18763 EVT StVT = St->getMemoryVT();
18765 SDValue StoredVal = St->getOperand(1);
18766 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18768 // If we are saving a concatenation of two XMM registers, perform two stores.
18769 // On Sandy Bridge, 256-bit memory operations are executed by two
18770 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18771 // memory operation.
18772 unsigned Alignment = St->getAlignment();
18773 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18774 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18775 StVT == VT && !IsAligned) {
18776 unsigned NumElems = VT.getVectorNumElements();
18780 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18781 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18783 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18784 SDValue Ptr0 = St->getBasePtr();
18785 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18787 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18788 St->getPointerInfo(), St->isVolatile(),
18789 St->isNonTemporal(), Alignment);
18790 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18791 St->getPointerInfo(), St->isVolatile(),
18792 St->isNonTemporal(),
18793 std::min(16U, Alignment));
18794 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18797 // Optimize trunc store (of multiple scalars) to shuffle and store.
18798 // First, pack all of the elements in one place. Next, store to memory
18799 // in fewer chunks.
18800 if (St->isTruncatingStore() && VT.isVector()) {
18801 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18802 unsigned NumElems = VT.getVectorNumElements();
18803 assert(StVT != VT && "Cannot truncate to the same type");
18804 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18805 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18807 // From, To sizes and ElemCount must be pow of two
18808 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18809 // We are going to use the original vector elt for storing.
18810 // Accumulated smaller vector elements must be a multiple of the store size.
18811 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18813 unsigned SizeRatio = FromSz / ToSz;
18815 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18817 // Create a type on which we perform the shuffle
18818 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18819 StVT.getScalarType(), NumElems*SizeRatio);
18821 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18823 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18824 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18825 for (unsigned i = 0; i != NumElems; ++i)
18826 ShuffleVec[i] = i * SizeRatio;
18828 // Can't shuffle using an illegal type.
18829 if (!TLI.isTypeLegal(WideVecVT))
18832 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18833 DAG.getUNDEF(WideVecVT),
18835 // At this point all of the data is stored at the bottom of the
18836 // register. We now need to save it to mem.
18838 // Find the largest store unit
18839 MVT StoreType = MVT::i8;
18840 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18841 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18842 MVT Tp = (MVT::SimpleValueType)tp;
18843 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18847 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18848 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18849 (64 <= NumElems * ToSz))
18850 StoreType = MVT::f64;
18852 // Bitcast the original vector into a vector of store-size units
18853 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18854 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18855 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18856 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18857 SmallVector<SDValue, 8> Chains;
18858 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18859 TLI.getPointerTy());
18860 SDValue Ptr = St->getBasePtr();
18862 // Perform one or more big stores into memory.
18863 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18864 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18865 StoreType, ShuffWide,
18866 DAG.getIntPtrConstant(i));
18867 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18868 St->getPointerInfo(), St->isVolatile(),
18869 St->isNonTemporal(), St->getAlignment());
18870 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18871 Chains.push_back(Ch);
18874 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18878 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
18879 // the FP state in cases where an emms may be missing.
18880 // A preferable solution to the general problem is to figure out the right
18881 // places to insert EMMS. This qualifies as a quick hack.
18883 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18884 if (VT.getSizeInBits() != 64)
18887 const Function *F = DAG.getMachineFunction().getFunction();
18888 bool NoImplicitFloatOps = F->getAttributes().
18889 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18890 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18891 && Subtarget->hasSSE2();
18892 if ((VT.isVector() ||
18893 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18894 isa<LoadSDNode>(St->getValue()) &&
18895 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18896 St->getChain().hasOneUse() && !St->isVolatile()) {
18897 SDNode* LdVal = St->getValue().getNode();
18898 LoadSDNode *Ld = 0;
18899 int TokenFactorIndex = -1;
18900 SmallVector<SDValue, 8> Ops;
18901 SDNode* ChainVal = St->getChain().getNode();
18902 // Must be a store of a load. We currently handle two cases: the load
18903 // is a direct child, and it's under an intervening TokenFactor. It is
18904 // possible to dig deeper under nested TokenFactors.
18905 if (ChainVal == LdVal)
18906 Ld = cast<LoadSDNode>(St->getChain());
18907 else if (St->getValue().hasOneUse() &&
18908 ChainVal->getOpcode() == ISD::TokenFactor) {
18909 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18910 if (ChainVal->getOperand(i).getNode() == LdVal) {
18911 TokenFactorIndex = i;
18912 Ld = cast<LoadSDNode>(St->getValue());
18914 Ops.push_back(ChainVal->getOperand(i));
18918 if (!Ld || !ISD::isNormalLoad(Ld))
18921 // If this is not the MMX case, i.e. we are just turning i64 load/store
18922 // into f64 load/store, avoid the transformation if there are multiple
18923 // uses of the loaded value.
18924 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18929 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18930 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18932 if (Subtarget->is64Bit() || F64IsLegal) {
18933 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18934 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18935 Ld->getPointerInfo(), Ld->isVolatile(),
18936 Ld->isNonTemporal(), Ld->isInvariant(),
18937 Ld->getAlignment());
18938 SDValue NewChain = NewLd.getValue(1);
18939 if (TokenFactorIndex != -1) {
18940 Ops.push_back(NewChain);
18941 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18944 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18945 St->getPointerInfo(),
18946 St->isVolatile(), St->isNonTemporal(),
18947 St->getAlignment());
18950 // Otherwise, lower to two pairs of 32-bit loads / stores.
18951 SDValue LoAddr = Ld->getBasePtr();
18952 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18953 DAG.getConstant(4, MVT::i32));
18955 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18956 Ld->getPointerInfo(),
18957 Ld->isVolatile(), Ld->isNonTemporal(),
18958 Ld->isInvariant(), Ld->getAlignment());
18959 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18960 Ld->getPointerInfo().getWithOffset(4),
18961 Ld->isVolatile(), Ld->isNonTemporal(),
18963 MinAlign(Ld->getAlignment(), 4));
18965 SDValue NewChain = LoLd.getValue(1);
18966 if (TokenFactorIndex != -1) {
18967 Ops.push_back(LoLd);
18968 Ops.push_back(HiLd);
18969 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18973 LoAddr = St->getBasePtr();
18974 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18975 DAG.getConstant(4, MVT::i32));
18977 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18978 St->getPointerInfo(),
18979 St->isVolatile(), St->isNonTemporal(),
18980 St->getAlignment());
18981 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18982 St->getPointerInfo().getWithOffset(4),
18984 St->isNonTemporal(),
18985 MinAlign(St->getAlignment(), 4));
18986 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18991 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18992 /// and return the operands for the horizontal operation in LHS and RHS. A
18993 /// horizontal operation performs the binary operation on successive elements
18994 /// of its first operand, then on successive elements of its second operand,
18995 /// returning the resulting values in a vector. For example, if
18996 /// A = < float a0, float a1, float a2, float a3 >
18998 /// B = < float b0, float b1, float b2, float b3 >
18999 /// then the result of doing a horizontal operation on A and B is
19000 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19001 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19002 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19003 /// set to A, RHS to B, and the routine returns 'true'.
19004 /// Note that the binary operation should have the property that if one of the
19005 /// operands is UNDEF then the result is UNDEF.
19006 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19007 // Look for the following pattern: if
19008 // A = < float a0, float a1, float a2, float a3 >
19009 // B = < float b0, float b1, float b2, float b3 >
19011 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19012 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19013 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19014 // which is A horizontal-op B.
19016 // At least one of the operands should be a vector shuffle.
19017 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19018 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19021 MVT VT = LHS.getSimpleValueType();
19023 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19024 "Unsupported vector type for horizontal add/sub");
19026 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19027 // operate independently on 128-bit lanes.
19028 unsigned NumElts = VT.getVectorNumElements();
19029 unsigned NumLanes = VT.getSizeInBits()/128;
19030 unsigned NumLaneElts = NumElts / NumLanes;
19031 assert((NumLaneElts % 2 == 0) &&
19032 "Vector type should have an even number of elements in each lane");
19033 unsigned HalfLaneElts = NumLaneElts/2;
19035 // View LHS in the form
19036 // LHS = VECTOR_SHUFFLE A, B, LMask
19037 // If LHS is not a shuffle then pretend it is the shuffle
19038 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19039 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19042 SmallVector<int, 16> LMask(NumElts);
19043 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19044 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19045 A = LHS.getOperand(0);
19046 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19047 B = LHS.getOperand(1);
19048 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19049 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19051 if (LHS.getOpcode() != ISD::UNDEF)
19053 for (unsigned i = 0; i != NumElts; ++i)
19057 // Likewise, view RHS in the form
19058 // RHS = VECTOR_SHUFFLE C, D, RMask
19060 SmallVector<int, 16> RMask(NumElts);
19061 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19062 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19063 C = RHS.getOperand(0);
19064 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19065 D = RHS.getOperand(1);
19066 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19067 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19069 if (RHS.getOpcode() != ISD::UNDEF)
19071 for (unsigned i = 0; i != NumElts; ++i)
19075 // Check that the shuffles are both shuffling the same vectors.
19076 if (!(A == C && B == D) && !(A == D && B == C))
19079 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19080 if (!A.getNode() && !B.getNode())
19083 // If A and B occur in reverse order in RHS, then "swap" them (which means
19084 // rewriting the mask).
19086 CommuteVectorShuffleMask(RMask, NumElts);
19088 // At this point LHS and RHS are equivalent to
19089 // LHS = VECTOR_SHUFFLE A, B, LMask
19090 // RHS = VECTOR_SHUFFLE A, B, RMask
19091 // Check that the masks correspond to performing a horizontal operation.
19092 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19093 for (unsigned i = 0; i != NumLaneElts; ++i) {
19094 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19096 // Ignore any UNDEF components.
19097 if (LIdx < 0 || RIdx < 0 ||
19098 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19099 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19102 // Check that successive elements are being operated on. If not, this is
19103 // not a horizontal operation.
19104 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19105 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19106 if (!(LIdx == Index && RIdx == Index + 1) &&
19107 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19112 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19113 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19117 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19118 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19119 const X86Subtarget *Subtarget) {
19120 EVT VT = N->getValueType(0);
19121 SDValue LHS = N->getOperand(0);
19122 SDValue RHS = N->getOperand(1);
19124 // Try to synthesize horizontal adds from adds of shuffles.
19125 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19126 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19127 isHorizontalBinOp(LHS, RHS, true))
19128 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19132 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19133 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19134 const X86Subtarget *Subtarget) {
19135 EVT VT = N->getValueType(0);
19136 SDValue LHS = N->getOperand(0);
19137 SDValue RHS = N->getOperand(1);
19139 // Try to synthesize horizontal subs from subs of shuffles.
19140 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19141 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19142 isHorizontalBinOp(LHS, RHS, false))
19143 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19147 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19148 /// X86ISD::FXOR nodes.
19149 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19150 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19151 // F[X]OR(0.0, x) -> x
19152 // F[X]OR(x, 0.0) -> x
19153 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19154 if (C->getValueAPF().isPosZero())
19155 return N->getOperand(1);
19156 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19157 if (C->getValueAPF().isPosZero())
19158 return N->getOperand(0);
19162 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19163 /// X86ISD::FMAX nodes.
19164 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19165 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19167 // Only perform optimizations if UnsafeMath is used.
19168 if (!DAG.getTarget().Options.UnsafeFPMath)
19171 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19172 // into FMINC and FMAXC, which are Commutative operations.
19173 unsigned NewOp = 0;
19174 switch (N->getOpcode()) {
19175 default: llvm_unreachable("unknown opcode");
19176 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19177 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19180 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19181 N->getOperand(0), N->getOperand(1));
19184 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19185 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19186 // FAND(0.0, x) -> 0.0
19187 // FAND(x, 0.0) -> 0.0
19188 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19189 if (C->getValueAPF().isPosZero())
19190 return N->getOperand(0);
19191 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19192 if (C->getValueAPF().isPosZero())
19193 return N->getOperand(1);
19197 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19198 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19199 // FANDN(x, 0.0) -> 0.0
19200 // FANDN(0.0, x) -> x
19201 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19202 if (C->getValueAPF().isPosZero())
19203 return N->getOperand(1);
19204 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19205 if (C->getValueAPF().isPosZero())
19206 return N->getOperand(1);
19210 static SDValue PerformBTCombine(SDNode *N,
19212 TargetLowering::DAGCombinerInfo &DCI) {
19213 // BT ignores high bits in the bit index operand.
19214 SDValue Op1 = N->getOperand(1);
19215 if (Op1.hasOneUse()) {
19216 unsigned BitWidth = Op1.getValueSizeInBits();
19217 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19218 APInt KnownZero, KnownOne;
19219 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19220 !DCI.isBeforeLegalizeOps());
19221 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19222 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19223 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19224 DCI.CommitTargetLoweringOpt(TLO);
19229 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19230 SDValue Op = N->getOperand(0);
19231 if (Op.getOpcode() == ISD::BITCAST)
19232 Op = Op.getOperand(0);
19233 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19234 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19235 VT.getVectorElementType().getSizeInBits() ==
19236 OpVT.getVectorElementType().getSizeInBits()) {
19237 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19242 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19243 const X86Subtarget *Subtarget) {
19244 EVT VT = N->getValueType(0);
19245 if (!VT.isVector())
19248 SDValue N0 = N->getOperand(0);
19249 SDValue N1 = N->getOperand(1);
19250 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19253 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19254 // both SSE and AVX2 since there is no sign-extended shift right
19255 // operation on a vector with 64-bit elements.
19256 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19257 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19258 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19259 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19260 SDValue N00 = N0.getOperand(0);
19262 // EXTLOAD has a better solution on AVX2,
19263 // it may be replaced with X86ISD::VSEXT node.
19264 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19265 if (!ISD::isNormalLoad(N00.getNode()))
19268 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19269 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19271 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19277 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19278 TargetLowering::DAGCombinerInfo &DCI,
19279 const X86Subtarget *Subtarget) {
19280 if (!DCI.isBeforeLegalizeOps())
19283 if (!Subtarget->hasFp256())
19286 EVT VT = N->getValueType(0);
19287 if (VT.isVector() && VT.getSizeInBits() == 256) {
19288 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19296 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19297 const X86Subtarget* Subtarget) {
19299 EVT VT = N->getValueType(0);
19301 // Let legalize expand this if it isn't a legal type yet.
19302 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19305 EVT ScalarVT = VT.getScalarType();
19306 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19307 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19310 SDValue A = N->getOperand(0);
19311 SDValue B = N->getOperand(1);
19312 SDValue C = N->getOperand(2);
19314 bool NegA = (A.getOpcode() == ISD::FNEG);
19315 bool NegB = (B.getOpcode() == ISD::FNEG);
19316 bool NegC = (C.getOpcode() == ISD::FNEG);
19318 // Negative multiplication when NegA xor NegB
19319 bool NegMul = (NegA != NegB);
19321 A = A.getOperand(0);
19323 B = B.getOperand(0);
19325 C = C.getOperand(0);
19329 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19331 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19333 return DAG.getNode(Opcode, dl, VT, A, B, C);
19336 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19337 TargetLowering::DAGCombinerInfo &DCI,
19338 const X86Subtarget *Subtarget) {
19339 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19340 // (and (i32 x86isd::setcc_carry), 1)
19341 // This eliminates the zext. This transformation is necessary because
19342 // ISD::SETCC is always legalized to i8.
19344 SDValue N0 = N->getOperand(0);
19345 EVT VT = N->getValueType(0);
19347 if (N0.getOpcode() == ISD::AND &&
19349 N0.getOperand(0).hasOneUse()) {
19350 SDValue N00 = N0.getOperand(0);
19351 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19352 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19353 if (!C || C->getZExtValue() != 1)
19355 return DAG.getNode(ISD::AND, dl, VT,
19356 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19357 N00.getOperand(0), N00.getOperand(1)),
19358 DAG.getConstant(1, VT));
19362 if (N0.getOpcode() == ISD::TRUNCATE &&
19364 N0.getOperand(0).hasOneUse()) {
19365 SDValue N00 = N0.getOperand(0);
19366 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19367 return DAG.getNode(ISD::AND, dl, VT,
19368 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19369 N00.getOperand(0), N00.getOperand(1)),
19370 DAG.getConstant(1, VT));
19373 if (VT.is256BitVector()) {
19374 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19382 // Optimize x == -y --> x+y == 0
19383 // x != -y --> x+y != 0
19384 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19385 const X86Subtarget* Subtarget) {
19386 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19387 SDValue LHS = N->getOperand(0);
19388 SDValue RHS = N->getOperand(1);
19389 EVT VT = N->getValueType(0);
19392 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19393 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19394 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19395 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19396 LHS.getValueType(), RHS, LHS.getOperand(1));
19397 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19398 addV, DAG.getConstant(0, addV.getValueType()), CC);
19400 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19401 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19402 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19403 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19404 RHS.getValueType(), LHS, RHS.getOperand(1));
19405 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19406 addV, DAG.getConstant(0, addV.getValueType()), CC);
19409 if (VT.getScalarType() == MVT::i1) {
19410 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19411 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19412 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19413 if (!IsSEXT0 && !IsVZero0)
19415 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19416 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19417 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19419 if (!IsSEXT1 && !IsVZero1)
19422 if (IsSEXT0 && IsVZero1) {
19423 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19424 if (CC == ISD::SETEQ)
19425 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19426 return LHS.getOperand(0);
19428 if (IsSEXT1 && IsVZero0) {
19429 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19430 if (CC == ISD::SETEQ)
19431 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19432 return RHS.getOperand(0);
19439 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19440 // as "sbb reg,reg", since it can be extended without zext and produces
19441 // an all-ones bit which is more useful than 0/1 in some cases.
19442 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19445 return DAG.getNode(ISD::AND, DL, VT,
19446 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19447 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19448 DAG.getConstant(1, VT));
19449 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19450 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19451 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19452 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19455 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19456 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19457 TargetLowering::DAGCombinerInfo &DCI,
19458 const X86Subtarget *Subtarget) {
19460 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19461 SDValue EFLAGS = N->getOperand(1);
19463 if (CC == X86::COND_A) {
19464 // Try to convert COND_A into COND_B in an attempt to facilitate
19465 // materializing "setb reg".
19467 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19468 // cannot take an immediate as its first operand.
19470 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19471 EFLAGS.getValueType().isInteger() &&
19472 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19473 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19474 EFLAGS.getNode()->getVTList(),
19475 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19476 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19477 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19481 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19482 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19484 if (CC == X86::COND_B)
19485 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19489 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19490 if (Flags.getNode()) {
19491 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19492 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19498 // Optimize branch condition evaluation.
19500 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19501 TargetLowering::DAGCombinerInfo &DCI,
19502 const X86Subtarget *Subtarget) {
19504 SDValue Chain = N->getOperand(0);
19505 SDValue Dest = N->getOperand(1);
19506 SDValue EFLAGS = N->getOperand(3);
19507 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19511 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19512 if (Flags.getNode()) {
19513 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19514 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19521 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19522 const X86TargetLowering *XTLI) {
19523 SDValue Op0 = N->getOperand(0);
19524 EVT InVT = Op0->getValueType(0);
19526 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19527 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19529 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19530 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19531 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19534 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19535 // a 32-bit target where SSE doesn't support i64->FP operations.
19536 if (Op0.getOpcode() == ISD::LOAD) {
19537 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19538 EVT VT = Ld->getValueType(0);
19539 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19540 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19541 !XTLI->getSubtarget()->is64Bit() &&
19543 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19544 Ld->getChain(), Op0, DAG);
19545 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19552 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19553 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19554 X86TargetLowering::DAGCombinerInfo &DCI) {
19555 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19556 // the result is either zero or one (depending on the input carry bit).
19557 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19558 if (X86::isZeroNode(N->getOperand(0)) &&
19559 X86::isZeroNode(N->getOperand(1)) &&
19560 // We don't have a good way to replace an EFLAGS use, so only do this when
19562 SDValue(N, 1).use_empty()) {
19564 EVT VT = N->getValueType(0);
19565 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19566 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19567 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19568 DAG.getConstant(X86::COND_B,MVT::i8),
19570 DAG.getConstant(1, VT));
19571 return DCI.CombineTo(N, Res1, CarryOut);
19577 // fold (add Y, (sete X, 0)) -> adc 0, Y
19578 // (add Y, (setne X, 0)) -> sbb -1, Y
19579 // (sub (sete X, 0), Y) -> sbb 0, Y
19580 // (sub (setne X, 0), Y) -> adc -1, Y
19581 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19584 // Look through ZExts.
19585 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19586 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19589 SDValue SetCC = Ext.getOperand(0);
19590 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19593 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19594 if (CC != X86::COND_E && CC != X86::COND_NE)
19597 SDValue Cmp = SetCC.getOperand(1);
19598 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19599 !X86::isZeroNode(Cmp.getOperand(1)) ||
19600 !Cmp.getOperand(0).getValueType().isInteger())
19603 SDValue CmpOp0 = Cmp.getOperand(0);
19604 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19605 DAG.getConstant(1, CmpOp0.getValueType()));
19607 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19608 if (CC == X86::COND_NE)
19609 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19610 DL, OtherVal.getValueType(), OtherVal,
19611 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19612 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19613 DL, OtherVal.getValueType(), OtherVal,
19614 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19617 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19618 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19619 const X86Subtarget *Subtarget) {
19620 EVT VT = N->getValueType(0);
19621 SDValue Op0 = N->getOperand(0);
19622 SDValue Op1 = N->getOperand(1);
19624 // Try to synthesize horizontal adds from adds of shuffles.
19625 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19626 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19627 isHorizontalBinOp(Op0, Op1, true))
19628 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19630 return OptimizeConditionalInDecrement(N, DAG);
19633 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19634 const X86Subtarget *Subtarget) {
19635 SDValue Op0 = N->getOperand(0);
19636 SDValue Op1 = N->getOperand(1);
19638 // X86 can't encode an immediate LHS of a sub. See if we can push the
19639 // negation into a preceding instruction.
19640 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19641 // If the RHS of the sub is a XOR with one use and a constant, invert the
19642 // immediate. Then add one to the LHS of the sub so we can turn
19643 // X-Y -> X+~Y+1, saving one register.
19644 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19645 isa<ConstantSDNode>(Op1.getOperand(1))) {
19646 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19647 EVT VT = Op0.getValueType();
19648 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19650 DAG.getConstant(~XorC, VT));
19651 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19652 DAG.getConstant(C->getAPIntValue()+1, VT));
19656 // Try to synthesize horizontal adds from adds of shuffles.
19657 EVT VT = N->getValueType(0);
19658 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19659 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19660 isHorizontalBinOp(Op0, Op1, true))
19661 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19663 return OptimizeConditionalInDecrement(N, DAG);
19666 /// performVZEXTCombine - Performs build vector combines
19667 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19668 TargetLowering::DAGCombinerInfo &DCI,
19669 const X86Subtarget *Subtarget) {
19670 // (vzext (bitcast (vzext (x)) -> (vzext x)
19671 SDValue In = N->getOperand(0);
19672 while (In.getOpcode() == ISD::BITCAST)
19673 In = In.getOperand(0);
19675 if (In.getOpcode() != X86ISD::VZEXT)
19678 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19682 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19683 DAGCombinerInfo &DCI) const {
19684 SelectionDAG &DAG = DCI.DAG;
19685 switch (N->getOpcode()) {
19687 case ISD::EXTRACT_VECTOR_ELT:
19688 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19690 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19691 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19692 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
19693 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
19694 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
19695 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
19698 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
19699 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
19700 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
19701 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
19702 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
19703 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
19704 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
19705 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
19706 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
19708 case X86ISD::FOR: return PerformFORCombine(N, DAG);
19710 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
19711 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
19712 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
19713 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
19714 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
19715 case ISD::ANY_EXTEND:
19716 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
19717 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
19718 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19719 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19720 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
19721 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19722 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19723 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
19724 case X86ISD::SHUFP: // Handle all target specific shuffles
19725 case X86ISD::PALIGNR:
19726 case X86ISD::UNPCKH:
19727 case X86ISD::UNPCKL:
19728 case X86ISD::MOVHLPS:
19729 case X86ISD::MOVLHPS:
19730 case X86ISD::PSHUFD:
19731 case X86ISD::PSHUFHW:
19732 case X86ISD::PSHUFLW:
19733 case X86ISD::MOVSS:
19734 case X86ISD::MOVSD:
19735 case X86ISD::VPERMILP:
19736 case X86ISD::VPERM2X128:
19737 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19738 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
19744 /// isTypeDesirableForOp - Return true if the target has native support for
19745 /// the specified value type and it is 'desirable' to use the type for the
19746 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19747 /// instruction encodings are longer and some i16 instructions are slow.
19748 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19749 if (!isTypeLegal(VT))
19751 if (VT != MVT::i16)
19758 case ISD::SIGN_EXTEND:
19759 case ISD::ZERO_EXTEND:
19760 case ISD::ANY_EXTEND:
19773 /// IsDesirableToPromoteOp - This method query the target whether it is
19774 /// beneficial for dag combiner to promote the specified node. If true, it
19775 /// should return the desired promotion type by reference.
19776 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19777 EVT VT = Op.getValueType();
19778 if (VT != MVT::i16)
19781 bool Promote = false;
19782 bool Commute = false;
19783 switch (Op.getOpcode()) {
19786 LoadSDNode *LD = cast<LoadSDNode>(Op);
19787 // If the non-extending load has a single use and it's not live out, then it
19788 // might be folded.
19789 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19790 Op.hasOneUse()*/) {
19791 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19792 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19793 // The only case where we'd want to promote LOAD (rather then it being
19794 // promoted as an operand is when it's only use is liveout.
19795 if (UI->getOpcode() != ISD::CopyToReg)
19802 case ISD::SIGN_EXTEND:
19803 case ISD::ZERO_EXTEND:
19804 case ISD::ANY_EXTEND:
19809 SDValue N0 = Op.getOperand(0);
19810 // Look out for (store (shl (load), x)).
19811 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19824 SDValue N0 = Op.getOperand(0);
19825 SDValue N1 = Op.getOperand(1);
19826 if (!Commute && MayFoldLoad(N1))
19828 // Avoid disabling potential load folding opportunities.
19829 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19831 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19841 //===----------------------------------------------------------------------===//
19842 // X86 Inline Assembly Support
19843 //===----------------------------------------------------------------------===//
19846 // Helper to match a string separated by whitespace.
19847 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19848 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19850 for (unsigned i = 0, e = args.size(); i != e; ++i) {
19851 StringRef piece(*args[i]);
19852 if (!s.startswith(piece)) // Check if the piece matches.
19855 s = s.substr(piece.size());
19856 StringRef::size_type pos = s.find_first_not_of(" \t");
19857 if (pos == 0) // We matched a prefix.
19865 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19868 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19870 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19871 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19872 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19873 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19875 if (AsmPieces.size() == 3)
19877 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19884 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19885 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19887 std::string AsmStr = IA->getAsmString();
19889 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19890 if (!Ty || Ty->getBitWidth() % 16 != 0)
19893 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19894 SmallVector<StringRef, 4> AsmPieces;
19895 SplitString(AsmStr, AsmPieces, ";\n");
19897 switch (AsmPieces.size()) {
19898 default: return false;
19900 // FIXME: this should verify that we are targeting a 486 or better. If not,
19901 // we will turn this bswap into something that will be lowered to logical
19902 // ops instead of emitting the bswap asm. For now, we don't support 486 or
19903 // lower so don't worry about this.
19905 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19906 matchAsm(AsmPieces[0], "bswapl", "$0") ||
19907 matchAsm(AsmPieces[0], "bswapq", "$0") ||
19908 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19909 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19910 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19911 // No need to check constraints, nothing other than the equivalent of
19912 // "=r,0" would be valid here.
19913 return IntrinsicLowering::LowerToByteSwap(CI);
19916 // rorw $$8, ${0:w} --> llvm.bswap.i16
19917 if (CI->getType()->isIntegerTy(16) &&
19918 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19919 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19920 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19922 const std::string &ConstraintsStr = IA->getConstraintString();
19923 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19924 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19925 if (clobbersFlagRegisters(AsmPieces))
19926 return IntrinsicLowering::LowerToByteSwap(CI);
19930 if (CI->getType()->isIntegerTy(32) &&
19931 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19932 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19933 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19934 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19936 const std::string &ConstraintsStr = IA->getConstraintString();
19937 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19938 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19939 if (clobbersFlagRegisters(AsmPieces))
19940 return IntrinsicLowering::LowerToByteSwap(CI);
19943 if (CI->getType()->isIntegerTy(64)) {
19944 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19945 if (Constraints.size() >= 2 &&
19946 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19947 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19948 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
19949 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19950 matchAsm(AsmPieces[1], "bswap", "%edx") &&
19951 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19952 return IntrinsicLowering::LowerToByteSwap(CI);
19960 /// getConstraintType - Given a constraint letter, return the type of
19961 /// constraint it is for this target.
19962 X86TargetLowering::ConstraintType
19963 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19964 if (Constraint.size() == 1) {
19965 switch (Constraint[0]) {
19976 return C_RegisterClass;
20000 return TargetLowering::getConstraintType(Constraint);
20003 /// Examine constraint type and operand type and determine a weight value.
20004 /// This object must already have been set up with the operand type
20005 /// and the current alternative constraint selected.
20006 TargetLowering::ConstraintWeight
20007 X86TargetLowering::getSingleConstraintMatchWeight(
20008 AsmOperandInfo &info, const char *constraint) const {
20009 ConstraintWeight weight = CW_Invalid;
20010 Value *CallOperandVal = info.CallOperandVal;
20011 // If we don't have a value, we can't do a match,
20012 // but allow it at the lowest weight.
20013 if (CallOperandVal == NULL)
20015 Type *type = CallOperandVal->getType();
20016 // Look at the constraint type.
20017 switch (*constraint) {
20019 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20030 if (CallOperandVal->getType()->isIntegerTy())
20031 weight = CW_SpecificReg;
20036 if (type->isFloatingPointTy())
20037 weight = CW_SpecificReg;
20040 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20041 weight = CW_SpecificReg;
20045 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20046 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20047 weight = CW_Register;
20050 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20051 if (C->getZExtValue() <= 31)
20052 weight = CW_Constant;
20056 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20057 if (C->getZExtValue() <= 63)
20058 weight = CW_Constant;
20062 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20063 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20064 weight = CW_Constant;
20068 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20069 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20070 weight = CW_Constant;
20074 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20075 if (C->getZExtValue() <= 3)
20076 weight = CW_Constant;
20080 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20081 if (C->getZExtValue() <= 0xff)
20082 weight = CW_Constant;
20087 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20088 weight = CW_Constant;
20092 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20093 if ((C->getSExtValue() >= -0x80000000LL) &&
20094 (C->getSExtValue() <= 0x7fffffffLL))
20095 weight = CW_Constant;
20099 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20100 if (C->getZExtValue() <= 0xffffffff)
20101 weight = CW_Constant;
20108 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20109 /// with another that has more specific requirements based on the type of the
20110 /// corresponding operand.
20111 const char *X86TargetLowering::
20112 LowerXConstraint(EVT ConstraintVT) const {
20113 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20114 // 'f' like normal targets.
20115 if (ConstraintVT.isFloatingPoint()) {
20116 if (Subtarget->hasSSE2())
20118 if (Subtarget->hasSSE1())
20122 return TargetLowering::LowerXConstraint(ConstraintVT);
20125 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20126 /// vector. If it is invalid, don't add anything to Ops.
20127 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20128 std::string &Constraint,
20129 std::vector<SDValue>&Ops,
20130 SelectionDAG &DAG) const {
20131 SDValue Result(0, 0);
20133 // Only support length 1 constraints for now.
20134 if (Constraint.length() > 1) return;
20136 char ConstraintLetter = Constraint[0];
20137 switch (ConstraintLetter) {
20140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20141 if (C->getZExtValue() <= 31) {
20142 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20148 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20149 if (C->getZExtValue() <= 63) {
20150 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20156 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20157 if (isInt<8>(C->getSExtValue())) {
20158 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20164 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20165 if (C->getZExtValue() <= 255) {
20166 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20172 // 32-bit signed value
20173 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20174 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20175 C->getSExtValue())) {
20176 // Widen to 64 bits here to get it sign extended.
20177 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20180 // FIXME gcc accepts some relocatable values here too, but only in certain
20181 // memory models; it's complicated.
20186 // 32-bit unsigned value
20187 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20188 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20189 C->getZExtValue())) {
20190 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20194 // FIXME gcc accepts some relocatable values here too, but only in certain
20195 // memory models; it's complicated.
20199 // Literal immediates are always ok.
20200 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20201 // Widen to 64 bits here to get it sign extended.
20202 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20206 // In any sort of PIC mode addresses need to be computed at runtime by
20207 // adding in a register or some sort of table lookup. These can't
20208 // be used as immediates.
20209 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20212 // If we are in non-pic codegen mode, we allow the address of a global (with
20213 // an optional displacement) to be used with 'i'.
20214 GlobalAddressSDNode *GA = 0;
20215 int64_t Offset = 0;
20217 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20219 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20220 Offset += GA->getOffset();
20222 } else if (Op.getOpcode() == ISD::ADD) {
20223 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20224 Offset += C->getZExtValue();
20225 Op = Op.getOperand(0);
20228 } else if (Op.getOpcode() == ISD::SUB) {
20229 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20230 Offset += -C->getZExtValue();
20231 Op = Op.getOperand(0);
20236 // Otherwise, this isn't something we can handle, reject it.
20240 const GlobalValue *GV = GA->getGlobal();
20241 // If we require an extra load to get this address, as in PIC mode, we
20242 // can't accept it.
20243 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20244 getTargetMachine())))
20247 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20248 GA->getValueType(0), Offset);
20253 if (Result.getNode()) {
20254 Ops.push_back(Result);
20257 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20260 std::pair<unsigned, const TargetRegisterClass*>
20261 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20263 // First, see if this is a constraint that directly corresponds to an LLVM
20265 if (Constraint.size() == 1) {
20266 // GCC Constraint Letters
20267 switch (Constraint[0]) {
20269 // TODO: Slight differences here in allocation order and leaving
20270 // RIP in the class. Do they matter any more here than they do
20271 // in the normal allocation?
20272 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20273 if (Subtarget->is64Bit()) {
20274 if (VT == MVT::i32 || VT == MVT::f32)
20275 return std::make_pair(0U, &X86::GR32RegClass);
20276 if (VT == MVT::i16)
20277 return std::make_pair(0U, &X86::GR16RegClass);
20278 if (VT == MVT::i8 || VT == MVT::i1)
20279 return std::make_pair(0U, &X86::GR8RegClass);
20280 if (VT == MVT::i64 || VT == MVT::f64)
20281 return std::make_pair(0U, &X86::GR64RegClass);
20284 // 32-bit fallthrough
20285 case 'Q': // Q_REGS
20286 if (VT == MVT::i32 || VT == MVT::f32)
20287 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20288 if (VT == MVT::i16)
20289 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20290 if (VT == MVT::i8 || VT == MVT::i1)
20291 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20292 if (VT == MVT::i64)
20293 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20295 case 'r': // GENERAL_REGS
20296 case 'l': // INDEX_REGS
20297 if (VT == MVT::i8 || VT == MVT::i1)
20298 return std::make_pair(0U, &X86::GR8RegClass);
20299 if (VT == MVT::i16)
20300 return std::make_pair(0U, &X86::GR16RegClass);
20301 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20302 return std::make_pair(0U, &X86::GR32RegClass);
20303 return std::make_pair(0U, &X86::GR64RegClass);
20304 case 'R': // LEGACY_REGS
20305 if (VT == MVT::i8 || VT == MVT::i1)
20306 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20307 if (VT == MVT::i16)
20308 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20309 if (VT == MVT::i32 || !Subtarget->is64Bit())
20310 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20311 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20312 case 'f': // FP Stack registers.
20313 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20314 // value to the correct fpstack register class.
20315 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20316 return std::make_pair(0U, &X86::RFP32RegClass);
20317 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20318 return std::make_pair(0U, &X86::RFP64RegClass);
20319 return std::make_pair(0U, &X86::RFP80RegClass);
20320 case 'y': // MMX_REGS if MMX allowed.
20321 if (!Subtarget->hasMMX()) break;
20322 return std::make_pair(0U, &X86::VR64RegClass);
20323 case 'Y': // SSE_REGS if SSE2 allowed
20324 if (!Subtarget->hasSSE2()) break;
20326 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20327 if (!Subtarget->hasSSE1()) break;
20329 switch (VT.SimpleTy) {
20331 // Scalar SSE types.
20334 return std::make_pair(0U, &X86::FR32RegClass);
20337 return std::make_pair(0U, &X86::FR64RegClass);
20345 return std::make_pair(0U, &X86::VR128RegClass);
20353 return std::make_pair(0U, &X86::VR256RegClass);
20358 return std::make_pair(0U, &X86::VR512RegClass);
20364 // Use the default implementation in TargetLowering to convert the register
20365 // constraint into a member of a register class.
20366 std::pair<unsigned, const TargetRegisterClass*> Res;
20367 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20369 // Not found as a standard register?
20370 if (Res.second == 0) {
20371 // Map st(0) -> st(7) -> ST0
20372 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20373 tolower(Constraint[1]) == 's' &&
20374 tolower(Constraint[2]) == 't' &&
20375 Constraint[3] == '(' &&
20376 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20377 Constraint[5] == ')' &&
20378 Constraint[6] == '}') {
20380 Res.first = X86::ST0+Constraint[4]-'0';
20381 Res.second = &X86::RFP80RegClass;
20385 // GCC allows "st(0)" to be called just plain "st".
20386 if (StringRef("{st}").equals_lower(Constraint)) {
20387 Res.first = X86::ST0;
20388 Res.second = &X86::RFP80RegClass;
20393 if (StringRef("{flags}").equals_lower(Constraint)) {
20394 Res.first = X86::EFLAGS;
20395 Res.second = &X86::CCRRegClass;
20399 // 'A' means EAX + EDX.
20400 if (Constraint == "A") {
20401 Res.first = X86::EAX;
20402 Res.second = &X86::GR32_ADRegClass;
20408 // Otherwise, check to see if this is a register class of the wrong value
20409 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20410 // turn into {ax},{dx}.
20411 if (Res.second->hasType(VT))
20412 return Res; // Correct type already, nothing to do.
20414 // All of the single-register GCC register classes map their values onto
20415 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20416 // really want an 8-bit or 32-bit register, map to the appropriate register
20417 // class and return the appropriate register.
20418 if (Res.second == &X86::GR16RegClass) {
20419 if (VT == MVT::i8 || VT == MVT::i1) {
20420 unsigned DestReg = 0;
20421 switch (Res.first) {
20423 case X86::AX: DestReg = X86::AL; break;
20424 case X86::DX: DestReg = X86::DL; break;
20425 case X86::CX: DestReg = X86::CL; break;
20426 case X86::BX: DestReg = X86::BL; break;
20429 Res.first = DestReg;
20430 Res.second = &X86::GR8RegClass;
20432 } else if (VT == MVT::i32 || VT == MVT::f32) {
20433 unsigned DestReg = 0;
20434 switch (Res.first) {
20436 case X86::AX: DestReg = X86::EAX; break;
20437 case X86::DX: DestReg = X86::EDX; break;
20438 case X86::CX: DestReg = X86::ECX; break;
20439 case X86::BX: DestReg = X86::EBX; break;
20440 case X86::SI: DestReg = X86::ESI; break;
20441 case X86::DI: DestReg = X86::EDI; break;
20442 case X86::BP: DestReg = X86::EBP; break;
20443 case X86::SP: DestReg = X86::ESP; break;
20446 Res.first = DestReg;
20447 Res.second = &X86::GR32RegClass;
20449 } else if (VT == MVT::i64 || VT == MVT::f64) {
20450 unsigned DestReg = 0;
20451 switch (Res.first) {
20453 case X86::AX: DestReg = X86::RAX; break;
20454 case X86::DX: DestReg = X86::RDX; break;
20455 case X86::CX: DestReg = X86::RCX; break;
20456 case X86::BX: DestReg = X86::RBX; break;
20457 case X86::SI: DestReg = X86::RSI; break;
20458 case X86::DI: DestReg = X86::RDI; break;
20459 case X86::BP: DestReg = X86::RBP; break;
20460 case X86::SP: DestReg = X86::RSP; break;
20463 Res.first = DestReg;
20464 Res.second = &X86::GR64RegClass;
20467 } else if (Res.second == &X86::FR32RegClass ||
20468 Res.second == &X86::FR64RegClass ||
20469 Res.second == &X86::VR128RegClass ||
20470 Res.second == &X86::VR256RegClass ||
20471 Res.second == &X86::FR32XRegClass ||
20472 Res.second == &X86::FR64XRegClass ||
20473 Res.second == &X86::VR128XRegClass ||
20474 Res.second == &X86::VR256XRegClass ||
20475 Res.second == &X86::VR512RegClass) {
20476 // Handle references to XMM physical registers that got mapped into the
20477 // wrong class. This can happen with constraints like {xmm0} where the
20478 // target independent register mapper will just pick the first match it can
20479 // find, ignoring the required type.
20481 if (VT == MVT::f32 || VT == MVT::i32)
20482 Res.second = &X86::FR32RegClass;
20483 else if (VT == MVT::f64 || VT == MVT::i64)
20484 Res.second = &X86::FR64RegClass;
20485 else if (X86::VR128RegClass.hasType(VT))
20486 Res.second = &X86::VR128RegClass;
20487 else if (X86::VR256RegClass.hasType(VT))
20488 Res.second = &X86::VR256RegClass;
20489 else if (X86::VR512RegClass.hasType(VT))
20490 Res.second = &X86::VR512RegClass;