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() && !Subtarget->isTargetCygMing()) {
254 // Setup Windows compiler runtime calls.
255 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
256 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
257 setLibcallName(RTLIB::SREM_I64, "_allrem");
258 setLibcallName(RTLIB::UREM_I64, "_aullrem");
259 setLibcallName(RTLIB::MUL_I64, "_allmul");
260 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
261 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266 // The _ftol2 runtime function has an unusual calling conv, which
267 // is modeled by a special pseudo-instruction.
268 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
269 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
270 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
271 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
274 if (Subtarget->isTargetDarwin()) {
275 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
276 setUseUnderscoreSetJmp(false);
277 setUseUnderscoreLongJmp(false);
278 } else if (Subtarget->isTargetMingw()) {
279 // MS runtime is weird: it exports _setjmp, but longjmp!
280 setUseUnderscoreSetJmp(true);
281 setUseUnderscoreLongJmp(false);
283 setUseUnderscoreSetJmp(true);
284 setUseUnderscoreLongJmp(true);
287 // Set up the register classes.
288 addRegisterClass(MVT::i8, &X86::GR8RegClass);
289 addRegisterClass(MVT::i16, &X86::GR16RegClass);
290 addRegisterClass(MVT::i32, &X86::GR32RegClass);
291 if (Subtarget->is64Bit())
292 addRegisterClass(MVT::i64, &X86::GR64RegClass);
294 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296 // We don't accept any truncstore of integer registers.
297 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
304 // SETOEQ and SETUNE require checking two conditions.
305 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
312 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
314 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
315 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
316 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
318 if (Subtarget->is64Bit()) {
319 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
320 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
321 } else if (!TM.Options.UseSoftFloat) {
322 // We have an algorithm for SSE2->double, and we turn this into a
323 // 64-bit FILD followed by conditional FADD for other targets.
324 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
325 // We have an algorithm for SSE2, and we turn this into a 64-bit
326 // FILD for other targets.
327 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
330 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
332 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
333 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
335 if (!TM.Options.UseSoftFloat) {
336 // SSE has no i16 to fp conversion, only i32
337 if (X86ScalarSSEf32) {
338 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
339 // f32 and f64 cases are Legal, f80 case is not
340 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
342 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
343 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
346 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
347 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
350 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
351 // are Legal, f80 is custom lowered.
352 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
353 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
355 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
357 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
358 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
360 if (X86ScalarSSEf32) {
361 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
362 // f32 and f64 cases are Legal, f80 case is not
363 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
365 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
366 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
369 // Handle FP_TO_UINT by promoting the destination to a larger signed
371 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
372 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
373 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
375 if (Subtarget->is64Bit()) {
376 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
377 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
378 } else if (!TM.Options.UseSoftFloat) {
379 // Since AVX is a superset of SSE3, only check for SSE here.
380 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381 // Expand FP_TO_UINT into a select.
382 // FIXME: We would like to use a Custom expander here eventually to do
383 // the optimal thing for SSE vs. the default expansion in the legalizer.
384 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
386 // With SSE3 we can use fisttpll to convert to a signed i64; without
387 // SSE, we're stuck with a fistpll.
388 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
391 if (isTargetFTOL()) {
392 // Use the _ftol2 runtime function, which has a pseudo-instruction
393 // to handle its weird calling convention.
394 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
397 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398 if (!X86ScalarSSEf64) {
399 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
400 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
401 if (Subtarget->is64Bit()) {
402 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
403 // Without SSE, i64->f64 goes through memory.
404 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
408 // Scalar integer divide and remainder are lowered to use operations that
409 // produce two results, to match the available instructions. This exposes
410 // the two-result form to trivial CSE, which is able to combine x/y and x%y
411 // into a single instruction.
413 // Scalar integer multiply-high is also lowered to use two-result
414 // operations, to match the available instructions. However, plain multiply
415 // (low) operations are left as Legal, as there are single-result
416 // instructions for this in x86. Using the two-result multiply instructions
417 // when both high and low results are needed must be arranged by dagcombine.
418 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
420 setOperationAction(ISD::MULHS, VT, Expand);
421 setOperationAction(ISD::MULHU, VT, Expand);
422 setOperationAction(ISD::SDIV, VT, Expand);
423 setOperationAction(ISD::UDIV, VT, Expand);
424 setOperationAction(ISD::SREM, VT, Expand);
425 setOperationAction(ISD::UREM, VT, Expand);
427 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428 setOperationAction(ISD::ADDC, VT, Custom);
429 setOperationAction(ISD::ADDE, VT, Custom);
430 setOperationAction(ISD::SUBC, VT, Custom);
431 setOperationAction(ISD::SUBE, VT, Custom);
434 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
435 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
436 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
437 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
438 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
439 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
443 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
444 if (Subtarget->is64Bit())
445 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
449 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
450 setOperationAction(ISD::FREM , MVT::f32 , Expand);
451 setOperationAction(ISD::FREM , MVT::f64 , Expand);
452 setOperationAction(ISD::FREM , MVT::f80 , Expand);
453 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
455 // Promote the i8 variants and force them on up to i32 which has a shorter
457 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
458 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
459 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
460 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
461 if (Subtarget->hasBMI()) {
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
464 if (Subtarget->is64Bit())
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
467 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
468 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
469 if (Subtarget->is64Bit())
470 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
473 if (Subtarget->hasLZCNT()) {
474 // When promoting the i8 variants, force them to i32 for a shorter
476 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
477 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
478 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
482 if (Subtarget->is64Bit())
483 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
485 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
486 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
487 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
491 if (Subtarget->is64Bit()) {
492 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
493 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
497 if (Subtarget->hasPOPCNT()) {
498 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
500 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
501 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
502 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
507 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
509 if (!Subtarget->hasMOVBE())
510 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
512 // These should be promoted to a larger select which is supported.
513 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
514 // X86 wants to expand cmov itself.
515 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
516 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
517 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
518 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
519 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
521 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
522 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
524 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
525 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
527 if (Subtarget->is64Bit()) {
528 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
529 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
531 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
532 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
533 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
534 // support continuation, user-level threading, and etc.. As a result, no
535 // other SjLj exception interfaces are implemented and please don't build
536 // your own exception handling based on them.
537 // LLVM/Clang supports zero-cost DWARF exception handling.
538 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
539 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
542 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
543 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
544 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
545 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
546 if (Subtarget->is64Bit())
547 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
548 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
549 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
550 if (Subtarget->is64Bit()) {
551 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
552 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
553 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
554 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
555 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
557 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
558 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
559 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
560 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
561 if (Subtarget->is64Bit()) {
562 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
563 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
564 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
567 if (Subtarget->hasSSE1())
568 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
570 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
572 // Expand certain atomics
573 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
575 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
576 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
577 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
580 if (!Subtarget->is64Bit()) {
581 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
582 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
595 if (Subtarget->hasCmpxchg16b()) {
596 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
599 // FIXME - use subtarget debug flags
600 if (!Subtarget->isTargetDarwin() &&
601 !Subtarget->isTargetELF() &&
602 !Subtarget->isTargetCygMing()) {
603 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
606 if (Subtarget->is64Bit()) {
607 setExceptionPointerRegister(X86::RAX);
608 setExceptionSelectorRegister(X86::RDX);
610 setExceptionPointerRegister(X86::EAX);
611 setExceptionSelectorRegister(X86::EDX);
613 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
614 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
616 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
617 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
619 setOperationAction(ISD::TRAP, MVT::Other, Legal);
620 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
622 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
623 setOperationAction(ISD::VASTART , MVT::Other, Custom);
624 setOperationAction(ISD::VAEND , MVT::Other, Expand);
625 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
626 // TargetInfo::X86_64ABIBuiltinVaList
627 setOperationAction(ISD::VAARG , MVT::Other, Custom);
628 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
630 // TargetInfo::CharPtrBuiltinVaList
631 setOperationAction(ISD::VAARG , MVT::Other, Expand);
632 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
635 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
636 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
638 if (Subtarget->isOSWindows() && !Subtarget->isTargetMacho())
639 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640 MVT::i64 : MVT::i32, Custom);
641 else if (TM.Options.EnableSegmentedStacks)
642 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
643 MVT::i64 : MVT::i32, Custom);
645 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
646 MVT::i64 : MVT::i32, Expand);
648 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
649 // f32 and f64 use SSE.
650 // Set up the FP register classes.
651 addRegisterClass(MVT::f32, &X86::FR32RegClass);
652 addRegisterClass(MVT::f64, &X86::FR64RegClass);
654 // Use ANDPD to simulate FABS.
655 setOperationAction(ISD::FABS , MVT::f64, Custom);
656 setOperationAction(ISD::FABS , MVT::f32, Custom);
658 // Use XORP to simulate FNEG.
659 setOperationAction(ISD::FNEG , MVT::f64, Custom);
660 setOperationAction(ISD::FNEG , MVT::f32, Custom);
662 // Use ANDPD and ORPD to simulate FCOPYSIGN.
663 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
664 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
666 // Lower this to FGETSIGNx86 plus an AND.
667 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
668 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
670 // We don't support sin/cos/fmod
671 setOperationAction(ISD::FSIN , MVT::f64, Expand);
672 setOperationAction(ISD::FCOS , MVT::f64, Expand);
673 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
674 setOperationAction(ISD::FSIN , MVT::f32, Expand);
675 setOperationAction(ISD::FCOS , MVT::f32, Expand);
676 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
678 // Expand FP immediates into loads from the stack, except for the special
680 addLegalFPImmediate(APFloat(+0.0)); // xorpd
681 addLegalFPImmediate(APFloat(+0.0f)); // xorps
682 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
683 // Use SSE for f32, x87 for f64.
684 // Set up the FP register classes.
685 addRegisterClass(MVT::f32, &X86::FR32RegClass);
686 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
688 // Use ANDPS to simulate FABS.
689 setOperationAction(ISD::FABS , MVT::f32, Custom);
691 // Use XORP to simulate FNEG.
692 setOperationAction(ISD::FNEG , MVT::f32, Custom);
694 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
696 // Use ANDPS and ORPS to simulate FCOPYSIGN.
697 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
698 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
700 // We don't support sin/cos/fmod
701 setOperationAction(ISD::FSIN , MVT::f32, Expand);
702 setOperationAction(ISD::FCOS , MVT::f32, Expand);
703 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
705 // Special cases we handle for FP constants.
706 addLegalFPImmediate(APFloat(+0.0f)); // xorps
707 addLegalFPImmediate(APFloat(+0.0)); // FLD0
708 addLegalFPImmediate(APFloat(+1.0)); // FLD1
709 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
710 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
712 if (!TM.Options.UnsafeFPMath) {
713 setOperationAction(ISD::FSIN , MVT::f64, Expand);
714 setOperationAction(ISD::FCOS , MVT::f64, Expand);
715 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
717 } else if (!TM.Options.UseSoftFloat) {
718 // f32 and f64 in x87.
719 // Set up the FP register classes.
720 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
721 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
723 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
724 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
725 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
726 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
728 if (!TM.Options.UnsafeFPMath) {
729 setOperationAction(ISD::FSIN , MVT::f64, Expand);
730 setOperationAction(ISD::FSIN , MVT::f32, Expand);
731 setOperationAction(ISD::FCOS , MVT::f64, Expand);
732 setOperationAction(ISD::FCOS , MVT::f32, Expand);
733 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
734 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
736 addLegalFPImmediate(APFloat(+0.0)); // FLD0
737 addLegalFPImmediate(APFloat(+1.0)); // FLD1
738 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
739 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
740 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
741 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
742 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
743 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
746 // We don't support FMA.
747 setOperationAction(ISD::FMA, MVT::f64, Expand);
748 setOperationAction(ISD::FMA, MVT::f32, Expand);
750 // Long double always uses X87.
751 if (!TM.Options.UseSoftFloat) {
752 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
753 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
754 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
756 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
757 addLegalFPImmediate(TmpFlt); // FLD0
759 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
762 APFloat TmpFlt2(+1.0);
763 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
765 addLegalFPImmediate(TmpFlt2); // FLD1
766 TmpFlt2.changeSign();
767 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
770 if (!TM.Options.UnsafeFPMath) {
771 setOperationAction(ISD::FSIN , MVT::f80, Expand);
772 setOperationAction(ISD::FCOS , MVT::f80, Expand);
773 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
776 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
777 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
778 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
779 setOperationAction(ISD::FRINT, MVT::f80, Expand);
780 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
781 setOperationAction(ISD::FMA, MVT::f80, Expand);
784 // Always use a library call for pow.
785 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
786 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
787 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
789 setOperationAction(ISD::FLOG, MVT::f80, Expand);
790 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
791 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
792 setOperationAction(ISD::FEXP, MVT::f80, Expand);
793 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
795 // First set operation action for all vector types to either promote
796 // (for widening) or expand (for scalarization). Then we will selectively
797 // turn on ones that can be effectively codegen'd.
798 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
799 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
800 MVT VT = (MVT::SimpleValueType)i;
801 setOperationAction(ISD::ADD , VT, Expand);
802 setOperationAction(ISD::SUB , VT, Expand);
803 setOperationAction(ISD::FADD, VT, Expand);
804 setOperationAction(ISD::FNEG, VT, Expand);
805 setOperationAction(ISD::FSUB, VT, Expand);
806 setOperationAction(ISD::MUL , VT, Expand);
807 setOperationAction(ISD::FMUL, VT, Expand);
808 setOperationAction(ISD::SDIV, VT, Expand);
809 setOperationAction(ISD::UDIV, VT, Expand);
810 setOperationAction(ISD::FDIV, VT, Expand);
811 setOperationAction(ISD::SREM, VT, Expand);
812 setOperationAction(ISD::UREM, VT, Expand);
813 setOperationAction(ISD::LOAD, VT, Expand);
814 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
816 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
817 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
818 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
819 setOperationAction(ISD::FABS, VT, Expand);
820 setOperationAction(ISD::FSIN, VT, Expand);
821 setOperationAction(ISD::FSINCOS, VT, Expand);
822 setOperationAction(ISD::FCOS, VT, Expand);
823 setOperationAction(ISD::FSINCOS, VT, Expand);
824 setOperationAction(ISD::FREM, VT, Expand);
825 setOperationAction(ISD::FMA, VT, Expand);
826 setOperationAction(ISD::FPOWI, VT, Expand);
827 setOperationAction(ISD::FSQRT, VT, Expand);
828 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
829 setOperationAction(ISD::FFLOOR, VT, Expand);
830 setOperationAction(ISD::FCEIL, VT, Expand);
831 setOperationAction(ISD::FTRUNC, VT, Expand);
832 setOperationAction(ISD::FRINT, VT, Expand);
833 setOperationAction(ISD::FNEARBYINT, VT, Expand);
834 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
835 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
836 setOperationAction(ISD::SDIVREM, VT, Expand);
837 setOperationAction(ISD::UDIVREM, VT, Expand);
838 setOperationAction(ISD::FPOW, VT, Expand);
839 setOperationAction(ISD::CTPOP, VT, Expand);
840 setOperationAction(ISD::CTTZ, VT, Expand);
841 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
842 setOperationAction(ISD::CTLZ, VT, Expand);
843 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
844 setOperationAction(ISD::SHL, VT, Expand);
845 setOperationAction(ISD::SRA, VT, Expand);
846 setOperationAction(ISD::SRL, VT, Expand);
847 setOperationAction(ISD::ROTL, VT, Expand);
848 setOperationAction(ISD::ROTR, VT, Expand);
849 setOperationAction(ISD::BSWAP, VT, Expand);
850 setOperationAction(ISD::SETCC, VT, Expand);
851 setOperationAction(ISD::FLOG, VT, Expand);
852 setOperationAction(ISD::FLOG2, VT, Expand);
853 setOperationAction(ISD::FLOG10, VT, Expand);
854 setOperationAction(ISD::FEXP, VT, Expand);
855 setOperationAction(ISD::FEXP2, VT, Expand);
856 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
857 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
858 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
859 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
860 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
861 setOperationAction(ISD::TRUNCATE, VT, Expand);
862 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
863 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
864 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
865 setOperationAction(ISD::VSELECT, VT, Expand);
866 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
867 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
868 setTruncStoreAction(VT,
869 (MVT::SimpleValueType)InnerVT, Expand);
870 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
871 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
872 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
875 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
876 // with -msoft-float, disable use of MMX as well.
877 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
878 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
879 // No operations on x86mmx supported, everything uses intrinsics.
882 // MMX-sized vectors (other than x86mmx) are expected to be expanded
883 // into smaller operations.
884 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
885 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
886 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
887 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
888 setOperationAction(ISD::AND, MVT::v8i8, Expand);
889 setOperationAction(ISD::AND, MVT::v4i16, Expand);
890 setOperationAction(ISD::AND, MVT::v2i32, Expand);
891 setOperationAction(ISD::AND, MVT::v1i64, Expand);
892 setOperationAction(ISD::OR, MVT::v8i8, Expand);
893 setOperationAction(ISD::OR, MVT::v4i16, Expand);
894 setOperationAction(ISD::OR, MVT::v2i32, Expand);
895 setOperationAction(ISD::OR, MVT::v1i64, Expand);
896 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
897 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
898 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
899 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
900 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
901 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
902 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
903 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
904 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
905 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
906 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
907 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
908 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
909 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
910 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
911 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
912 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
914 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
915 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
917 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
918 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
919 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
920 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
921 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
922 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
923 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
924 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
925 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
926 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
927 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
928 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
931 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
932 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
934 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
935 // registers cannot be used even for integer operations.
936 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
937 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
938 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
939 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
941 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
942 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
943 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
944 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
945 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
946 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
947 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
948 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
949 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
950 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
951 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
952 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
953 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
954 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
955 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
956 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
957 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
958 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
960 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
961 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
962 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
963 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
965 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
966 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
971 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
972 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
973 MVT VT = (MVT::SimpleValueType)i;
974 // Do not attempt to custom lower non-power-of-2 vectors
975 if (!isPowerOf2_32(VT.getVectorNumElements()))
977 // Do not attempt to custom lower non-128-bit vectors
978 if (!VT.is128BitVector())
980 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
981 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
982 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
985 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
986 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
987 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
988 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
989 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
992 if (Subtarget->is64Bit()) {
993 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
994 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
997 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
998 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
999 MVT VT = (MVT::SimpleValueType)i;
1001 // Do not attempt to promote non-128-bit vectors
1002 if (!VT.is128BitVector())
1005 setOperationAction(ISD::AND, VT, Promote);
1006 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1007 setOperationAction(ISD::OR, VT, Promote);
1008 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1009 setOperationAction(ISD::XOR, VT, Promote);
1010 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1011 setOperationAction(ISD::LOAD, VT, Promote);
1012 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1013 setOperationAction(ISD::SELECT, VT, Promote);
1014 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1017 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1019 // Custom lower v2i64 and v2f64 selects.
1020 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1021 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1022 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1023 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1025 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1026 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1028 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1029 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1030 // As there is no 64-bit GPR available, we need build a special custom
1031 // sequence to convert from v2i32 to v2f32.
1032 if (!Subtarget->is64Bit())
1033 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1035 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1036 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1038 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1041 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1042 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1043 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1044 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1045 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1046 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1047 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1048 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1049 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1050 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1051 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1053 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1054 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1055 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1056 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1057 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1058 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1059 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1060 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1061 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1062 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1064 // FIXME: Do we need to handle scalar-to-vector here?
1065 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1068 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1069 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1073 // i8 and i16 vectors are custom , because the source register and source
1074 // source memory operand types are not the same width. f32 vectors are
1075 // custom since the immediate controlling the insert encodes additional
1077 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1078 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1079 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1080 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1082 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1083 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1084 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1085 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1087 // FIXME: these should be Legal but thats only for the case where
1088 // the index is constant. For now custom expand to deal with that.
1089 if (Subtarget->is64Bit()) {
1090 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1091 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1095 if (Subtarget->hasSSE2()) {
1096 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1097 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1099 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1100 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1102 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1103 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1105 // In the customized shift lowering, the legal cases in AVX2 will be
1107 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1108 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1110 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1111 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1113 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1115 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1116 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1119 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1120 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1122 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1123 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1124 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1125 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1127 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1128 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1129 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1131 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1140 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1142 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1144 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1153 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1154 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1155 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1157 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1158 // even though v8i16 is a legal type.
1159 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1160 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1161 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1163 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1164 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1165 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1167 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1168 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1170 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1172 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1176 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1183 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1184 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1185 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1186 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1188 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1189 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1190 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1192 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1193 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1194 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1195 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1197 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1198 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1199 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1200 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1201 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1202 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1203 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1204 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1205 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1206 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1207 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1208 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1210 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1211 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1212 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1213 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1214 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1215 setOperationAction(ISD::FMA, MVT::f32, Legal);
1216 setOperationAction(ISD::FMA, MVT::f64, Legal);
1219 if (Subtarget->hasInt256()) {
1220 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1221 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1222 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1223 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1225 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1226 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1227 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1228 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1230 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1231 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1232 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1233 // Don't lower v32i8 because there is no 128-bit byte mul
1235 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1237 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1239 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1240 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1241 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1242 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1244 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1245 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1246 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1247 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1249 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1250 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1251 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1252 // Don't lower v32i8 because there is no 128-bit byte mul
1255 // In the customized shift lowering, the legal cases in AVX2 will be
1257 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1258 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1260 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1261 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1263 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1265 // Custom lower several nodes for 256-bit types.
1266 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1267 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1268 MVT VT = (MVT::SimpleValueType)i;
1270 // Extract subvector is special because the value type
1271 // (result) is 128-bit but the source is 256-bit wide.
1272 if (VT.is128BitVector())
1273 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1275 // Do not attempt to custom lower other non-256-bit vectors
1276 if (!VT.is256BitVector())
1279 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1280 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1281 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1282 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1283 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1284 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1285 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1288 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1289 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1290 MVT VT = (MVT::SimpleValueType)i;
1292 // Do not attempt to promote non-256-bit vectors
1293 if (!VT.is256BitVector())
1296 setOperationAction(ISD::AND, VT, Promote);
1297 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1298 setOperationAction(ISD::OR, VT, Promote);
1299 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1300 setOperationAction(ISD::XOR, VT, Promote);
1301 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1302 setOperationAction(ISD::LOAD, VT, Promote);
1303 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1304 setOperationAction(ISD::SELECT, VT, Promote);
1305 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1309 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1310 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1311 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1312 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1313 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1315 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1316 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1317 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1319 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1320 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1321 setOperationAction(ISD::XOR, MVT::i1, Legal);
1322 setOperationAction(ISD::OR, MVT::i1, Legal);
1323 setOperationAction(ISD::AND, MVT::i1, Legal);
1324 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1325 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1326 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1327 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1328 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1329 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1331 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1332 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1333 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1334 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1335 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1336 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1338 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1340 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1341 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1342 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1343 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1344 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1345 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1346 setOperationAction(ISD::SDIV, MVT::v16i32, Custom);
1348 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1349 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1350 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1351 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1352 if (Subtarget->is64Bit()) {
1353 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1354 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1355 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1356 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1358 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1359 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1360 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1361 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1362 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1363 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1364 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1365 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1367 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1368 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1369 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1372 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1373 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1374 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1375 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1376 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1377 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1378 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1379 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1381 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1383 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1384 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1386 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1388 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1389 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1391 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1393 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1395 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1396 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1397 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1398 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1399 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1401 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1402 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1404 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1405 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1407 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1409 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1410 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1412 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1413 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1415 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1416 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1418 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1419 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1420 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1421 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1422 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1423 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1425 // Custom lower several nodes.
1426 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1427 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1428 MVT VT = (MVT::SimpleValueType)i;
1430 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1431 // Extract subvector is special because the value type
1432 // (result) is 256/128-bit but the source is 512-bit wide.
1433 if (VT.is128BitVector() || VT.is256BitVector())
1434 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1436 if (VT.getVectorElementType() == MVT::i1)
1437 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1439 // Do not attempt to custom lower other non-512-bit vectors
1440 if (!VT.is512BitVector())
1443 if ( EltSize >= 32) {
1444 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1445 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1446 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1447 setOperationAction(ISD::VSELECT, VT, Legal);
1448 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1449 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1450 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1453 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1454 MVT VT = (MVT::SimpleValueType)i;
1456 // Do not attempt to promote non-256-bit vectors
1457 if (!VT.is512BitVector())
1460 setOperationAction(ISD::SELECT, VT, Promote);
1461 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1465 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1466 // of this type with custom code.
1467 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1468 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1469 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1473 // We want to custom lower some of our intrinsics.
1474 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1475 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1476 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1478 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1479 // handle type legalization for these operations here.
1481 // FIXME: We really should do custom legalization for addition and
1482 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1483 // than generic legalization for 64-bit multiplication-with-overflow, though.
1484 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1485 // Add/Sub/Mul with overflow operations are custom lowered.
1487 setOperationAction(ISD::SADDO, VT, Custom);
1488 setOperationAction(ISD::UADDO, VT, Custom);
1489 setOperationAction(ISD::SSUBO, VT, Custom);
1490 setOperationAction(ISD::USUBO, VT, Custom);
1491 setOperationAction(ISD::SMULO, VT, Custom);
1492 setOperationAction(ISD::UMULO, VT, Custom);
1495 // There are no 8-bit 3-address imul/mul instructions
1496 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1497 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1499 if (!Subtarget->is64Bit()) {
1500 // These libcalls are not available in 32-bit.
1501 setLibcallName(RTLIB::SHL_I128, 0);
1502 setLibcallName(RTLIB::SRL_I128, 0);
1503 setLibcallName(RTLIB::SRA_I128, 0);
1506 // Combine sin / cos into one node or libcall if possible.
1507 if (Subtarget->hasSinCos()) {
1508 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1509 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1510 if (Subtarget->isTargetDarwin()) {
1511 // For MacOSX, we don't want to the normal expansion of a libcall to
1512 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1514 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1515 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1519 // We have target-specific dag combine patterns for the following nodes:
1520 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1521 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1522 setTargetDAGCombine(ISD::VSELECT);
1523 setTargetDAGCombine(ISD::SELECT);
1524 setTargetDAGCombine(ISD::SHL);
1525 setTargetDAGCombine(ISD::SRA);
1526 setTargetDAGCombine(ISD::SRL);
1527 setTargetDAGCombine(ISD::OR);
1528 setTargetDAGCombine(ISD::AND);
1529 setTargetDAGCombine(ISD::ADD);
1530 setTargetDAGCombine(ISD::FADD);
1531 setTargetDAGCombine(ISD::FSUB);
1532 setTargetDAGCombine(ISD::FMA);
1533 setTargetDAGCombine(ISD::SUB);
1534 setTargetDAGCombine(ISD::LOAD);
1535 setTargetDAGCombine(ISD::STORE);
1536 setTargetDAGCombine(ISD::ZERO_EXTEND);
1537 setTargetDAGCombine(ISD::ANY_EXTEND);
1538 setTargetDAGCombine(ISD::SIGN_EXTEND);
1539 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1540 setTargetDAGCombine(ISD::TRUNCATE);
1541 setTargetDAGCombine(ISD::SINT_TO_FP);
1542 setTargetDAGCombine(ISD::SETCC);
1543 if (Subtarget->is64Bit())
1544 setTargetDAGCombine(ISD::MUL);
1545 setTargetDAGCombine(ISD::XOR);
1547 computeRegisterProperties();
1549 // On Darwin, -Os means optimize for size without hurting performance,
1550 // do not reduce the limit.
1551 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1552 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1553 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1554 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1555 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1556 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1557 setPrefLoopAlignment(4); // 2^4 bytes.
1559 // Predictable cmov don't hurt on atom because it's in-order.
1560 PredictableSelectIsExpensive = !Subtarget->isAtom();
1562 setPrefFunctionAlignment(4); // 2^4 bytes.
1565 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1567 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1569 if (Subtarget->hasAVX512())
1570 switch(VT.getVectorNumElements()) {
1571 case 8: return MVT::v8i1;
1572 case 16: return MVT::v16i1;
1575 return VT.changeVectorElementTypeToInteger();
1578 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1579 /// the desired ByVal argument alignment.
1580 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1583 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1584 if (VTy->getBitWidth() == 128)
1586 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1587 unsigned EltAlign = 0;
1588 getMaxByValAlign(ATy->getElementType(), EltAlign);
1589 if (EltAlign > MaxAlign)
1590 MaxAlign = EltAlign;
1591 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1592 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1593 unsigned EltAlign = 0;
1594 getMaxByValAlign(STy->getElementType(i), EltAlign);
1595 if (EltAlign > MaxAlign)
1596 MaxAlign = EltAlign;
1603 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1604 /// function arguments in the caller parameter area. For X86, aggregates
1605 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1606 /// are at 4-byte boundaries.
1607 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1608 if (Subtarget->is64Bit()) {
1609 // Max of 8 and alignment of type.
1610 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1617 if (Subtarget->hasSSE1())
1618 getMaxByValAlign(Ty, Align);
1622 /// getOptimalMemOpType - Returns the target specific optimal type for load
1623 /// and store operations as a result of memset, memcpy, and memmove
1624 /// lowering. If DstAlign is zero that means it's safe to destination
1625 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1626 /// means there isn't a need to check it against alignment requirement,
1627 /// probably because the source does not need to be loaded. If 'IsMemset' is
1628 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1629 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1630 /// source is constant so it does not need to be loaded.
1631 /// It returns EVT::Other if the type should be determined using generic
1632 /// target-independent logic.
1634 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1635 unsigned DstAlign, unsigned SrcAlign,
1636 bool IsMemset, bool ZeroMemset,
1638 MachineFunction &MF) const {
1639 const Function *F = MF.getFunction();
1640 if ((!IsMemset || ZeroMemset) &&
1641 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1642 Attribute::NoImplicitFloat)) {
1644 (Subtarget->isUnalignedMemAccessFast() ||
1645 ((DstAlign == 0 || DstAlign >= 16) &&
1646 (SrcAlign == 0 || SrcAlign >= 16)))) {
1648 if (Subtarget->hasInt256())
1650 if (Subtarget->hasFp256())
1653 if (Subtarget->hasSSE2())
1655 if (Subtarget->hasSSE1())
1657 } else if (!MemcpyStrSrc && Size >= 8 &&
1658 !Subtarget->is64Bit() &&
1659 Subtarget->hasSSE2()) {
1660 // Do not use f64 to lower memcpy if source is string constant. It's
1661 // better to use i32 to avoid the loads.
1665 if (Subtarget->is64Bit() && Size >= 8)
1670 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1672 return X86ScalarSSEf32;
1673 else if (VT == MVT::f64)
1674 return X86ScalarSSEf64;
1679 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1683 *Fast = Subtarget->isUnalignedMemAccessFast();
1687 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1688 /// current function. The returned value is a member of the
1689 /// MachineJumpTableInfo::JTEntryKind enum.
1690 unsigned X86TargetLowering::getJumpTableEncoding() const {
1691 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1693 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1694 Subtarget->isPICStyleGOT())
1695 return MachineJumpTableInfo::EK_Custom32;
1697 // Otherwise, use the normal jump table encoding heuristics.
1698 return TargetLowering::getJumpTableEncoding();
1702 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1703 const MachineBasicBlock *MBB,
1704 unsigned uid,MCContext &Ctx) const{
1705 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1706 Subtarget->isPICStyleGOT());
1707 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1709 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1710 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1713 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1715 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1716 SelectionDAG &DAG) const {
1717 if (!Subtarget->is64Bit())
1718 // This doesn't have SDLoc associated with it, but is not really the
1719 // same as a Register.
1720 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1724 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1725 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1727 const MCExpr *X86TargetLowering::
1728 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1729 MCContext &Ctx) const {
1730 // X86-64 uses RIP relative addressing based on the jump table label.
1731 if (Subtarget->isPICStyleRIPRel())
1732 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1734 // Otherwise, the reference is relative to the PIC base.
1735 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1738 // FIXME: Why this routine is here? Move to RegInfo!
1739 std::pair<const TargetRegisterClass*, uint8_t>
1740 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1741 const TargetRegisterClass *RRC = 0;
1743 switch (VT.SimpleTy) {
1745 return TargetLowering::findRepresentativeClass(VT);
1746 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1747 RRC = Subtarget->is64Bit() ?
1748 (const TargetRegisterClass*)&X86::GR64RegClass :
1749 (const TargetRegisterClass*)&X86::GR32RegClass;
1752 RRC = &X86::VR64RegClass;
1754 case MVT::f32: case MVT::f64:
1755 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1756 case MVT::v4f32: case MVT::v2f64:
1757 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1759 RRC = &X86::VR128RegClass;
1762 return std::make_pair(RRC, Cost);
1765 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1766 unsigned &Offset) const {
1767 if (!Subtarget->isTargetLinux())
1770 if (Subtarget->is64Bit()) {
1771 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1773 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1785 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1786 unsigned DestAS) const {
1787 assert(SrcAS != DestAS && "Expected different address spaces!");
1789 return SrcAS < 256 && DestAS < 256;
1792 //===----------------------------------------------------------------------===//
1793 // Return Value Calling Convention Implementation
1794 //===----------------------------------------------------------------------===//
1796 #include "X86GenCallingConv.inc"
1799 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1800 MachineFunction &MF, bool isVarArg,
1801 const SmallVectorImpl<ISD::OutputArg> &Outs,
1802 LLVMContext &Context) const {
1803 SmallVector<CCValAssign, 16> RVLocs;
1804 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1806 return CCInfo.CheckReturn(Outs, RetCC_X86);
1809 const uint16_t *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1810 static const uint16_t ScratchRegs[] = { X86::R11, 0 };
1815 X86TargetLowering::LowerReturn(SDValue Chain,
1816 CallingConv::ID CallConv, bool isVarArg,
1817 const SmallVectorImpl<ISD::OutputArg> &Outs,
1818 const SmallVectorImpl<SDValue> &OutVals,
1819 SDLoc dl, SelectionDAG &DAG) const {
1820 MachineFunction &MF = DAG.getMachineFunction();
1821 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1823 SmallVector<CCValAssign, 16> RVLocs;
1824 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1825 RVLocs, *DAG.getContext());
1826 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1829 SmallVector<SDValue, 6> RetOps;
1830 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1831 // Operand #1 = Bytes To Pop
1832 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1835 // Copy the result values into the output registers.
1836 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1837 CCValAssign &VA = RVLocs[i];
1838 assert(VA.isRegLoc() && "Can only return in registers!");
1839 SDValue ValToCopy = OutVals[i];
1840 EVT ValVT = ValToCopy.getValueType();
1842 // Promote values to the appropriate types
1843 if (VA.getLocInfo() == CCValAssign::SExt)
1844 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1845 else if (VA.getLocInfo() == CCValAssign::ZExt)
1846 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1847 else if (VA.getLocInfo() == CCValAssign::AExt)
1848 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1849 else if (VA.getLocInfo() == CCValAssign::BCvt)
1850 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1852 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1853 "Unexpected FP-extend for return value.");
1855 // If this is x86-64, and we disabled SSE, we can't return FP values,
1856 // or SSE or MMX vectors.
1857 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1858 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1859 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1860 report_fatal_error("SSE register return with SSE disabled");
1862 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1863 // llvm-gcc has never done it right and no one has noticed, so this
1864 // should be OK for now.
1865 if (ValVT == MVT::f64 &&
1866 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1867 report_fatal_error("SSE2 register return with SSE2 disabled");
1869 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1870 // the RET instruction and handled by the FP Stackifier.
1871 if (VA.getLocReg() == X86::ST0 ||
1872 VA.getLocReg() == X86::ST1) {
1873 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1874 // change the value to the FP stack register class.
1875 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1876 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1877 RetOps.push_back(ValToCopy);
1878 // Don't emit a copytoreg.
1882 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1883 // which is returned in RAX / RDX.
1884 if (Subtarget->is64Bit()) {
1885 if (ValVT == MVT::x86mmx) {
1886 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1887 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1888 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1890 // If we don't have SSE2 available, convert to v4f32 so the generated
1891 // register is legal.
1892 if (!Subtarget->hasSSE2())
1893 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1898 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1899 Flag = Chain.getValue(1);
1900 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1903 // The x86-64 ABIs require that for returning structs by value we copy
1904 // the sret argument into %rax/%eax (depending on ABI) for the return.
1905 // Win32 requires us to put the sret argument to %eax as well.
1906 // We saved the argument into a virtual register in the entry block,
1907 // so now we copy the value out and into %rax/%eax.
1908 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1909 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1910 MachineFunction &MF = DAG.getMachineFunction();
1911 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1912 unsigned Reg = FuncInfo->getSRetReturnReg();
1914 "SRetReturnReg should have been set in LowerFormalArguments().");
1915 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1918 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1919 X86::RAX : X86::EAX;
1920 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1921 Flag = Chain.getValue(1);
1923 // RAX/EAX now acts like a return value.
1924 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1927 RetOps[0] = Chain; // Update chain.
1929 // Add the flag if we have it.
1931 RetOps.push_back(Flag);
1933 return DAG.getNode(X86ISD::RET_FLAG, dl,
1934 MVT::Other, &RetOps[0], RetOps.size());
1937 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1938 if (N->getNumValues() != 1)
1940 if (!N->hasNUsesOfValue(1, 0))
1943 SDValue TCChain = Chain;
1944 SDNode *Copy = *N->use_begin();
1945 if (Copy->getOpcode() == ISD::CopyToReg) {
1946 // If the copy has a glue operand, we conservatively assume it isn't safe to
1947 // perform a tail call.
1948 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1950 TCChain = Copy->getOperand(0);
1951 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1954 bool HasRet = false;
1955 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1957 if (UI->getOpcode() != X86ISD::RET_FLAG)
1970 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1971 ISD::NodeType ExtendKind) const {
1973 // TODO: Is this also valid on 32-bit?
1974 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1975 ReturnMVT = MVT::i8;
1977 ReturnMVT = MVT::i32;
1979 MVT MinVT = getRegisterType(ReturnMVT);
1980 return VT.bitsLT(MinVT) ? MinVT : VT;
1983 /// LowerCallResult - Lower the result values of a call into the
1984 /// appropriate copies out of appropriate physical registers.
1987 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1988 CallingConv::ID CallConv, bool isVarArg,
1989 const SmallVectorImpl<ISD::InputArg> &Ins,
1990 SDLoc dl, SelectionDAG &DAG,
1991 SmallVectorImpl<SDValue> &InVals) const {
1993 // Assign locations to each value returned by this call.
1994 SmallVector<CCValAssign, 16> RVLocs;
1995 bool Is64Bit = Subtarget->is64Bit();
1996 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1997 getTargetMachine(), RVLocs, *DAG.getContext());
1998 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2000 // Copy all of the result registers out of their specified physreg.
2001 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2002 CCValAssign &VA = RVLocs[i];
2003 EVT CopyVT = VA.getValVT();
2005 // If this is x86-64, and we disabled SSE, we can't return FP values
2006 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2007 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2008 report_fatal_error("SSE register return with SSE disabled");
2013 // If this is a call to a function that returns an fp value on the floating
2014 // point stack, we must guarantee the value is popped from the stack, so
2015 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2016 // if the return value is not used. We use the FpPOP_RETVAL instruction
2018 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2019 // If we prefer to use the value in xmm registers, copy it out as f80 and
2020 // use a truncate to move it from fp stack reg to xmm reg.
2021 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2022 SDValue Ops[] = { Chain, InFlag };
2023 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2024 MVT::Other, MVT::Glue, Ops), 1);
2025 Val = Chain.getValue(0);
2027 // Round the f80 to the right size, which also moves it to the appropriate
2029 if (CopyVT != VA.getValVT())
2030 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2031 // This truncation won't change the value.
2032 DAG.getIntPtrConstant(1));
2034 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2035 CopyVT, InFlag).getValue(1);
2036 Val = Chain.getValue(0);
2038 InFlag = Chain.getValue(2);
2039 InVals.push_back(Val);
2045 //===----------------------------------------------------------------------===//
2046 // C & StdCall & Fast Calling Convention implementation
2047 //===----------------------------------------------------------------------===//
2048 // StdCall calling convention seems to be standard for many Windows' API
2049 // routines and around. It differs from C calling convention just a little:
2050 // callee should clean up the stack, not caller. Symbols should be also
2051 // decorated in some fancy way :) It doesn't support any vector arguments.
2052 // For info on fast calling convention see Fast Calling Convention (tail call)
2053 // implementation LowerX86_32FastCCCallTo.
2055 /// CallIsStructReturn - Determines whether a call uses struct return
2057 enum StructReturnType {
2062 static StructReturnType
2063 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2065 return NotStructReturn;
2067 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2068 if (!Flags.isSRet())
2069 return NotStructReturn;
2070 if (Flags.isInReg())
2071 return RegStructReturn;
2072 return StackStructReturn;
2075 /// ArgsAreStructReturn - Determines whether a function uses struct
2076 /// return semantics.
2077 static StructReturnType
2078 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2080 return NotStructReturn;
2082 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2083 if (!Flags.isSRet())
2084 return NotStructReturn;
2085 if (Flags.isInReg())
2086 return RegStructReturn;
2087 return StackStructReturn;
2090 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2091 /// by "Src" to address "Dst" with size and alignment information specified by
2092 /// the specific parameter attribute. The copy will be passed as a byval
2093 /// function parameter.
2095 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2096 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2098 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2100 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2101 /*isVolatile*/false, /*AlwaysInline=*/true,
2102 MachinePointerInfo(), MachinePointerInfo());
2105 /// IsTailCallConvention - Return true if the calling convention is one that
2106 /// supports tail call optimization.
2107 static bool IsTailCallConvention(CallingConv::ID CC) {
2108 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2109 CC == CallingConv::HiPE);
2112 /// \brief Return true if the calling convention is a C calling convention.
2113 static bool IsCCallConvention(CallingConv::ID CC) {
2114 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2115 CC == CallingConv::X86_64_SysV);
2118 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2119 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2123 CallingConv::ID CalleeCC = CS.getCallingConv();
2124 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2130 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2131 /// a tailcall target by changing its ABI.
2132 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2133 bool GuaranteedTailCallOpt) {
2134 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2138 X86TargetLowering::LowerMemArgument(SDValue Chain,
2139 CallingConv::ID CallConv,
2140 const SmallVectorImpl<ISD::InputArg> &Ins,
2141 SDLoc dl, SelectionDAG &DAG,
2142 const CCValAssign &VA,
2143 MachineFrameInfo *MFI,
2145 // Create the nodes corresponding to a load from this parameter slot.
2146 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2147 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2148 getTargetMachine().Options.GuaranteedTailCallOpt);
2149 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2152 // If value is passed by pointer we have address passed instead of the value
2154 if (VA.getLocInfo() == CCValAssign::Indirect)
2155 ValVT = VA.getLocVT();
2157 ValVT = VA.getValVT();
2159 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2160 // changed with more analysis.
2161 // In case of tail call optimization mark all arguments mutable. Since they
2162 // could be overwritten by lowering of arguments in case of a tail call.
2163 if (Flags.isByVal()) {
2164 unsigned Bytes = Flags.getByValSize();
2165 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2166 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2167 return DAG.getFrameIndex(FI, getPointerTy());
2169 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2170 VA.getLocMemOffset(), isImmutable);
2171 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2172 return DAG.getLoad(ValVT, dl, Chain, FIN,
2173 MachinePointerInfo::getFixedStack(FI),
2174 false, false, false, 0);
2179 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2180 CallingConv::ID CallConv,
2182 const SmallVectorImpl<ISD::InputArg> &Ins,
2185 SmallVectorImpl<SDValue> &InVals)
2187 MachineFunction &MF = DAG.getMachineFunction();
2188 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2190 const Function* Fn = MF.getFunction();
2191 if (Fn->hasExternalLinkage() &&
2192 Subtarget->isTargetCygMing() &&
2193 Fn->getName() == "main")
2194 FuncInfo->setForceFramePointer(true);
2196 MachineFrameInfo *MFI = MF.getFrameInfo();
2197 bool Is64Bit = Subtarget->is64Bit();
2198 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2200 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2201 "Var args not supported with calling convention fastcc, ghc or hipe");
2203 // Assign locations to all of the incoming arguments.
2204 SmallVector<CCValAssign, 16> ArgLocs;
2205 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2206 ArgLocs, *DAG.getContext());
2208 // Allocate shadow area for Win64
2210 CCInfo.AllocateStack(32, 8);
2212 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2214 unsigned LastVal = ~0U;
2216 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2217 CCValAssign &VA = ArgLocs[i];
2218 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2220 assert(VA.getValNo() != LastVal &&
2221 "Don't support value assigned to multiple locs yet");
2223 LastVal = VA.getValNo();
2225 if (VA.isRegLoc()) {
2226 EVT RegVT = VA.getLocVT();
2227 const TargetRegisterClass *RC;
2228 if (RegVT == MVT::i32)
2229 RC = &X86::GR32RegClass;
2230 else if (Is64Bit && RegVT == MVT::i64)
2231 RC = &X86::GR64RegClass;
2232 else if (RegVT == MVT::f32)
2233 RC = &X86::FR32RegClass;
2234 else if (RegVT == MVT::f64)
2235 RC = &X86::FR64RegClass;
2236 else if (RegVT.is512BitVector())
2237 RC = &X86::VR512RegClass;
2238 else if (RegVT.is256BitVector())
2239 RC = &X86::VR256RegClass;
2240 else if (RegVT.is128BitVector())
2241 RC = &X86::VR128RegClass;
2242 else if (RegVT == MVT::x86mmx)
2243 RC = &X86::VR64RegClass;
2244 else if (RegVT == MVT::i1)
2245 RC = &X86::VK1RegClass;
2246 else if (RegVT == MVT::v8i1)
2247 RC = &X86::VK8RegClass;
2248 else if (RegVT == MVT::v16i1)
2249 RC = &X86::VK16RegClass;
2251 llvm_unreachable("Unknown argument type!");
2253 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2254 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2256 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2257 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2259 if (VA.getLocInfo() == CCValAssign::SExt)
2260 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2261 DAG.getValueType(VA.getValVT()));
2262 else if (VA.getLocInfo() == CCValAssign::ZExt)
2263 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2264 DAG.getValueType(VA.getValVT()));
2265 else if (VA.getLocInfo() == CCValAssign::BCvt)
2266 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2268 if (VA.isExtInLoc()) {
2269 // Handle MMX values passed in XMM regs.
2270 if (RegVT.isVector())
2271 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2273 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2276 assert(VA.isMemLoc());
2277 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2280 // If value is passed via pointer - do a load.
2281 if (VA.getLocInfo() == CCValAssign::Indirect)
2282 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2283 MachinePointerInfo(), false, false, false, 0);
2285 InVals.push_back(ArgValue);
2288 // The x86-64 ABIs require that for returning structs by value we copy
2289 // the sret argument into %rax/%eax (depending on ABI) for the return.
2290 // Win32 requires us to put the sret argument to %eax as well.
2291 // Save the argument into a virtual register so that we can access it
2292 // from the return points.
2293 if (MF.getFunction()->hasStructRetAttr() &&
2294 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2295 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2296 unsigned Reg = FuncInfo->getSRetReturnReg();
2298 MVT PtrTy = getPointerTy();
2299 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2300 FuncInfo->setSRetReturnReg(Reg);
2302 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2303 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2306 unsigned StackSize = CCInfo.getNextStackOffset();
2307 // Align stack specially for tail calls.
2308 if (FuncIsMadeTailCallSafe(CallConv,
2309 MF.getTarget().Options.GuaranteedTailCallOpt))
2310 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2312 // If the function takes variable number of arguments, make a frame index for
2313 // the start of the first vararg value... for expansion of llvm.va_start.
2315 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2316 CallConv != CallingConv::X86_ThisCall)) {
2317 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2320 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2322 // FIXME: We should really autogenerate these arrays
2323 static const uint16_t GPR64ArgRegsWin64[] = {
2324 X86::RCX, X86::RDX, X86::R8, X86::R9
2326 static const uint16_t GPR64ArgRegs64Bit[] = {
2327 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2329 static const uint16_t XMMArgRegs64Bit[] = {
2330 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2331 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2333 const uint16_t *GPR64ArgRegs;
2334 unsigned NumXMMRegs = 0;
2337 // The XMM registers which might contain var arg parameters are shadowed
2338 // in their paired GPR. So we only need to save the GPR to their home
2340 TotalNumIntRegs = 4;
2341 GPR64ArgRegs = GPR64ArgRegsWin64;
2343 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2344 GPR64ArgRegs = GPR64ArgRegs64Bit;
2346 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2349 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2352 bool NoImplicitFloatOps = Fn->getAttributes().
2353 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2354 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2355 "SSE register cannot be used when SSE is disabled!");
2356 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2357 NoImplicitFloatOps) &&
2358 "SSE register cannot be used when SSE is disabled!");
2359 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2360 !Subtarget->hasSSE1())
2361 // Kernel mode asks for SSE to be disabled, so don't push them
2363 TotalNumXMMRegs = 0;
2366 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2367 // Get to the caller-allocated home save location. Add 8 to account
2368 // for the return address.
2369 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2370 FuncInfo->setRegSaveFrameIndex(
2371 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2372 // Fixup to set vararg frame on shadow area (4 x i64).
2374 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2376 // For X86-64, if there are vararg parameters that are passed via
2377 // registers, then we must store them to their spots on the stack so
2378 // they may be loaded by deferencing the result of va_next.
2379 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2380 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2381 FuncInfo->setRegSaveFrameIndex(
2382 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2386 // Store the integer parameter registers.
2387 SmallVector<SDValue, 8> MemOps;
2388 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2390 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2391 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2392 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2393 DAG.getIntPtrConstant(Offset));
2394 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2395 &X86::GR64RegClass);
2396 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2398 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2399 MachinePointerInfo::getFixedStack(
2400 FuncInfo->getRegSaveFrameIndex(), Offset),
2402 MemOps.push_back(Store);
2406 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2407 // Now store the XMM (fp + vector) parameter registers.
2408 SmallVector<SDValue, 11> SaveXMMOps;
2409 SaveXMMOps.push_back(Chain);
2411 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2412 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2413 SaveXMMOps.push_back(ALVal);
2415 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2416 FuncInfo->getRegSaveFrameIndex()));
2417 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2418 FuncInfo->getVarArgsFPOffset()));
2420 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2421 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2422 &X86::VR128RegClass);
2423 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2424 SaveXMMOps.push_back(Val);
2426 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2428 &SaveXMMOps[0], SaveXMMOps.size()));
2431 if (!MemOps.empty())
2432 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2433 &MemOps[0], MemOps.size());
2437 // Some CCs need callee pop.
2438 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2439 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2440 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2442 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2443 // If this is an sret function, the return should pop the hidden pointer.
2444 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2445 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2446 argsAreStructReturn(Ins) == StackStructReturn)
2447 FuncInfo->setBytesToPopOnReturn(4);
2451 // RegSaveFrameIndex is X86-64 only.
2452 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2453 if (CallConv == CallingConv::X86_FastCall ||
2454 CallConv == CallingConv::X86_ThisCall)
2455 // fastcc functions can't have varargs.
2456 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2459 FuncInfo->setArgumentStackSize(StackSize);
2465 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2466 SDValue StackPtr, SDValue Arg,
2467 SDLoc dl, SelectionDAG &DAG,
2468 const CCValAssign &VA,
2469 ISD::ArgFlagsTy Flags) const {
2470 unsigned LocMemOffset = VA.getLocMemOffset();
2471 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2472 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2473 if (Flags.isByVal())
2474 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2476 return DAG.getStore(Chain, dl, Arg, PtrOff,
2477 MachinePointerInfo::getStack(LocMemOffset),
2481 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2482 /// optimization is performed and it is required.
2484 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2485 SDValue &OutRetAddr, SDValue Chain,
2486 bool IsTailCall, bool Is64Bit,
2487 int FPDiff, SDLoc dl) const {
2488 // Adjust the Return address stack slot.
2489 EVT VT = getPointerTy();
2490 OutRetAddr = getReturnAddressFrameIndex(DAG);
2492 // Load the "old" Return address.
2493 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2494 false, false, false, 0);
2495 return SDValue(OutRetAddr.getNode(), 1);
2498 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2499 /// optimization is performed and it is required (FPDiff!=0).
2501 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2502 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2503 unsigned SlotSize, int FPDiff, SDLoc dl) {
2504 // Store the return address to the appropriate stack slot.
2505 if (!FPDiff) return Chain;
2506 // Calculate the new stack slot for the return address.
2507 int NewReturnAddrFI =
2508 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2510 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2511 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2512 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2518 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2519 SmallVectorImpl<SDValue> &InVals) const {
2520 SelectionDAG &DAG = CLI.DAG;
2522 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2523 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2524 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2525 SDValue Chain = CLI.Chain;
2526 SDValue Callee = CLI.Callee;
2527 CallingConv::ID CallConv = CLI.CallConv;
2528 bool &isTailCall = CLI.IsTailCall;
2529 bool isVarArg = CLI.IsVarArg;
2531 MachineFunction &MF = DAG.getMachineFunction();
2532 bool Is64Bit = Subtarget->is64Bit();
2533 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2534 StructReturnType SR = callIsStructReturn(Outs);
2535 bool IsSibcall = false;
2537 if (MF.getTarget().Options.DisableTailCalls)
2541 // Check if it's really possible to do a tail call.
2542 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2543 isVarArg, SR != NotStructReturn,
2544 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2545 Outs, OutVals, Ins, DAG);
2547 // Sibcalls are automatically detected tailcalls which do not require
2549 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2556 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2557 "Var args not supported with calling convention fastcc, ghc or hipe");
2559 // Analyze operands of the call, assigning locations to each operand.
2560 SmallVector<CCValAssign, 16> ArgLocs;
2561 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2562 ArgLocs, *DAG.getContext());
2564 // Allocate shadow area for Win64
2566 CCInfo.AllocateStack(32, 8);
2568 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2570 // Get a count of how many bytes are to be pushed on the stack.
2571 unsigned NumBytes = CCInfo.getNextStackOffset();
2573 // This is a sibcall. The memory operands are available in caller's
2574 // own caller's stack.
2576 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2577 IsTailCallConvention(CallConv))
2578 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2581 if (isTailCall && !IsSibcall) {
2582 // Lower arguments at fp - stackoffset + fpdiff.
2583 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2584 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2586 FPDiff = NumBytesCallerPushed - NumBytes;
2588 // Set the delta of movement of the returnaddr stackslot.
2589 // But only set if delta is greater than previous delta.
2590 if (FPDiff < X86Info->getTCReturnAddrDelta())
2591 X86Info->setTCReturnAddrDelta(FPDiff);
2594 unsigned NumBytesToPush = NumBytes;
2595 unsigned NumBytesToPop = NumBytes;
2597 // If we have an inalloca argument, all stack space has already been allocated
2598 // for us and be right at the top of the stack. We don't support multiple
2599 // arguments passed in memory when using inalloca.
2600 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2602 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2603 "an inalloca argument must be the only memory argument");
2607 Chain = DAG.getCALLSEQ_START(
2608 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2610 SDValue RetAddrFrIdx;
2611 // Load return address for tail calls.
2612 if (isTailCall && FPDiff)
2613 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2614 Is64Bit, FPDiff, dl);
2616 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2617 SmallVector<SDValue, 8> MemOpChains;
2620 // Walk the register/memloc assignments, inserting copies/loads. In the case
2621 // of tail call optimization arguments are handle later.
2622 const X86RegisterInfo *RegInfo =
2623 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2624 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2625 // Skip inalloca arguments, they have already been written.
2626 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2627 if (Flags.isInAlloca())
2630 CCValAssign &VA = ArgLocs[i];
2631 EVT RegVT = VA.getLocVT();
2632 SDValue Arg = OutVals[i];
2633 bool isByVal = Flags.isByVal();
2635 // Promote the value if needed.
2636 switch (VA.getLocInfo()) {
2637 default: llvm_unreachable("Unknown loc info!");
2638 case CCValAssign::Full: break;
2639 case CCValAssign::SExt:
2640 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2642 case CCValAssign::ZExt:
2643 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2645 case CCValAssign::AExt:
2646 if (RegVT.is128BitVector()) {
2647 // Special case: passing MMX values in XMM registers.
2648 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2649 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2650 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2652 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2654 case CCValAssign::BCvt:
2655 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2657 case CCValAssign::Indirect: {
2658 // Store the argument.
2659 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2660 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2661 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2662 MachinePointerInfo::getFixedStack(FI),
2669 if (VA.isRegLoc()) {
2670 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2671 if (isVarArg && IsWin64) {
2672 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2673 // shadow reg if callee is a varargs function.
2674 unsigned ShadowReg = 0;
2675 switch (VA.getLocReg()) {
2676 case X86::XMM0: ShadowReg = X86::RCX; break;
2677 case X86::XMM1: ShadowReg = X86::RDX; break;
2678 case X86::XMM2: ShadowReg = X86::R8; break;
2679 case X86::XMM3: ShadowReg = X86::R9; break;
2682 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2684 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2685 assert(VA.isMemLoc());
2686 if (StackPtr.getNode() == 0)
2687 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2689 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2690 dl, DAG, VA, Flags));
2694 if (!MemOpChains.empty())
2695 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2696 &MemOpChains[0], MemOpChains.size());
2698 if (Subtarget->isPICStyleGOT()) {
2699 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2702 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2703 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2705 // If we are tail calling and generating PIC/GOT style code load the
2706 // address of the callee into ECX. The value in ecx is used as target of
2707 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2708 // for tail calls on PIC/GOT architectures. Normally we would just put the
2709 // address of GOT into ebx and then call target@PLT. But for tail calls
2710 // ebx would be restored (since ebx is callee saved) before jumping to the
2713 // Note: The actual moving to ECX is done further down.
2714 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2715 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2716 !G->getGlobal()->hasProtectedVisibility())
2717 Callee = LowerGlobalAddress(Callee, DAG);
2718 else if (isa<ExternalSymbolSDNode>(Callee))
2719 Callee = LowerExternalSymbol(Callee, DAG);
2723 if (Is64Bit && isVarArg && !IsWin64) {
2724 // From AMD64 ABI document:
2725 // For calls that may call functions that use varargs or stdargs
2726 // (prototype-less calls or calls to functions containing ellipsis (...) in
2727 // the declaration) %al is used as hidden argument to specify the number
2728 // of SSE registers used. The contents of %al do not need to match exactly
2729 // the number of registers, but must be an ubound on the number of SSE
2730 // registers used and is in the range 0 - 8 inclusive.
2732 // Count the number of XMM registers allocated.
2733 static const uint16_t XMMArgRegs[] = {
2734 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2735 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2737 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2738 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2739 && "SSE registers cannot be used when SSE is disabled");
2741 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2742 DAG.getConstant(NumXMMRegs, MVT::i8)));
2745 // For tail calls lower the arguments to the 'real' stack slot.
2747 // Force all the incoming stack arguments to be loaded from the stack
2748 // before any new outgoing arguments are stored to the stack, because the
2749 // outgoing stack slots may alias the incoming argument stack slots, and
2750 // the alias isn't otherwise explicit. This is slightly more conservative
2751 // than necessary, because it means that each store effectively depends
2752 // on every argument instead of just those arguments it would clobber.
2753 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2755 SmallVector<SDValue, 8> MemOpChains2;
2758 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2759 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2760 CCValAssign &VA = ArgLocs[i];
2763 assert(VA.isMemLoc());
2764 SDValue Arg = OutVals[i];
2765 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2766 // Create frame index.
2767 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2768 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2769 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2770 FIN = DAG.getFrameIndex(FI, getPointerTy());
2772 if (Flags.isByVal()) {
2773 // Copy relative to framepointer.
2774 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2775 if (StackPtr.getNode() == 0)
2776 StackPtr = DAG.getCopyFromReg(Chain, dl,
2777 RegInfo->getStackRegister(),
2779 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2781 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2785 // Store relative to framepointer.
2786 MemOpChains2.push_back(
2787 DAG.getStore(ArgChain, dl, Arg, FIN,
2788 MachinePointerInfo::getFixedStack(FI),
2794 if (!MemOpChains2.empty())
2795 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2796 &MemOpChains2[0], MemOpChains2.size());
2798 // Store the return address to the appropriate stack slot.
2799 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2800 getPointerTy(), RegInfo->getSlotSize(),
2804 // Build a sequence of copy-to-reg nodes chained together with token chain
2805 // and flag operands which copy the outgoing args into registers.
2807 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2808 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2809 RegsToPass[i].second, InFlag);
2810 InFlag = Chain.getValue(1);
2813 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2814 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2815 // In the 64-bit large code model, we have to make all calls
2816 // through a register, since the call instruction's 32-bit
2817 // pc-relative offset may not be large enough to hold the whole
2819 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2820 // If the callee is a GlobalAddress node (quite common, every direct call
2821 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2824 // We should use extra load for direct calls to dllimported functions in
2826 const GlobalValue *GV = G->getGlobal();
2827 if (!GV->hasDLLImportStorageClass()) {
2828 unsigned char OpFlags = 0;
2829 bool ExtraLoad = false;
2830 unsigned WrapperKind = ISD::DELETED_NODE;
2832 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2833 // external symbols most go through the PLT in PIC mode. If the symbol
2834 // has hidden or protected visibility, or if it is static or local, then
2835 // we don't need to use the PLT - we can directly call it.
2836 if (Subtarget->isTargetELF() &&
2837 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2838 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2839 OpFlags = X86II::MO_PLT;
2840 } else if (Subtarget->isPICStyleStubAny() &&
2841 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2842 (!Subtarget->getTargetTriple().isMacOSX() ||
2843 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2844 // PC-relative references to external symbols should go through $stub,
2845 // unless we're building with the leopard linker or later, which
2846 // automatically synthesizes these stubs.
2847 OpFlags = X86II::MO_DARWIN_STUB;
2848 } else if (Subtarget->isPICStyleRIPRel() &&
2849 isa<Function>(GV) &&
2850 cast<Function>(GV)->getAttributes().
2851 hasAttribute(AttributeSet::FunctionIndex,
2852 Attribute::NonLazyBind)) {
2853 // If the function is marked as non-lazy, generate an indirect call
2854 // which loads from the GOT directly. This avoids runtime overhead
2855 // at the cost of eager binding (and one extra byte of encoding).
2856 OpFlags = X86II::MO_GOTPCREL;
2857 WrapperKind = X86ISD::WrapperRIP;
2861 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2862 G->getOffset(), OpFlags);
2864 // Add a wrapper if needed.
2865 if (WrapperKind != ISD::DELETED_NODE)
2866 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2867 // Add extra indirection if needed.
2869 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2870 MachinePointerInfo::getGOT(),
2871 false, false, false, 0);
2873 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2874 unsigned char OpFlags = 0;
2876 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2877 // external symbols should go through the PLT.
2878 if (Subtarget->isTargetELF() &&
2879 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2880 OpFlags = X86II::MO_PLT;
2881 } else if (Subtarget->isPICStyleStubAny() &&
2882 (!Subtarget->getTargetTriple().isMacOSX() ||
2883 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2884 // PC-relative references to external symbols should go through $stub,
2885 // unless we're building with the leopard linker or later, which
2886 // automatically synthesizes these stubs.
2887 OpFlags = X86II::MO_DARWIN_STUB;
2890 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2894 // Returns a chain & a flag for retval copy to use.
2895 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2896 SmallVector<SDValue, 8> Ops;
2898 if (!IsSibcall && isTailCall) {
2899 Chain = DAG.getCALLSEQ_END(Chain,
2900 DAG.getIntPtrConstant(NumBytesToPop, true),
2901 DAG.getIntPtrConstant(0, true), InFlag, dl);
2902 InFlag = Chain.getValue(1);
2905 Ops.push_back(Chain);
2906 Ops.push_back(Callee);
2909 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2911 // Add argument registers to the end of the list so that they are known live
2913 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2914 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2915 RegsToPass[i].second.getValueType()));
2917 // Add a register mask operand representing the call-preserved registers.
2918 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2919 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2920 assert(Mask && "Missing call preserved mask for calling convention");
2921 Ops.push_back(DAG.getRegisterMask(Mask));
2923 if (InFlag.getNode())
2924 Ops.push_back(InFlag);
2928 //// If this is the first return lowered for this function, add the regs
2929 //// to the liveout set for the function.
2930 // This isn't right, although it's probably harmless on x86; liveouts
2931 // should be computed from returns not tail calls. Consider a void
2932 // function making a tail call to a function returning int.
2933 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2936 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2937 InFlag = Chain.getValue(1);
2939 // Create the CALLSEQ_END node.
2940 unsigned NumBytesForCalleeToPop;
2941 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2942 getTargetMachine().Options.GuaranteedTailCallOpt))
2943 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2944 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2945 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2946 SR == StackStructReturn)
2947 // If this is a call to a struct-return function, the callee
2948 // pops the hidden struct pointer, so we have to push it back.
2949 // This is common for Darwin/X86, Linux & Mingw32 targets.
2950 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2951 NumBytesForCalleeToPop = 4;
2953 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2955 // Returns a flag for retval copy to use.
2957 Chain = DAG.getCALLSEQ_END(Chain,
2958 DAG.getIntPtrConstant(NumBytesToPop, true),
2959 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2962 InFlag = Chain.getValue(1);
2965 // Handle result values, copying them out of physregs into vregs that we
2967 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2968 Ins, dl, DAG, InVals);
2971 //===----------------------------------------------------------------------===//
2972 // Fast Calling Convention (tail call) implementation
2973 //===----------------------------------------------------------------------===//
2975 // Like std call, callee cleans arguments, convention except that ECX is
2976 // reserved for storing the tail called function address. Only 2 registers are
2977 // free for argument passing (inreg). Tail call optimization is performed
2979 // * tailcallopt is enabled
2980 // * caller/callee are fastcc
2981 // On X86_64 architecture with GOT-style position independent code only local
2982 // (within module) calls are supported at the moment.
2983 // To keep the stack aligned according to platform abi the function
2984 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2985 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2986 // If a tail called function callee has more arguments than the caller the
2987 // caller needs to make sure that there is room to move the RETADDR to. This is
2988 // achieved by reserving an area the size of the argument delta right after the
2989 // original REtADDR, but before the saved framepointer or the spilled registers
2990 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3002 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3003 /// for a 16 byte align requirement.
3005 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3006 SelectionDAG& DAG) const {
3007 MachineFunction &MF = DAG.getMachineFunction();
3008 const TargetMachine &TM = MF.getTarget();
3009 const X86RegisterInfo *RegInfo =
3010 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3011 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3012 unsigned StackAlignment = TFI.getStackAlignment();
3013 uint64_t AlignMask = StackAlignment - 1;
3014 int64_t Offset = StackSize;
3015 unsigned SlotSize = RegInfo->getSlotSize();
3016 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3017 // Number smaller than 12 so just add the difference.
3018 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3020 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3021 Offset = ((~AlignMask) & Offset) + StackAlignment +
3022 (StackAlignment-SlotSize);
3027 /// MatchingStackOffset - Return true if the given stack call argument is
3028 /// already available in the same position (relatively) of the caller's
3029 /// incoming argument stack.
3031 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3032 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3033 const X86InstrInfo *TII) {
3034 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3036 if (Arg.getOpcode() == ISD::CopyFromReg) {
3037 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3038 if (!TargetRegisterInfo::isVirtualRegister(VR))
3040 MachineInstr *Def = MRI->getVRegDef(VR);
3043 if (!Flags.isByVal()) {
3044 if (!TII->isLoadFromStackSlot(Def, FI))
3047 unsigned Opcode = Def->getOpcode();
3048 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3049 Def->getOperand(1).isFI()) {
3050 FI = Def->getOperand(1).getIndex();
3051 Bytes = Flags.getByValSize();
3055 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3056 if (Flags.isByVal())
3057 // ByVal argument is passed in as a pointer but it's now being
3058 // dereferenced. e.g.
3059 // define @foo(%struct.X* %A) {
3060 // tail call @bar(%struct.X* byval %A)
3063 SDValue Ptr = Ld->getBasePtr();
3064 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3067 FI = FINode->getIndex();
3068 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3069 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3070 FI = FINode->getIndex();
3071 Bytes = Flags.getByValSize();
3075 assert(FI != INT_MAX);
3076 if (!MFI->isFixedObjectIndex(FI))
3078 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3081 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3082 /// for tail call optimization. Targets which want to do tail call
3083 /// optimization should implement this function.
3085 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3086 CallingConv::ID CalleeCC,
3088 bool isCalleeStructRet,
3089 bool isCallerStructRet,
3091 const SmallVectorImpl<ISD::OutputArg> &Outs,
3092 const SmallVectorImpl<SDValue> &OutVals,
3093 const SmallVectorImpl<ISD::InputArg> &Ins,
3094 SelectionDAG &DAG) const {
3095 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3098 // If -tailcallopt is specified, make fastcc functions tail-callable.
3099 const MachineFunction &MF = DAG.getMachineFunction();
3100 const Function *CallerF = MF.getFunction();
3102 // If the function return type is x86_fp80 and the callee return type is not,
3103 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3104 // perform a tailcall optimization here.
3105 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3108 CallingConv::ID CallerCC = CallerF->getCallingConv();
3109 bool CCMatch = CallerCC == CalleeCC;
3110 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3111 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3113 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3114 if (IsTailCallConvention(CalleeCC) && CCMatch)
3119 // Look for obvious safe cases to perform tail call optimization that do not
3120 // require ABI changes. This is what gcc calls sibcall.
3122 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3123 // emit a special epilogue.
3124 const X86RegisterInfo *RegInfo =
3125 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3126 if (RegInfo->needsStackRealignment(MF))
3129 // Also avoid sibcall optimization if either caller or callee uses struct
3130 // return semantics.
3131 if (isCalleeStructRet || isCallerStructRet)
3134 // An stdcall/thiscall caller is expected to clean up its arguments; the
3135 // callee isn't going to do that.
3136 // FIXME: this is more restrictive than needed. We could produce a tailcall
3137 // when the stack adjustment matches. For example, with a thiscall that takes
3138 // only one argument.
3139 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3140 CallerCC == CallingConv::X86_ThisCall))
3143 // Do not sibcall optimize vararg calls unless all arguments are passed via
3145 if (isVarArg && !Outs.empty()) {
3147 // Optimizing for varargs on Win64 is unlikely to be safe without
3148 // additional testing.
3149 if (IsCalleeWin64 || IsCallerWin64)
3152 SmallVector<CCValAssign, 16> ArgLocs;
3153 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3154 getTargetMachine(), ArgLocs, *DAG.getContext());
3156 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3157 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3158 if (!ArgLocs[i].isRegLoc())
3162 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3163 // stack. Therefore, if it's not used by the call it is not safe to optimize
3164 // this into a sibcall.
3165 bool Unused = false;
3166 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3173 SmallVector<CCValAssign, 16> RVLocs;
3174 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3175 getTargetMachine(), RVLocs, *DAG.getContext());
3176 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3177 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3178 CCValAssign &VA = RVLocs[i];
3179 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3184 // If the calling conventions do not match, then we'd better make sure the
3185 // results are returned in the same way as what the caller expects.
3187 SmallVector<CCValAssign, 16> RVLocs1;
3188 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3189 getTargetMachine(), RVLocs1, *DAG.getContext());
3190 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3192 SmallVector<CCValAssign, 16> RVLocs2;
3193 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3194 getTargetMachine(), RVLocs2, *DAG.getContext());
3195 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3197 if (RVLocs1.size() != RVLocs2.size())
3199 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3200 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3202 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3204 if (RVLocs1[i].isRegLoc()) {
3205 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3208 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3214 // If the callee takes no arguments then go on to check the results of the
3216 if (!Outs.empty()) {
3217 // Check if stack adjustment is needed. For now, do not do this if any
3218 // argument is passed on the stack.
3219 SmallVector<CCValAssign, 16> ArgLocs;
3220 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3221 getTargetMachine(), ArgLocs, *DAG.getContext());
3223 // Allocate shadow area for Win64
3225 CCInfo.AllocateStack(32, 8);
3227 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3228 if (CCInfo.getNextStackOffset()) {
3229 MachineFunction &MF = DAG.getMachineFunction();
3230 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3233 // Check if the arguments are already laid out in the right way as
3234 // the caller's fixed stack objects.
3235 MachineFrameInfo *MFI = MF.getFrameInfo();
3236 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3237 const X86InstrInfo *TII =
3238 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3239 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3240 CCValAssign &VA = ArgLocs[i];
3241 SDValue Arg = OutVals[i];
3242 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3243 if (VA.getLocInfo() == CCValAssign::Indirect)
3245 if (!VA.isRegLoc()) {
3246 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3253 // If the tailcall address may be in a register, then make sure it's
3254 // possible to register allocate for it. In 32-bit, the call address can
3255 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3256 // callee-saved registers are restored. These happen to be the same
3257 // registers used to pass 'inreg' arguments so watch out for those.
3258 if (!Subtarget->is64Bit() &&
3259 ((!isa<GlobalAddressSDNode>(Callee) &&
3260 !isa<ExternalSymbolSDNode>(Callee)) ||
3261 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3262 unsigned NumInRegs = 0;
3263 // In PIC we need an extra register to formulate the address computation
3265 unsigned MaxInRegs =
3266 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3268 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3269 CCValAssign &VA = ArgLocs[i];
3272 unsigned Reg = VA.getLocReg();
3275 case X86::EAX: case X86::EDX: case X86::ECX:
3276 if (++NumInRegs == MaxInRegs)
3288 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3289 const TargetLibraryInfo *libInfo) const {
3290 return X86::createFastISel(funcInfo, libInfo);
3293 //===----------------------------------------------------------------------===//
3294 // Other Lowering Hooks
3295 //===----------------------------------------------------------------------===//
3297 static bool MayFoldLoad(SDValue Op) {
3298 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3301 static bool MayFoldIntoStore(SDValue Op) {
3302 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3305 static bool isTargetShuffle(unsigned Opcode) {
3307 default: return false;
3308 case X86ISD::PSHUFD:
3309 case X86ISD::PSHUFHW:
3310 case X86ISD::PSHUFLW:
3312 case X86ISD::PALIGNR:
3313 case X86ISD::MOVLHPS:
3314 case X86ISD::MOVLHPD:
3315 case X86ISD::MOVHLPS:
3316 case X86ISD::MOVLPS:
3317 case X86ISD::MOVLPD:
3318 case X86ISD::MOVSHDUP:
3319 case X86ISD::MOVSLDUP:
3320 case X86ISD::MOVDDUP:
3323 case X86ISD::UNPCKL:
3324 case X86ISD::UNPCKH:
3325 case X86ISD::VPERMILP:
3326 case X86ISD::VPERM2X128:
3327 case X86ISD::VPERMI:
3332 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3333 SDValue V1, SelectionDAG &DAG) {
3335 default: llvm_unreachable("Unknown x86 shuffle node");
3336 case X86ISD::MOVSHDUP:
3337 case X86ISD::MOVSLDUP:
3338 case X86ISD::MOVDDUP:
3339 return DAG.getNode(Opc, dl, VT, V1);
3343 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3344 SDValue V1, unsigned TargetMask,
3345 SelectionDAG &DAG) {
3347 default: llvm_unreachable("Unknown x86 shuffle node");
3348 case X86ISD::PSHUFD:
3349 case X86ISD::PSHUFHW:
3350 case X86ISD::PSHUFLW:
3351 case X86ISD::VPERMILP:
3352 case X86ISD::VPERMI:
3353 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3357 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3358 SDValue V1, SDValue V2, unsigned TargetMask,
3359 SelectionDAG &DAG) {
3361 default: llvm_unreachable("Unknown x86 shuffle node");
3362 case X86ISD::PALIGNR:
3364 case X86ISD::VPERM2X128:
3365 return DAG.getNode(Opc, dl, VT, V1, V2,
3366 DAG.getConstant(TargetMask, MVT::i8));
3370 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3371 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3373 default: llvm_unreachable("Unknown x86 shuffle node");
3374 case X86ISD::MOVLHPS:
3375 case X86ISD::MOVLHPD:
3376 case X86ISD::MOVHLPS:
3377 case X86ISD::MOVLPS:
3378 case X86ISD::MOVLPD:
3381 case X86ISD::UNPCKL:
3382 case X86ISD::UNPCKH:
3383 return DAG.getNode(Opc, dl, VT, V1, V2);
3387 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3388 MachineFunction &MF = DAG.getMachineFunction();
3389 const X86RegisterInfo *RegInfo =
3390 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3391 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3392 int ReturnAddrIndex = FuncInfo->getRAIndex();
3394 if (ReturnAddrIndex == 0) {
3395 // Set up a frame object for the return address.
3396 unsigned SlotSize = RegInfo->getSlotSize();
3397 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3400 FuncInfo->setRAIndex(ReturnAddrIndex);
3403 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3406 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3407 bool hasSymbolicDisplacement) {
3408 // Offset should fit into 32 bit immediate field.
3409 if (!isInt<32>(Offset))
3412 // If we don't have a symbolic displacement - we don't have any extra
3414 if (!hasSymbolicDisplacement)
3417 // FIXME: Some tweaks might be needed for medium code model.
3418 if (M != CodeModel::Small && M != CodeModel::Kernel)
3421 // For small code model we assume that latest object is 16MB before end of 31
3422 // bits boundary. We may also accept pretty large negative constants knowing
3423 // that all objects are in the positive half of address space.
3424 if (M == CodeModel::Small && Offset < 16*1024*1024)
3427 // For kernel code model we know that all object resist in the negative half
3428 // of 32bits address space. We may not accept negative offsets, since they may
3429 // be just off and we may accept pretty large positive ones.
3430 if (M == CodeModel::Kernel && Offset > 0)
3436 /// isCalleePop - Determines whether the callee is required to pop its
3437 /// own arguments. Callee pop is necessary to support tail calls.
3438 bool X86::isCalleePop(CallingConv::ID CallingConv,
3439 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3443 switch (CallingConv) {
3446 case CallingConv::X86_StdCall:
3448 case CallingConv::X86_FastCall:
3450 case CallingConv::X86_ThisCall:
3452 case CallingConv::Fast:
3454 case CallingConv::GHC:
3456 case CallingConv::HiPE:
3461 /// \brief Return true if the condition is an unsigned comparison operation.
3462 static bool isX86CCUnsigned(unsigned X86CC) {
3464 default: llvm_unreachable("Invalid integer condition!");
3465 case X86::COND_E: return true;
3466 case X86::COND_G: return false;
3467 case X86::COND_GE: return false;
3468 case X86::COND_L: return false;
3469 case X86::COND_LE: return false;
3470 case X86::COND_NE: return true;
3471 case X86::COND_B: return true;
3472 case X86::COND_A: return true;
3473 case X86::COND_BE: return true;
3474 case X86::COND_AE: return true;
3476 llvm_unreachable("covered switch fell through?!");
3479 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3480 /// specific condition code, returning the condition code and the LHS/RHS of the
3481 /// comparison to make.
3482 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3483 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3485 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3486 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3487 // X > -1 -> X == 0, jump !sign.
3488 RHS = DAG.getConstant(0, RHS.getValueType());
3489 return X86::COND_NS;
3491 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3492 // X < 0 -> X == 0, jump on sign.
3495 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3497 RHS = DAG.getConstant(0, RHS.getValueType());
3498 return X86::COND_LE;
3502 switch (SetCCOpcode) {
3503 default: llvm_unreachable("Invalid integer condition!");
3504 case ISD::SETEQ: return X86::COND_E;
3505 case ISD::SETGT: return X86::COND_G;
3506 case ISD::SETGE: return X86::COND_GE;
3507 case ISD::SETLT: return X86::COND_L;
3508 case ISD::SETLE: return X86::COND_LE;
3509 case ISD::SETNE: return X86::COND_NE;
3510 case ISD::SETULT: return X86::COND_B;
3511 case ISD::SETUGT: return X86::COND_A;
3512 case ISD::SETULE: return X86::COND_BE;
3513 case ISD::SETUGE: return X86::COND_AE;
3517 // First determine if it is required or is profitable to flip the operands.
3519 // If LHS is a foldable load, but RHS is not, flip the condition.
3520 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3521 !ISD::isNON_EXTLoad(RHS.getNode())) {
3522 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3523 std::swap(LHS, RHS);
3526 switch (SetCCOpcode) {
3532 std::swap(LHS, RHS);
3536 // On a floating point condition, the flags are set as follows:
3538 // 0 | 0 | 0 | X > Y
3539 // 0 | 0 | 1 | X < Y
3540 // 1 | 0 | 0 | X == Y
3541 // 1 | 1 | 1 | unordered
3542 switch (SetCCOpcode) {
3543 default: llvm_unreachable("Condcode should be pre-legalized away");
3545 case ISD::SETEQ: return X86::COND_E;
3546 case ISD::SETOLT: // flipped
3548 case ISD::SETGT: return X86::COND_A;
3549 case ISD::SETOLE: // flipped
3551 case ISD::SETGE: return X86::COND_AE;
3552 case ISD::SETUGT: // flipped
3554 case ISD::SETLT: return X86::COND_B;
3555 case ISD::SETUGE: // flipped
3557 case ISD::SETLE: return X86::COND_BE;
3559 case ISD::SETNE: return X86::COND_NE;
3560 case ISD::SETUO: return X86::COND_P;
3561 case ISD::SETO: return X86::COND_NP;
3563 case ISD::SETUNE: return X86::COND_INVALID;
3567 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3568 /// code. Current x86 isa includes the following FP cmov instructions:
3569 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3570 static bool hasFPCMov(unsigned X86CC) {
3586 /// isFPImmLegal - Returns true if the target can instruction select the
3587 /// specified FP immediate natively. If false, the legalizer will
3588 /// materialize the FP immediate as a load from a constant pool.
3589 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3590 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3591 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3597 /// \brief Returns true if it is beneficial to convert a load of a constant
3598 /// to just the constant itself.
3599 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3601 assert(Ty->isIntegerTy());
3603 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3604 if (BitSize == 0 || BitSize > 64)
3609 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3610 /// the specified range (L, H].
3611 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3612 return (Val < 0) || (Val >= Low && Val < Hi);
3615 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3616 /// specified value.
3617 static bool isUndefOrEqual(int Val, int CmpVal) {
3618 return (Val < 0 || Val == CmpVal);
3621 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3622 /// from position Pos and ending in Pos+Size, falls within the specified
3623 /// sequential range (L, L+Pos]. or is undef.
3624 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3625 unsigned Pos, unsigned Size, int Low) {
3626 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3627 if (!isUndefOrEqual(Mask[i], Low))
3632 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3633 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3634 /// the second operand.
3635 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3636 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3637 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3638 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3639 return (Mask[0] < 2 && Mask[1] < 2);
3643 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3644 /// is suitable for input to PSHUFHW.
3645 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3646 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3649 // Lower quadword copied in order or undef.
3650 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3653 // Upper quadword shuffled.
3654 for (unsigned i = 4; i != 8; ++i)
3655 if (!isUndefOrInRange(Mask[i], 4, 8))
3658 if (VT == MVT::v16i16) {
3659 // Lower quadword copied in order or undef.
3660 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3663 // Upper quadword shuffled.
3664 for (unsigned i = 12; i != 16; ++i)
3665 if (!isUndefOrInRange(Mask[i], 12, 16))
3672 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3673 /// is suitable for input to PSHUFLW.
3674 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3675 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3678 // Upper quadword copied in order.
3679 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3682 // Lower quadword shuffled.
3683 for (unsigned i = 0; i != 4; ++i)
3684 if (!isUndefOrInRange(Mask[i], 0, 4))
3687 if (VT == MVT::v16i16) {
3688 // Upper quadword copied in order.
3689 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3692 // Lower quadword shuffled.
3693 for (unsigned i = 8; i != 12; ++i)
3694 if (!isUndefOrInRange(Mask[i], 8, 12))
3701 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3702 /// is suitable for input to PALIGNR.
3703 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3704 const X86Subtarget *Subtarget) {
3705 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3706 (VT.is256BitVector() && !Subtarget->hasInt256()))
3709 unsigned NumElts = VT.getVectorNumElements();
3710 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3711 unsigned NumLaneElts = NumElts/NumLanes;
3713 // Do not handle 64-bit element shuffles with palignr.
3714 if (NumLaneElts == 2)
3717 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3719 for (i = 0; i != NumLaneElts; ++i) {
3724 // Lane is all undef, go to next lane
3725 if (i == NumLaneElts)
3728 int Start = Mask[i+l];
3730 // Make sure its in this lane in one of the sources
3731 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3732 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3735 // If not lane 0, then we must match lane 0
3736 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3739 // Correct second source to be contiguous with first source
3740 if (Start >= (int)NumElts)
3741 Start -= NumElts - NumLaneElts;
3743 // Make sure we're shifting in the right direction.
3744 if (Start <= (int)(i+l))
3749 // Check the rest of the elements to see if they are consecutive.
3750 for (++i; i != NumLaneElts; ++i) {
3751 int Idx = Mask[i+l];
3753 // Make sure its in this lane
3754 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3755 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3758 // If not lane 0, then we must match lane 0
3759 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3762 if (Idx >= (int)NumElts)
3763 Idx -= NumElts - NumLaneElts;
3765 if (!isUndefOrEqual(Idx, Start+i))
3774 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3775 /// the two vector operands have swapped position.
3776 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3777 unsigned NumElems) {
3778 for (unsigned i = 0; i != NumElems; ++i) {
3782 else if (idx < (int)NumElems)
3783 Mask[i] = idx + NumElems;
3785 Mask[i] = idx - NumElems;
3789 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3790 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3791 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3792 /// reverse of what x86 shuffles want.
3793 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3795 unsigned NumElems = VT.getVectorNumElements();
3796 unsigned NumLanes = VT.getSizeInBits()/128;
3797 unsigned NumLaneElems = NumElems/NumLanes;
3799 if (NumLaneElems != 2 && NumLaneElems != 4)
3802 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3803 bool symetricMaskRequired =
3804 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3806 // VSHUFPSY divides the resulting vector into 4 chunks.
3807 // The sources are also splitted into 4 chunks, and each destination
3808 // chunk must come from a different source chunk.
3810 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3811 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3813 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3814 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3816 // VSHUFPDY divides the resulting vector into 4 chunks.
3817 // The sources are also splitted into 4 chunks, and each destination
3818 // chunk must come from a different source chunk.
3820 // SRC1 => X3 X2 X1 X0
3821 // SRC2 => Y3 Y2 Y1 Y0
3823 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3825 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3826 unsigned HalfLaneElems = NumLaneElems/2;
3827 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3828 for (unsigned i = 0; i != NumLaneElems; ++i) {
3829 int Idx = Mask[i+l];
3830 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3831 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3833 // For VSHUFPSY, the mask of the second half must be the same as the
3834 // first but with the appropriate offsets. This works in the same way as
3835 // VPERMILPS works with masks.
3836 if (!symetricMaskRequired || Idx < 0)
3838 if (MaskVal[i] < 0) {
3839 MaskVal[i] = Idx - l;
3842 if ((signed)(Idx - l) != MaskVal[i])
3850 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3851 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3852 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3853 if (!VT.is128BitVector())
3856 unsigned NumElems = VT.getVectorNumElements();
3861 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3862 return isUndefOrEqual(Mask[0], 6) &&
3863 isUndefOrEqual(Mask[1], 7) &&
3864 isUndefOrEqual(Mask[2], 2) &&
3865 isUndefOrEqual(Mask[3], 3);
3868 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3869 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3871 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3872 if (!VT.is128BitVector())
3875 unsigned NumElems = VT.getVectorNumElements();
3880 return isUndefOrEqual(Mask[0], 2) &&
3881 isUndefOrEqual(Mask[1], 3) &&
3882 isUndefOrEqual(Mask[2], 2) &&
3883 isUndefOrEqual(Mask[3], 3);
3886 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3887 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3888 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3889 if (!VT.is128BitVector())
3892 unsigned NumElems = VT.getVectorNumElements();
3894 if (NumElems != 2 && NumElems != 4)
3897 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3898 if (!isUndefOrEqual(Mask[i], i + NumElems))
3901 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3902 if (!isUndefOrEqual(Mask[i], i))
3908 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3909 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3910 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3911 if (!VT.is128BitVector())
3914 unsigned NumElems = VT.getVectorNumElements();
3916 if (NumElems != 2 && NumElems != 4)
3919 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3920 if (!isUndefOrEqual(Mask[i], i))
3923 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3924 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3931 // Some special combinations that can be optimized.
3934 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3935 SelectionDAG &DAG) {
3936 MVT VT = SVOp->getSimpleValueType(0);
3939 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3942 ArrayRef<int> Mask = SVOp->getMask();
3944 // These are the special masks that may be optimized.
3945 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3946 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3947 bool MatchEvenMask = true;
3948 bool MatchOddMask = true;
3949 for (int i=0; i<8; ++i) {
3950 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3951 MatchEvenMask = false;
3952 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3953 MatchOddMask = false;
3956 if (!MatchEvenMask && !MatchOddMask)
3959 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3961 SDValue Op0 = SVOp->getOperand(0);
3962 SDValue Op1 = SVOp->getOperand(1);
3964 if (MatchEvenMask) {
3965 // Shift the second operand right to 32 bits.
3966 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3967 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3969 // Shift the first operand left to 32 bits.
3970 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3971 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3973 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3974 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3977 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3978 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3979 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3980 bool HasInt256, bool V2IsSplat = false) {
3982 assert(VT.getSizeInBits() >= 128 &&
3983 "Unsupported vector type for unpckl");
3985 // AVX defines UNPCK* to operate independently on 128-bit lanes.
3987 unsigned NumOf256BitLanes;
3988 unsigned NumElts = VT.getVectorNumElements();
3989 if (VT.is256BitVector()) {
3990 if (NumElts != 4 && NumElts != 8 &&
3991 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3994 NumOf256BitLanes = 1;
3995 } else if (VT.is512BitVector()) {
3996 assert(VT.getScalarType().getSizeInBits() >= 32 &&
3997 "Unsupported vector type for unpckh");
3999 NumOf256BitLanes = 2;
4002 NumOf256BitLanes = 1;
4005 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4006 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4008 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4009 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4010 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4011 int BitI = Mask[l256*NumEltsInStride+l+i];
4012 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4013 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4015 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4017 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4025 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4026 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4027 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4028 bool HasInt256, bool V2IsSplat = false) {
4029 assert(VT.getSizeInBits() >= 128 &&
4030 "Unsupported vector type for unpckh");
4032 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4034 unsigned NumOf256BitLanes;
4035 unsigned NumElts = VT.getVectorNumElements();
4036 if (VT.is256BitVector()) {
4037 if (NumElts != 4 && NumElts != 8 &&
4038 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4041 NumOf256BitLanes = 1;
4042 } else if (VT.is512BitVector()) {
4043 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4044 "Unsupported vector type for unpckh");
4046 NumOf256BitLanes = 2;
4049 NumOf256BitLanes = 1;
4052 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4053 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4055 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4056 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4057 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4058 int BitI = Mask[l256*NumEltsInStride+l+i];
4059 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4060 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4062 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4064 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4072 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4073 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4075 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4076 unsigned NumElts = VT.getVectorNumElements();
4077 bool Is256BitVec = VT.is256BitVector();
4079 if (VT.is512BitVector())
4081 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4082 "Unsupported vector type for unpckh");
4084 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4085 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4088 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4089 // FIXME: Need a better way to get rid of this, there's no latency difference
4090 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4091 // the former later. We should also remove the "_undef" special mask.
4092 if (NumElts == 4 && Is256BitVec)
4095 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4096 // independently on 128-bit lanes.
4097 unsigned NumLanes = VT.getSizeInBits()/128;
4098 unsigned NumLaneElts = NumElts/NumLanes;
4100 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4101 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4102 int BitI = Mask[l+i];
4103 int BitI1 = Mask[l+i+1];
4105 if (!isUndefOrEqual(BitI, j))
4107 if (!isUndefOrEqual(BitI1, j))
4115 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4116 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4118 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4119 unsigned NumElts = VT.getVectorNumElements();
4121 if (VT.is512BitVector())
4124 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4125 "Unsupported vector type for unpckh");
4127 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4128 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4131 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4132 // independently on 128-bit lanes.
4133 unsigned NumLanes = VT.getSizeInBits()/128;
4134 unsigned NumLaneElts = NumElts/NumLanes;
4136 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4137 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4138 int BitI = Mask[l+i];
4139 int BitI1 = Mask[l+i+1];
4140 if (!isUndefOrEqual(BitI, j))
4142 if (!isUndefOrEqual(BitI1, j))
4149 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4150 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4151 /// MOVSD, and MOVD, i.e. setting the lowest element.
4152 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4153 if (VT.getVectorElementType().getSizeInBits() < 32)
4155 if (!VT.is128BitVector())
4158 unsigned NumElts = VT.getVectorNumElements();
4160 if (!isUndefOrEqual(Mask[0], NumElts))
4163 for (unsigned i = 1; i != NumElts; ++i)
4164 if (!isUndefOrEqual(Mask[i], i))
4170 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4171 /// as permutations between 128-bit chunks or halves. As an example: this
4173 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4174 /// The first half comes from the second half of V1 and the second half from the
4175 /// the second half of V2.
4176 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4177 if (!HasFp256 || !VT.is256BitVector())
4180 // The shuffle result is divided into half A and half B. In total the two
4181 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4182 // B must come from C, D, E or F.
4183 unsigned HalfSize = VT.getVectorNumElements()/2;
4184 bool MatchA = false, MatchB = false;
4186 // Check if A comes from one of C, D, E, F.
4187 for (unsigned Half = 0; Half != 4; ++Half) {
4188 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4194 // Check if B comes from one of C, D, E, F.
4195 for (unsigned Half = 0; Half != 4; ++Half) {
4196 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4202 return MatchA && MatchB;
4205 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4206 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4207 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4208 MVT VT = SVOp->getSimpleValueType(0);
4210 unsigned HalfSize = VT.getVectorNumElements()/2;
4212 unsigned FstHalf = 0, SndHalf = 0;
4213 for (unsigned i = 0; i < HalfSize; ++i) {
4214 if (SVOp->getMaskElt(i) > 0) {
4215 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4219 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4220 if (SVOp->getMaskElt(i) > 0) {
4221 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4226 return (FstHalf | (SndHalf << 4));
4229 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4230 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4231 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4235 unsigned NumElts = VT.getVectorNumElements();
4237 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4238 for (unsigned i = 0; i != NumElts; ++i) {
4241 Imm8 |= Mask[i] << (i*2);
4246 unsigned LaneSize = 4;
4247 SmallVector<int, 4> MaskVal(LaneSize, -1);
4249 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4250 for (unsigned i = 0; i != LaneSize; ++i) {
4251 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4255 if (MaskVal[i] < 0) {
4256 MaskVal[i] = Mask[i+l] - l;
4257 Imm8 |= MaskVal[i] << (i*2);
4260 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4267 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4268 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4269 /// Note that VPERMIL mask matching is different depending whether theunderlying
4270 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4271 /// to the same elements of the low, but to the higher half of the source.
4272 /// In VPERMILPD the two lanes could be shuffled independently of each other
4273 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4274 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4275 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4276 if (VT.getSizeInBits() < 256 || EltSize < 32)
4278 bool symetricMaskRequired = (EltSize == 32);
4279 unsigned NumElts = VT.getVectorNumElements();
4281 unsigned NumLanes = VT.getSizeInBits()/128;
4282 unsigned LaneSize = NumElts/NumLanes;
4283 // 2 or 4 elements in one lane
4285 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4286 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4287 for (unsigned i = 0; i != LaneSize; ++i) {
4288 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4290 if (symetricMaskRequired) {
4291 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4292 ExpectedMaskVal[i] = Mask[i+l] - l;
4295 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4303 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4304 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4305 /// element of vector 2 and the other elements to come from vector 1 in order.
4306 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4307 bool V2IsSplat = false, bool V2IsUndef = false) {
4308 if (!VT.is128BitVector())
4311 unsigned NumOps = VT.getVectorNumElements();
4312 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4315 if (!isUndefOrEqual(Mask[0], 0))
4318 for (unsigned i = 1; i != NumOps; ++i)
4319 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4320 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4321 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4327 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4328 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4329 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4330 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4331 const X86Subtarget *Subtarget) {
4332 if (!Subtarget->hasSSE3())
4335 unsigned NumElems = VT.getVectorNumElements();
4337 if ((VT.is128BitVector() && NumElems != 4) ||
4338 (VT.is256BitVector() && NumElems != 8) ||
4339 (VT.is512BitVector() && NumElems != 16))
4342 // "i+1" is the value the indexed mask element must have
4343 for (unsigned i = 0; i != NumElems; i += 2)
4344 if (!isUndefOrEqual(Mask[i], i+1) ||
4345 !isUndefOrEqual(Mask[i+1], i+1))
4351 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4352 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4353 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4354 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4355 const X86Subtarget *Subtarget) {
4356 if (!Subtarget->hasSSE3())
4359 unsigned NumElems = VT.getVectorNumElements();
4361 if ((VT.is128BitVector() && NumElems != 4) ||
4362 (VT.is256BitVector() && NumElems != 8) ||
4363 (VT.is512BitVector() && NumElems != 16))
4366 // "i" is the value the indexed mask element must have
4367 for (unsigned i = 0; i != NumElems; i += 2)
4368 if (!isUndefOrEqual(Mask[i], i) ||
4369 !isUndefOrEqual(Mask[i+1], i))
4375 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4376 /// specifies a shuffle of elements that is suitable for input to 256-bit
4377 /// version of MOVDDUP.
4378 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4379 if (!HasFp256 || !VT.is256BitVector())
4382 unsigned NumElts = VT.getVectorNumElements();
4386 for (unsigned i = 0; i != NumElts/2; ++i)
4387 if (!isUndefOrEqual(Mask[i], 0))
4389 for (unsigned i = NumElts/2; i != NumElts; ++i)
4390 if (!isUndefOrEqual(Mask[i], NumElts/2))
4395 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4396 /// specifies a shuffle of elements that is suitable for input to 128-bit
4397 /// version of MOVDDUP.
4398 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4399 if (!VT.is128BitVector())
4402 unsigned e = VT.getVectorNumElements() / 2;
4403 for (unsigned i = 0; i != e; ++i)
4404 if (!isUndefOrEqual(Mask[i], i))
4406 for (unsigned i = 0; i != e; ++i)
4407 if (!isUndefOrEqual(Mask[e+i], i))
4412 /// isVEXTRACTIndex - Return true if the specified
4413 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4414 /// suitable for instruction that extract 128 or 256 bit vectors
4415 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4416 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4417 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4420 // The index should be aligned on a vecWidth-bit boundary.
4422 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4424 MVT VT = N->getSimpleValueType(0);
4425 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4426 bool Result = (Index * ElSize) % vecWidth == 0;
4431 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4432 /// operand specifies a subvector insert that is suitable for input to
4433 /// insertion of 128 or 256-bit subvectors
4434 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4435 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4436 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4438 // The index should be aligned on a vecWidth-bit boundary.
4440 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4442 MVT VT = N->getSimpleValueType(0);
4443 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4444 bool Result = (Index * ElSize) % vecWidth == 0;
4449 bool X86::isVINSERT128Index(SDNode *N) {
4450 return isVINSERTIndex(N, 128);
4453 bool X86::isVINSERT256Index(SDNode *N) {
4454 return isVINSERTIndex(N, 256);
4457 bool X86::isVEXTRACT128Index(SDNode *N) {
4458 return isVEXTRACTIndex(N, 128);
4461 bool X86::isVEXTRACT256Index(SDNode *N) {
4462 return isVEXTRACTIndex(N, 256);
4465 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4466 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4467 /// Handles 128-bit and 256-bit.
4468 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4469 MVT VT = N->getSimpleValueType(0);
4471 assert((VT.getSizeInBits() >= 128) &&
4472 "Unsupported vector type for PSHUF/SHUFP");
4474 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4475 // independently on 128-bit lanes.
4476 unsigned NumElts = VT.getVectorNumElements();
4477 unsigned NumLanes = VT.getSizeInBits()/128;
4478 unsigned NumLaneElts = NumElts/NumLanes;
4480 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4481 "Only supports 2, 4 or 8 elements per lane");
4483 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4485 for (unsigned i = 0; i != NumElts; ++i) {
4486 int Elt = N->getMaskElt(i);
4487 if (Elt < 0) continue;
4488 Elt &= NumLaneElts - 1;
4489 unsigned ShAmt = (i << Shift) % 8;
4490 Mask |= Elt << ShAmt;
4496 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4497 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4498 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4499 MVT VT = N->getSimpleValueType(0);
4501 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4502 "Unsupported vector type for PSHUFHW");
4504 unsigned NumElts = VT.getVectorNumElements();
4507 for (unsigned l = 0; l != NumElts; l += 8) {
4508 // 8 nodes per lane, but we only care about the last 4.
4509 for (unsigned i = 0; i < 4; ++i) {
4510 int Elt = N->getMaskElt(l+i+4);
4511 if (Elt < 0) continue;
4512 Elt &= 0x3; // only 2-bits.
4513 Mask |= Elt << (i * 2);
4520 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4521 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4522 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4523 MVT VT = N->getSimpleValueType(0);
4525 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4526 "Unsupported vector type for PSHUFHW");
4528 unsigned NumElts = VT.getVectorNumElements();
4531 for (unsigned l = 0; l != NumElts; l += 8) {
4532 // 8 nodes per lane, but we only care about the first 4.
4533 for (unsigned i = 0; i < 4; ++i) {
4534 int Elt = N->getMaskElt(l+i);
4535 if (Elt < 0) continue;
4536 Elt &= 0x3; // only 2-bits
4537 Mask |= Elt << (i * 2);
4544 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4545 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4546 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4547 MVT VT = SVOp->getSimpleValueType(0);
4548 unsigned EltSize = VT.is512BitVector() ? 1 :
4549 VT.getVectorElementType().getSizeInBits() >> 3;
4551 unsigned NumElts = VT.getVectorNumElements();
4552 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4553 unsigned NumLaneElts = NumElts/NumLanes;
4557 for (i = 0; i != NumElts; ++i) {
4558 Val = SVOp->getMaskElt(i);
4562 if (Val >= (int)NumElts)
4563 Val -= NumElts - NumLaneElts;
4565 assert(Val - i > 0 && "PALIGNR imm should be positive");
4566 return (Val - i) * EltSize;
4569 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4570 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4571 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4572 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4575 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4577 MVT VecVT = N->getOperand(0).getSimpleValueType();
4578 MVT ElVT = VecVT.getVectorElementType();
4580 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4581 return Index / NumElemsPerChunk;
4584 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4585 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4586 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4587 llvm_unreachable("Illegal insert subvector for VINSERT");
4590 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4592 MVT VecVT = N->getSimpleValueType(0);
4593 MVT ElVT = VecVT.getVectorElementType();
4595 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4596 return Index / NumElemsPerChunk;
4599 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4600 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4601 /// and VINSERTI128 instructions.
4602 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4603 return getExtractVEXTRACTImmediate(N, 128);
4606 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4607 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4608 /// and VINSERTI64x4 instructions.
4609 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4610 return getExtractVEXTRACTImmediate(N, 256);
4613 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4614 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4615 /// and VINSERTI128 instructions.
4616 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4617 return getInsertVINSERTImmediate(N, 128);
4620 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4621 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4622 /// and VINSERTI64x4 instructions.
4623 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4624 return getInsertVINSERTImmediate(N, 256);
4627 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4629 bool X86::isZeroNode(SDValue Elt) {
4630 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4631 return CN->isNullValue();
4632 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4633 return CFP->getValueAPF().isPosZero();
4637 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4638 /// their permute mask.
4639 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4640 SelectionDAG &DAG) {
4641 MVT VT = SVOp->getSimpleValueType(0);
4642 unsigned NumElems = VT.getVectorNumElements();
4643 SmallVector<int, 8> MaskVec;
4645 for (unsigned i = 0; i != NumElems; ++i) {
4646 int Idx = SVOp->getMaskElt(i);
4648 if (Idx < (int)NumElems)
4653 MaskVec.push_back(Idx);
4655 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4656 SVOp->getOperand(0), &MaskVec[0]);
4659 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4660 /// match movhlps. The lower half elements should come from upper half of
4661 /// V1 (and in order), and the upper half elements should come from the upper
4662 /// half of V2 (and in order).
4663 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4664 if (!VT.is128BitVector())
4666 if (VT.getVectorNumElements() != 4)
4668 for (unsigned i = 0, e = 2; i != e; ++i)
4669 if (!isUndefOrEqual(Mask[i], i+2))
4671 for (unsigned i = 2; i != 4; ++i)
4672 if (!isUndefOrEqual(Mask[i], i+4))
4677 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4678 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4680 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4681 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4683 N = N->getOperand(0).getNode();
4684 if (!ISD::isNON_EXTLoad(N))
4687 *LD = cast<LoadSDNode>(N);
4691 // Test whether the given value is a vector value which will be legalized
4693 static bool WillBeConstantPoolLoad(SDNode *N) {
4694 if (N->getOpcode() != ISD::BUILD_VECTOR)
4697 // Check for any non-constant elements.
4698 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4699 switch (N->getOperand(i).getNode()->getOpcode()) {
4701 case ISD::ConstantFP:
4708 // Vectors of all-zeros and all-ones are materialized with special
4709 // instructions rather than being loaded.
4710 return !ISD::isBuildVectorAllZeros(N) &&
4711 !ISD::isBuildVectorAllOnes(N);
4714 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4715 /// match movlp{s|d}. The lower half elements should come from lower half of
4716 /// V1 (and in order), and the upper half elements should come from the upper
4717 /// half of V2 (and in order). And since V1 will become the source of the
4718 /// MOVLP, it must be either a vector load or a scalar load to vector.
4719 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4720 ArrayRef<int> Mask, MVT VT) {
4721 if (!VT.is128BitVector())
4724 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4726 // Is V2 is a vector load, don't do this transformation. We will try to use
4727 // load folding shufps op.
4728 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4731 unsigned NumElems = VT.getVectorNumElements();
4733 if (NumElems != 2 && NumElems != 4)
4735 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4736 if (!isUndefOrEqual(Mask[i], i))
4738 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4739 if (!isUndefOrEqual(Mask[i], i+NumElems))
4744 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4746 static bool isSplatVector(SDNode *N) {
4747 if (N->getOpcode() != ISD::BUILD_VECTOR)
4750 SDValue SplatValue = N->getOperand(0);
4751 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4752 if (N->getOperand(i) != SplatValue)
4757 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4758 /// to an zero vector.
4759 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4760 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4761 SDValue V1 = N->getOperand(0);
4762 SDValue V2 = N->getOperand(1);
4763 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4764 for (unsigned i = 0; i != NumElems; ++i) {
4765 int Idx = N->getMaskElt(i);
4766 if (Idx >= (int)NumElems) {
4767 unsigned Opc = V2.getOpcode();
4768 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4770 if (Opc != ISD::BUILD_VECTOR ||
4771 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4773 } else if (Idx >= 0) {
4774 unsigned Opc = V1.getOpcode();
4775 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4777 if (Opc != ISD::BUILD_VECTOR ||
4778 !X86::isZeroNode(V1.getOperand(Idx)))
4785 /// getZeroVector - Returns a vector of specified type with all zero elements.
4787 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4788 SelectionDAG &DAG, SDLoc dl) {
4789 assert(VT.isVector() && "Expected a vector type");
4791 // Always build SSE zero vectors as <4 x i32> bitcasted
4792 // to their dest type. This ensures they get CSE'd.
4794 if (VT.is128BitVector()) { // SSE
4795 if (Subtarget->hasSSE2()) { // SSE2
4796 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4797 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4799 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4800 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4802 } else if (VT.is256BitVector()) { // AVX
4803 if (Subtarget->hasInt256()) { // AVX2
4804 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4805 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4806 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4807 array_lengthof(Ops));
4809 // 256-bit logic and arithmetic instructions in AVX are all
4810 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4811 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4812 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4813 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4814 array_lengthof(Ops));
4816 } else if (VT.is512BitVector()) { // AVX-512
4817 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4818 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4819 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4820 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4821 } else if (VT.getScalarType() == MVT::i1) {
4822 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4823 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4824 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4825 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4826 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4827 Ops, VT.getVectorNumElements());
4829 llvm_unreachable("Unexpected vector type");
4831 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4834 /// getOnesVector - Returns a vector of specified type with all bits set.
4835 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4836 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4837 /// Then bitcast to their original type, ensuring they get CSE'd.
4838 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4840 assert(VT.isVector() && "Expected a vector type");
4842 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4844 if (VT.is256BitVector()) {
4845 if (HasInt256) { // AVX2
4846 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4847 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4848 array_lengthof(Ops));
4850 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4851 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4853 } else if (VT.is128BitVector()) {
4854 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4856 llvm_unreachable("Unexpected vector type");
4858 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4861 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4862 /// that point to V2 points to its first element.
4863 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4864 for (unsigned i = 0; i != NumElems; ++i) {
4865 if (Mask[i] > (int)NumElems) {
4871 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4872 /// operation of specified width.
4873 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4875 unsigned NumElems = VT.getVectorNumElements();
4876 SmallVector<int, 8> Mask;
4877 Mask.push_back(NumElems);
4878 for (unsigned i = 1; i != NumElems; ++i)
4880 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4883 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4884 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4886 unsigned NumElems = VT.getVectorNumElements();
4887 SmallVector<int, 8> Mask;
4888 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4890 Mask.push_back(i + NumElems);
4892 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4895 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4896 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4898 unsigned NumElems = VT.getVectorNumElements();
4899 SmallVector<int, 8> Mask;
4900 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4901 Mask.push_back(i + Half);
4902 Mask.push_back(i + NumElems + Half);
4904 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4907 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4908 // a generic shuffle instruction because the target has no such instructions.
4909 // Generate shuffles which repeat i16 and i8 several times until they can be
4910 // represented by v4f32 and then be manipulated by target suported shuffles.
4911 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4912 MVT VT = V.getSimpleValueType();
4913 int NumElems = VT.getVectorNumElements();
4916 while (NumElems > 4) {
4917 if (EltNo < NumElems/2) {
4918 V = getUnpackl(DAG, dl, VT, V, V);
4920 V = getUnpackh(DAG, dl, VT, V, V);
4921 EltNo -= NumElems/2;
4928 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4929 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4930 MVT VT = V.getSimpleValueType();
4933 if (VT.is128BitVector()) {
4934 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4935 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4936 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4938 } else if (VT.is256BitVector()) {
4939 // To use VPERMILPS to splat scalars, the second half of indicies must
4940 // refer to the higher part, which is a duplication of the lower one,
4941 // because VPERMILPS can only handle in-lane permutations.
4942 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4943 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4945 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4946 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4949 llvm_unreachable("Vector size not supported");
4951 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4954 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4955 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4956 MVT SrcVT = SV->getSimpleValueType(0);
4957 SDValue V1 = SV->getOperand(0);
4960 int EltNo = SV->getSplatIndex();
4961 int NumElems = SrcVT.getVectorNumElements();
4962 bool Is256BitVec = SrcVT.is256BitVector();
4964 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4965 "Unknown how to promote splat for type");
4967 // Extract the 128-bit part containing the splat element and update
4968 // the splat element index when it refers to the higher register.
4970 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4971 if (EltNo >= NumElems/2)
4972 EltNo -= NumElems/2;
4975 // All i16 and i8 vector types can't be used directly by a generic shuffle
4976 // instruction because the target has no such instruction. Generate shuffles
4977 // which repeat i16 and i8 several times until they fit in i32, and then can
4978 // be manipulated by target suported shuffles.
4979 MVT EltVT = SrcVT.getVectorElementType();
4980 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4981 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4983 // Recreate the 256-bit vector and place the same 128-bit vector
4984 // into the low and high part. This is necessary because we want
4985 // to use VPERM* to shuffle the vectors
4987 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4990 return getLegalSplat(DAG, V1, EltNo);
4993 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4994 /// vector of zero or undef vector. This produces a shuffle where the low
4995 /// element of V2 is swizzled into the zero/undef vector, landing at element
4996 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4997 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4999 const X86Subtarget *Subtarget,
5000 SelectionDAG &DAG) {
5001 MVT VT = V2.getSimpleValueType();
5003 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5004 unsigned NumElems = VT.getVectorNumElements();
5005 SmallVector<int, 16> MaskVec;
5006 for (unsigned i = 0; i != NumElems; ++i)
5007 // If this is the insertion idx, put the low elt of V2 here.
5008 MaskVec.push_back(i == Idx ? NumElems : i);
5009 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5012 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5013 /// target specific opcode. Returns true if the Mask could be calculated.
5014 /// Sets IsUnary to true if only uses one source.
5015 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5016 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5017 unsigned NumElems = VT.getVectorNumElements();
5021 switch(N->getOpcode()) {
5023 ImmN = N->getOperand(N->getNumOperands()-1);
5024 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5026 case X86ISD::UNPCKH:
5027 DecodeUNPCKHMask(VT, Mask);
5029 case X86ISD::UNPCKL:
5030 DecodeUNPCKLMask(VT, Mask);
5032 case X86ISD::MOVHLPS:
5033 DecodeMOVHLPSMask(NumElems, Mask);
5035 case X86ISD::MOVLHPS:
5036 DecodeMOVLHPSMask(NumElems, Mask);
5038 case X86ISD::PALIGNR:
5039 ImmN = N->getOperand(N->getNumOperands()-1);
5040 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5042 case X86ISD::PSHUFD:
5043 case X86ISD::VPERMILP:
5044 ImmN = N->getOperand(N->getNumOperands()-1);
5045 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5048 case X86ISD::PSHUFHW:
5049 ImmN = N->getOperand(N->getNumOperands()-1);
5050 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5053 case X86ISD::PSHUFLW:
5054 ImmN = N->getOperand(N->getNumOperands()-1);
5055 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5058 case X86ISD::VPERMI:
5059 ImmN = N->getOperand(N->getNumOperands()-1);
5060 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5064 case X86ISD::MOVSD: {
5065 // The index 0 always comes from the first element of the second source,
5066 // this is why MOVSS and MOVSD are used in the first place. The other
5067 // elements come from the other positions of the first source vector
5068 Mask.push_back(NumElems);
5069 for (unsigned i = 1; i != NumElems; ++i) {
5074 case X86ISD::VPERM2X128:
5075 ImmN = N->getOperand(N->getNumOperands()-1);
5076 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5077 if (Mask.empty()) return false;
5079 case X86ISD::MOVDDUP:
5080 case X86ISD::MOVLHPD:
5081 case X86ISD::MOVLPD:
5082 case X86ISD::MOVLPS:
5083 case X86ISD::MOVSHDUP:
5084 case X86ISD::MOVSLDUP:
5085 // Not yet implemented
5087 default: llvm_unreachable("unknown target shuffle node");
5093 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5094 /// element of the result of the vector shuffle.
5095 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5098 return SDValue(); // Limit search depth.
5100 SDValue V = SDValue(N, 0);
5101 EVT VT = V.getValueType();
5102 unsigned Opcode = V.getOpcode();
5104 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5105 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5106 int Elt = SV->getMaskElt(Index);
5109 return DAG.getUNDEF(VT.getVectorElementType());
5111 unsigned NumElems = VT.getVectorNumElements();
5112 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5113 : SV->getOperand(1);
5114 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5117 // Recurse into target specific vector shuffles to find scalars.
5118 if (isTargetShuffle(Opcode)) {
5119 MVT ShufVT = V.getSimpleValueType();
5120 unsigned NumElems = ShufVT.getVectorNumElements();
5121 SmallVector<int, 16> ShuffleMask;
5124 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5127 int Elt = ShuffleMask[Index];
5129 return DAG.getUNDEF(ShufVT.getVectorElementType());
5131 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5133 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5137 // Actual nodes that may contain scalar elements
5138 if (Opcode == ISD::BITCAST) {
5139 V = V.getOperand(0);
5140 EVT SrcVT = V.getValueType();
5141 unsigned NumElems = VT.getVectorNumElements();
5143 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5147 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5148 return (Index == 0) ? V.getOperand(0)
5149 : DAG.getUNDEF(VT.getVectorElementType());
5151 if (V.getOpcode() == ISD::BUILD_VECTOR)
5152 return V.getOperand(Index);
5157 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5158 /// shuffle operation which come from a consecutively from a zero. The
5159 /// search can start in two different directions, from left or right.
5160 /// We count undefs as zeros until PreferredNum is reached.
5161 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5162 unsigned NumElems, bool ZerosFromLeft,
5164 unsigned PreferredNum = -1U) {
5165 unsigned NumZeros = 0;
5166 for (unsigned i = 0; i != NumElems; ++i) {
5167 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5168 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5172 if (X86::isZeroNode(Elt))
5174 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5175 NumZeros = std::min(NumZeros + 1, PreferredNum);
5183 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5184 /// correspond consecutively to elements from one of the vector operands,
5185 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5187 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5188 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5189 unsigned NumElems, unsigned &OpNum) {
5190 bool SeenV1 = false;
5191 bool SeenV2 = false;
5193 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5194 int Idx = SVOp->getMaskElt(i);
5195 // Ignore undef indicies
5199 if (Idx < (int)NumElems)
5204 // Only accept consecutive elements from the same vector
5205 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5209 OpNum = SeenV1 ? 0 : 1;
5213 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5214 /// logical left shift of a vector.
5215 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5216 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5218 SVOp->getSimpleValueType(0).getVectorNumElements();
5219 unsigned NumZeros = getNumOfConsecutiveZeros(
5220 SVOp, NumElems, false /* check zeros from right */, DAG,
5221 SVOp->getMaskElt(0));
5227 // Considering the elements in the mask that are not consecutive zeros,
5228 // check if they consecutively come from only one of the source vectors.
5230 // V1 = {X, A, B, C} 0
5232 // vector_shuffle V1, V2 <1, 2, 3, X>
5234 if (!isShuffleMaskConsecutive(SVOp,
5235 0, // Mask Start Index
5236 NumElems-NumZeros, // Mask End Index(exclusive)
5237 NumZeros, // Where to start looking in the src vector
5238 NumElems, // Number of elements in vector
5239 OpSrc)) // Which source operand ?
5244 ShVal = SVOp->getOperand(OpSrc);
5248 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5249 /// logical left shift of a vector.
5250 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5251 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5253 SVOp->getSimpleValueType(0).getVectorNumElements();
5254 unsigned NumZeros = getNumOfConsecutiveZeros(
5255 SVOp, NumElems, true /* check zeros from left */, DAG,
5256 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5262 // Considering the elements in the mask that are not consecutive zeros,
5263 // check if they consecutively come from only one of the source vectors.
5265 // 0 { A, B, X, X } = V2
5267 // vector_shuffle V1, V2 <X, X, 4, 5>
5269 if (!isShuffleMaskConsecutive(SVOp,
5270 NumZeros, // Mask Start Index
5271 NumElems, // Mask End Index(exclusive)
5272 0, // Where to start looking in the src vector
5273 NumElems, // Number of elements in vector
5274 OpSrc)) // Which source operand ?
5279 ShVal = SVOp->getOperand(OpSrc);
5283 /// isVectorShift - Returns true if the shuffle can be implemented as a
5284 /// logical left or right shift of a vector.
5285 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5286 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5287 // Although the logic below support any bitwidth size, there are no
5288 // shift instructions which handle more than 128-bit vectors.
5289 if (!SVOp->getSimpleValueType(0).is128BitVector())
5292 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5293 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5299 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5301 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5302 unsigned NumNonZero, unsigned NumZero,
5304 const X86Subtarget* Subtarget,
5305 const TargetLowering &TLI) {
5312 for (unsigned i = 0; i < 16; ++i) {
5313 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5314 if (ThisIsNonZero && First) {
5316 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5318 V = DAG.getUNDEF(MVT::v8i16);
5323 SDValue ThisElt(0, 0), LastElt(0, 0);
5324 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5325 if (LastIsNonZero) {
5326 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5327 MVT::i16, Op.getOperand(i-1));
5329 if (ThisIsNonZero) {
5330 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5331 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5332 ThisElt, DAG.getConstant(8, MVT::i8));
5334 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5338 if (ThisElt.getNode())
5339 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5340 DAG.getIntPtrConstant(i/2));
5344 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5347 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5349 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5350 unsigned NumNonZero, unsigned NumZero,
5352 const X86Subtarget* Subtarget,
5353 const TargetLowering &TLI) {
5360 for (unsigned i = 0; i < 8; ++i) {
5361 bool isNonZero = (NonZeros & (1 << i)) != 0;
5365 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5367 V = DAG.getUNDEF(MVT::v8i16);
5370 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5371 MVT::v8i16, V, Op.getOperand(i),
5372 DAG.getIntPtrConstant(i));
5379 /// getVShift - Return a vector logical shift node.
5381 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5382 unsigned NumBits, SelectionDAG &DAG,
5383 const TargetLowering &TLI, SDLoc dl) {
5384 assert(VT.is128BitVector() && "Unknown type for VShift");
5385 EVT ShVT = MVT::v2i64;
5386 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5387 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5388 return DAG.getNode(ISD::BITCAST, dl, VT,
5389 DAG.getNode(Opc, dl, ShVT, SrcOp,
5390 DAG.getConstant(NumBits,
5391 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5395 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5397 // Check if the scalar load can be widened into a vector load. And if
5398 // the address is "base + cst" see if the cst can be "absorbed" into
5399 // the shuffle mask.
5400 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5401 SDValue Ptr = LD->getBasePtr();
5402 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5404 EVT PVT = LD->getValueType(0);
5405 if (PVT != MVT::i32 && PVT != MVT::f32)
5410 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5411 FI = FINode->getIndex();
5413 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5414 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5415 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5416 Offset = Ptr.getConstantOperandVal(1);
5417 Ptr = Ptr.getOperand(0);
5422 // FIXME: 256-bit vector instructions don't require a strict alignment,
5423 // improve this code to support it better.
5424 unsigned RequiredAlign = VT.getSizeInBits()/8;
5425 SDValue Chain = LD->getChain();
5426 // Make sure the stack object alignment is at least 16 or 32.
5427 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5428 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5429 if (MFI->isFixedObjectIndex(FI)) {
5430 // Can't change the alignment. FIXME: It's possible to compute
5431 // the exact stack offset and reference FI + adjust offset instead.
5432 // If someone *really* cares about this. That's the way to implement it.
5435 MFI->setObjectAlignment(FI, RequiredAlign);
5439 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5440 // Ptr + (Offset & ~15).
5443 if ((Offset % RequiredAlign) & 3)
5445 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5447 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5448 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5450 int EltNo = (Offset - StartOffset) >> 2;
5451 unsigned NumElems = VT.getVectorNumElements();
5453 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5454 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5455 LD->getPointerInfo().getWithOffset(StartOffset),
5456 false, false, false, 0);
5458 SmallVector<int, 8> Mask;
5459 for (unsigned i = 0; i != NumElems; ++i)
5460 Mask.push_back(EltNo);
5462 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5468 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5469 /// vector of type 'VT', see if the elements can be replaced by a single large
5470 /// load which has the same value as a build_vector whose operands are 'elts'.
5472 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5474 /// FIXME: we'd also like to handle the case where the last elements are zero
5475 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5476 /// There's even a handy isZeroNode for that purpose.
5477 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5478 SDLoc &DL, SelectionDAG &DAG,
5479 bool isAfterLegalize) {
5480 EVT EltVT = VT.getVectorElementType();
5481 unsigned NumElems = Elts.size();
5483 LoadSDNode *LDBase = NULL;
5484 unsigned LastLoadedElt = -1U;
5486 // For each element in the initializer, see if we've found a load or an undef.
5487 // If we don't find an initial load element, or later load elements are
5488 // non-consecutive, bail out.
5489 for (unsigned i = 0; i < NumElems; ++i) {
5490 SDValue Elt = Elts[i];
5492 if (!Elt.getNode() ||
5493 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5496 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5498 LDBase = cast<LoadSDNode>(Elt.getNode());
5502 if (Elt.getOpcode() == ISD::UNDEF)
5505 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5506 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5511 // If we have found an entire vector of loads and undefs, then return a large
5512 // load of the entire vector width starting at the base pointer. If we found
5513 // consecutive loads for the low half, generate a vzext_load node.
5514 if (LastLoadedElt == NumElems - 1) {
5516 if (isAfterLegalize &&
5517 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5520 SDValue NewLd = SDValue();
5522 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5523 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5524 LDBase->getPointerInfo(),
5525 LDBase->isVolatile(), LDBase->isNonTemporal(),
5526 LDBase->isInvariant(), 0);
5527 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5528 LDBase->getPointerInfo(),
5529 LDBase->isVolatile(), LDBase->isNonTemporal(),
5530 LDBase->isInvariant(), LDBase->getAlignment());
5532 if (LDBase->hasAnyUseOfValue(1)) {
5533 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5535 SDValue(NewLd.getNode(), 1));
5536 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5537 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5538 SDValue(NewLd.getNode(), 1));
5543 if (NumElems == 4 && LastLoadedElt == 1 &&
5544 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5545 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5546 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5548 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5549 array_lengthof(Ops), MVT::i64,
5550 LDBase->getPointerInfo(),
5551 LDBase->getAlignment(),
5552 false/*isVolatile*/, true/*ReadMem*/,
5555 // Make sure the newly-created LOAD is in the same position as LDBase in
5556 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5557 // update uses of LDBase's output chain to use the TokenFactor.
5558 if (LDBase->hasAnyUseOfValue(1)) {
5559 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5560 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5561 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5562 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5563 SDValue(ResNode.getNode(), 1));
5566 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5571 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5572 /// to generate a splat value for the following cases:
5573 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5574 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5575 /// a scalar load, or a constant.
5576 /// The VBROADCAST node is returned when a pattern is found,
5577 /// or SDValue() otherwise.
5578 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5579 SelectionDAG &DAG) {
5580 if (!Subtarget->hasFp256())
5583 MVT VT = Op.getSimpleValueType();
5586 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5587 "Unsupported vector type for broadcast.");
5592 switch (Op.getOpcode()) {
5594 // Unknown pattern found.
5597 case ISD::BUILD_VECTOR: {
5598 // The BUILD_VECTOR node must be a splat.
5599 if (!isSplatVector(Op.getNode()))
5602 Ld = Op.getOperand(0);
5603 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5604 Ld.getOpcode() == ISD::ConstantFP);
5606 // The suspected load node has several users. Make sure that all
5607 // of its users are from the BUILD_VECTOR node.
5608 // Constants may have multiple users.
5609 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5614 case ISD::VECTOR_SHUFFLE: {
5615 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5617 // Shuffles must have a splat mask where the first element is
5619 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5622 SDValue Sc = Op.getOperand(0);
5623 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5624 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5626 if (!Subtarget->hasInt256())
5629 // Use the register form of the broadcast instruction available on AVX2.
5630 if (VT.getSizeInBits() >= 256)
5631 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5632 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5635 Ld = Sc.getOperand(0);
5636 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5637 Ld.getOpcode() == ISD::ConstantFP);
5639 // The scalar_to_vector node and the suspected
5640 // load node must have exactly one user.
5641 // Constants may have multiple users.
5643 // AVX-512 has register version of the broadcast
5644 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5645 Ld.getValueType().getSizeInBits() >= 32;
5646 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5653 bool IsGE256 = (VT.getSizeInBits() >= 256);
5655 // Handle the broadcasting a single constant scalar from the constant pool
5656 // into a vector. On Sandybridge it is still better to load a constant vector
5657 // from the constant pool and not to broadcast it from a scalar.
5658 if (ConstSplatVal && Subtarget->hasInt256()) {
5659 EVT CVT = Ld.getValueType();
5660 assert(!CVT.isVector() && "Must not broadcast a vector type");
5661 unsigned ScalarSize = CVT.getSizeInBits();
5663 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5664 const Constant *C = 0;
5665 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5666 C = CI->getConstantIntValue();
5667 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5668 C = CF->getConstantFPValue();
5670 assert(C && "Invalid constant type");
5672 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5673 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5674 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5675 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5676 MachinePointerInfo::getConstantPool(),
5677 false, false, false, Alignment);
5679 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5683 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5684 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5686 // Handle AVX2 in-register broadcasts.
5687 if (!IsLoad && Subtarget->hasInt256() &&
5688 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5689 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5691 // The scalar source must be a normal load.
5695 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5696 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5698 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5699 // double since there is no vbroadcastsd xmm
5700 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5701 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5702 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5705 // Unsupported broadcast.
5709 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5710 MVT VT = Op.getSimpleValueType();
5712 // Skip if insert_vec_elt is not supported.
5713 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5714 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5718 unsigned NumElems = Op.getNumOperands();
5722 SmallVector<unsigned, 4> InsertIndices;
5723 SmallVector<int, 8> Mask(NumElems, -1);
5725 for (unsigned i = 0; i != NumElems; ++i) {
5726 unsigned Opc = Op.getOperand(i).getOpcode();
5728 if (Opc == ISD::UNDEF)
5731 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5732 // Quit if more than 1 elements need inserting.
5733 if (InsertIndices.size() > 1)
5736 InsertIndices.push_back(i);
5740 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5741 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5743 // Quit if extracted from vector of different type.
5744 if (ExtractedFromVec.getValueType() != VT)
5747 // Quit if non-constant index.
5748 if (!isa<ConstantSDNode>(ExtIdx))
5751 if (VecIn1.getNode() == 0)
5752 VecIn1 = ExtractedFromVec;
5753 else if (VecIn1 != ExtractedFromVec) {
5754 if (VecIn2.getNode() == 0)
5755 VecIn2 = ExtractedFromVec;
5756 else if (VecIn2 != ExtractedFromVec)
5757 // Quit if more than 2 vectors to shuffle
5761 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5763 if (ExtractedFromVec == VecIn1)
5765 else if (ExtractedFromVec == VecIn2)
5766 Mask[i] = Idx + NumElems;
5769 if (VecIn1.getNode() == 0)
5772 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5773 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5774 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5775 unsigned Idx = InsertIndices[i];
5776 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5777 DAG.getIntPtrConstant(Idx));
5783 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5785 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5787 MVT VT = Op.getSimpleValueType();
5788 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5789 "Unexpected type in LowerBUILD_VECTORvXi1!");
5792 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5793 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5794 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5795 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5796 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5797 Ops, VT.getVectorNumElements());
5800 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5801 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5802 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5803 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5804 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5805 Ops, VT.getVectorNumElements());
5808 bool AllContants = true;
5809 uint64_t Immediate = 0;
5810 int NonConstIdx = -1;
5811 bool IsSplat = true;
5812 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5813 SDValue In = Op.getOperand(idx);
5814 if (In.getOpcode() == ISD::UNDEF)
5816 if (!isa<ConstantSDNode>(In)) {
5817 AllContants = false;
5820 else if (cast<ConstantSDNode>(In)->getZExtValue())
5821 Immediate |= (1ULL << idx);
5822 if (In != Op.getOperand(0))
5827 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5828 DAG.getConstant(Immediate, MVT::i16));
5829 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5830 DAG.getIntPtrConstant(0));
5833 if (!IsSplat && (NonConstIdx != 0))
5834 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5835 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5838 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5839 DAG.getConstant(-1, SelectVT),
5840 DAG.getConstant(0, SelectVT));
5842 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5843 DAG.getConstant((Immediate | 1), SelectVT),
5844 DAG.getConstant(Immediate, SelectVT));
5845 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5849 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5852 MVT VT = Op.getSimpleValueType();
5853 MVT ExtVT = VT.getVectorElementType();
5854 unsigned NumElems = Op.getNumOperands();
5856 // Generate vectors for predicate vectors.
5857 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5858 return LowerBUILD_VECTORvXi1(Op, DAG);
5860 // Vectors containing all zeros can be matched by pxor and xorps later
5861 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5862 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5863 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5864 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5867 return getZeroVector(VT, Subtarget, DAG, dl);
5870 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5871 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5872 // vpcmpeqd on 256-bit vectors.
5873 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5874 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5877 if (!VT.is512BitVector())
5878 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5881 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5882 if (Broadcast.getNode())
5885 unsigned EVTBits = ExtVT.getSizeInBits();
5887 unsigned NumZero = 0;
5888 unsigned NumNonZero = 0;
5889 unsigned NonZeros = 0;
5890 bool IsAllConstants = true;
5891 SmallSet<SDValue, 8> Values;
5892 for (unsigned i = 0; i < NumElems; ++i) {
5893 SDValue Elt = Op.getOperand(i);
5894 if (Elt.getOpcode() == ISD::UNDEF)
5897 if (Elt.getOpcode() != ISD::Constant &&
5898 Elt.getOpcode() != ISD::ConstantFP)
5899 IsAllConstants = false;
5900 if (X86::isZeroNode(Elt))
5903 NonZeros |= (1 << i);
5908 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5909 if (NumNonZero == 0)
5910 return DAG.getUNDEF(VT);
5912 // Special case for single non-zero, non-undef, element.
5913 if (NumNonZero == 1) {
5914 unsigned Idx = countTrailingZeros(NonZeros);
5915 SDValue Item = Op.getOperand(Idx);
5917 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5918 // the value are obviously zero, truncate the value to i32 and do the
5919 // insertion that way. Only do this if the value is non-constant or if the
5920 // value is a constant being inserted into element 0. It is cheaper to do
5921 // a constant pool load than it is to do a movd + shuffle.
5922 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5923 (!IsAllConstants || Idx == 0)) {
5924 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5926 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5927 EVT VecVT = MVT::v4i32;
5928 unsigned VecElts = 4;
5930 // Truncate the value (which may itself be a constant) to i32, and
5931 // convert it to a vector with movd (S2V+shuffle to zero extend).
5932 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5933 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5934 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5936 // Now we have our 32-bit value zero extended in the low element of
5937 // a vector. If Idx != 0, swizzle it into place.
5939 SmallVector<int, 4> Mask;
5940 Mask.push_back(Idx);
5941 for (unsigned i = 1; i != VecElts; ++i)
5943 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5946 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5950 // If we have a constant or non-constant insertion into the low element of
5951 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5952 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5953 // depending on what the source datatype is.
5956 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5958 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5959 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5960 if (VT.is256BitVector() || VT.is512BitVector()) {
5961 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5962 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5963 Item, DAG.getIntPtrConstant(0));
5965 assert(VT.is128BitVector() && "Expected an SSE value type!");
5966 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5967 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5968 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5971 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5972 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5973 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5974 if (VT.is256BitVector()) {
5975 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5976 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5978 assert(VT.is128BitVector() && "Expected an SSE value type!");
5979 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5981 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5985 // Is it a vector logical left shift?
5986 if (NumElems == 2 && Idx == 1 &&
5987 X86::isZeroNode(Op.getOperand(0)) &&
5988 !X86::isZeroNode(Op.getOperand(1))) {
5989 unsigned NumBits = VT.getSizeInBits();
5990 return getVShift(true, VT,
5991 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5992 VT, Op.getOperand(1)),
5993 NumBits/2, DAG, *this, dl);
5996 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5999 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6000 // is a non-constant being inserted into an element other than the low one,
6001 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6002 // movd/movss) to move this into the low element, then shuffle it into
6004 if (EVTBits == 32) {
6005 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6007 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6008 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6009 SmallVector<int, 8> MaskVec;
6010 for (unsigned i = 0; i != NumElems; ++i)
6011 MaskVec.push_back(i == Idx ? 0 : 1);
6012 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6016 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6017 if (Values.size() == 1) {
6018 if (EVTBits == 32) {
6019 // Instead of a shuffle like this:
6020 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6021 // Check if it's possible to issue this instead.
6022 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6023 unsigned Idx = countTrailingZeros(NonZeros);
6024 SDValue Item = Op.getOperand(Idx);
6025 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6026 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6031 // A vector full of immediates; various special cases are already
6032 // handled, so this is best done with a single constant-pool load.
6036 // For AVX-length vectors, build the individual 128-bit pieces and use
6037 // shuffles to put them in place.
6038 if (VT.is256BitVector() || VT.is512BitVector()) {
6039 SmallVector<SDValue, 64> V;
6040 for (unsigned i = 0; i != NumElems; ++i)
6041 V.push_back(Op.getOperand(i));
6043 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6045 // Build both the lower and upper subvector.
6046 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6047 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6050 // Recreate the wider vector with the lower and upper part.
6051 if (VT.is256BitVector())
6052 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6053 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6056 // Let legalizer expand 2-wide build_vectors.
6057 if (EVTBits == 64) {
6058 if (NumNonZero == 1) {
6059 // One half is zero or undef.
6060 unsigned Idx = countTrailingZeros(NonZeros);
6061 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6062 Op.getOperand(Idx));
6063 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6068 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6069 if (EVTBits == 8 && NumElems == 16) {
6070 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6072 if (V.getNode()) return V;
6075 if (EVTBits == 16 && NumElems == 8) {
6076 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6078 if (V.getNode()) return V;
6081 // If element VT is == 32 bits, turn it into a number of shuffles.
6082 SmallVector<SDValue, 8> V(NumElems);
6083 if (NumElems == 4 && NumZero > 0) {
6084 for (unsigned i = 0; i < 4; ++i) {
6085 bool isZero = !(NonZeros & (1 << i));
6087 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6089 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6092 for (unsigned i = 0; i < 2; ++i) {
6093 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6096 V[i] = V[i*2]; // Must be a zero vector.
6099 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6102 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6105 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6110 bool Reverse1 = (NonZeros & 0x3) == 2;
6111 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6115 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6116 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6118 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6121 if (Values.size() > 1 && VT.is128BitVector()) {
6122 // Check for a build vector of consecutive loads.
6123 for (unsigned i = 0; i < NumElems; ++i)
6124 V[i] = Op.getOperand(i);
6126 // Check for elements which are consecutive loads.
6127 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6131 // Check for a build vector from mostly shuffle plus few inserting.
6132 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6136 // For SSE 4.1, use insertps to put the high elements into the low element.
6137 if (getSubtarget()->hasSSE41()) {
6139 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6140 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6142 Result = DAG.getUNDEF(VT);
6144 for (unsigned i = 1; i < NumElems; ++i) {
6145 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6146 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6147 Op.getOperand(i), DAG.getIntPtrConstant(i));
6152 // Otherwise, expand into a number of unpckl*, start by extending each of
6153 // our (non-undef) elements to the full vector width with the element in the
6154 // bottom slot of the vector (which generates no code for SSE).
6155 for (unsigned i = 0; i < NumElems; ++i) {
6156 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6157 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6159 V[i] = DAG.getUNDEF(VT);
6162 // Next, we iteratively mix elements, e.g. for v4f32:
6163 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6164 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6165 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6166 unsigned EltStride = NumElems >> 1;
6167 while (EltStride != 0) {
6168 for (unsigned i = 0; i < EltStride; ++i) {
6169 // If V[i+EltStride] is undef and this is the first round of mixing,
6170 // then it is safe to just drop this shuffle: V[i] is already in the
6171 // right place, the one element (since it's the first round) being
6172 // inserted as undef can be dropped. This isn't safe for successive
6173 // rounds because they will permute elements within both vectors.
6174 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6175 EltStride == NumElems/2)
6178 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6187 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6188 // to create 256-bit vectors from two other 128-bit ones.
6189 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6191 MVT ResVT = Op.getSimpleValueType();
6193 assert((ResVT.is256BitVector() ||
6194 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6196 SDValue V1 = Op.getOperand(0);
6197 SDValue V2 = Op.getOperand(1);
6198 unsigned NumElems = ResVT.getVectorNumElements();
6199 if(ResVT.is256BitVector())
6200 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6202 if (Op.getNumOperands() == 4) {
6203 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6204 ResVT.getVectorNumElements()/2);
6205 SDValue V3 = Op.getOperand(2);
6206 SDValue V4 = Op.getOperand(3);
6207 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6208 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6210 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6213 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6214 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6215 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6216 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6217 Op.getNumOperands() == 4)));
6219 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6220 // from two other 128-bit ones.
6222 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6223 return LowerAVXCONCAT_VECTORS(Op, DAG);
6226 // Try to lower a shuffle node into a simple blend instruction.
6228 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6229 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6230 SDValue V1 = SVOp->getOperand(0);
6231 SDValue V2 = SVOp->getOperand(1);
6233 MVT VT = SVOp->getSimpleValueType(0);
6234 MVT EltVT = VT.getVectorElementType();
6235 unsigned NumElems = VT.getVectorNumElements();
6237 // There is no blend with immediate in AVX-512.
6238 if (VT.is512BitVector())
6241 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6243 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6246 // Check the mask for BLEND and build the value.
6247 unsigned MaskValue = 0;
6248 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6249 unsigned NumLanes = (NumElems-1)/8 + 1;
6250 unsigned NumElemsInLane = NumElems / NumLanes;
6252 // Blend for v16i16 should be symetric for the both lanes.
6253 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6255 int SndLaneEltIdx = (NumLanes == 2) ?
6256 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6257 int EltIdx = SVOp->getMaskElt(i);
6259 if ((EltIdx < 0 || EltIdx == (int)i) &&
6260 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6263 if (((unsigned)EltIdx == (i + NumElems)) &&
6264 (SndLaneEltIdx < 0 ||
6265 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6266 MaskValue |= (1<<i);
6271 // Convert i32 vectors to floating point if it is not AVX2.
6272 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6274 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6275 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6277 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6278 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6281 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6282 DAG.getConstant(MaskValue, MVT::i32));
6283 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6286 /// In vector type \p VT, return true if the element at index \p InputIdx
6287 /// falls on a different 128-bit lane than \p OutputIdx.
6288 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6289 unsigned OutputIdx) {
6290 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6291 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6294 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6295 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6296 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6297 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6299 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6300 SelectionDAG &DAG) {
6301 MVT VT = V1.getSimpleValueType();
6302 assert(VT.is128BitVector() || VT.is256BitVector());
6304 MVT EltVT = VT.getVectorElementType();
6305 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6306 unsigned NumElts = VT.getVectorNumElements();
6308 SmallVector<SDValue, 32> PshufbMask;
6309 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6310 int InputIdx = MaskVals[OutputIdx];
6311 unsigned InputByteIdx;
6313 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6314 InputByteIdx = 0x80;
6316 // Cross lane is not allowed.
6317 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6319 InputByteIdx = InputIdx * EltSizeInBytes;
6320 // Index is an byte offset within the 128-bit lane.
6321 InputByteIdx &= 0xf;
6324 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6325 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6326 if (InputByteIdx != 0x80)
6331 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6333 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6334 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6335 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6336 PshufbMask.data(), PshufbMask.size()));
6339 // v8i16 shuffles - Prefer shuffles in the following order:
6340 // 1. [all] pshuflw, pshufhw, optional move
6341 // 2. [ssse3] 1 x pshufb
6342 // 3. [ssse3] 2 x pshufb + 1 x por
6343 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6345 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6346 SelectionDAG &DAG) {
6347 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6348 SDValue V1 = SVOp->getOperand(0);
6349 SDValue V2 = SVOp->getOperand(1);
6351 SmallVector<int, 8> MaskVals;
6353 // Determine if more than 1 of the words in each of the low and high quadwords
6354 // of the result come from the same quadword of one of the two inputs. Undef
6355 // mask values count as coming from any quadword, for better codegen.
6357 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6358 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6359 unsigned LoQuad[] = { 0, 0, 0, 0 };
6360 unsigned HiQuad[] = { 0, 0, 0, 0 };
6361 // Indices of quads used.
6362 std::bitset<4> InputQuads;
6363 for (unsigned i = 0; i < 8; ++i) {
6364 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6365 int EltIdx = SVOp->getMaskElt(i);
6366 MaskVals.push_back(EltIdx);
6375 InputQuads.set(EltIdx / 4);
6378 int BestLoQuad = -1;
6379 unsigned MaxQuad = 1;
6380 for (unsigned i = 0; i < 4; ++i) {
6381 if (LoQuad[i] > MaxQuad) {
6383 MaxQuad = LoQuad[i];
6387 int BestHiQuad = -1;
6389 for (unsigned i = 0; i < 4; ++i) {
6390 if (HiQuad[i] > MaxQuad) {
6392 MaxQuad = HiQuad[i];
6396 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6397 // of the two input vectors, shuffle them into one input vector so only a
6398 // single pshufb instruction is necessary. If there are more than 2 input
6399 // quads, disable the next transformation since it does not help SSSE3.
6400 bool V1Used = InputQuads[0] || InputQuads[1];
6401 bool V2Used = InputQuads[2] || InputQuads[3];
6402 if (Subtarget->hasSSSE3()) {
6403 if (InputQuads.count() == 2 && V1Used && V2Used) {
6404 BestLoQuad = InputQuads[0] ? 0 : 1;
6405 BestHiQuad = InputQuads[2] ? 2 : 3;
6407 if (InputQuads.count() > 2) {
6413 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6414 // the shuffle mask. If a quad is scored as -1, that means that it contains
6415 // words from all 4 input quadwords.
6417 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6419 BestLoQuad < 0 ? 0 : BestLoQuad,
6420 BestHiQuad < 0 ? 1 : BestHiQuad
6422 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6423 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6424 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6425 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6427 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6428 // source words for the shuffle, to aid later transformations.
6429 bool AllWordsInNewV = true;
6430 bool InOrder[2] = { true, true };
6431 for (unsigned i = 0; i != 8; ++i) {
6432 int idx = MaskVals[i];
6434 InOrder[i/4] = false;
6435 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6437 AllWordsInNewV = false;
6441 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6442 if (AllWordsInNewV) {
6443 for (int i = 0; i != 8; ++i) {
6444 int idx = MaskVals[i];
6447 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6448 if ((idx != i) && idx < 4)
6450 if ((idx != i) && idx > 3)
6459 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6460 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6461 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6462 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6463 unsigned TargetMask = 0;
6464 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6465 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6466 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6467 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6468 getShufflePSHUFLWImmediate(SVOp);
6469 V1 = NewV.getOperand(0);
6470 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6474 // Promote splats to a larger type which usually leads to more efficient code.
6475 // FIXME: Is this true if pshufb is available?
6476 if (SVOp->isSplat())
6477 return PromoteSplat(SVOp, DAG);
6479 // If we have SSSE3, and all words of the result are from 1 input vector,
6480 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6481 // is present, fall back to case 4.
6482 if (Subtarget->hasSSSE3()) {
6483 SmallVector<SDValue,16> pshufbMask;
6485 // If we have elements from both input vectors, set the high bit of the
6486 // shuffle mask element to zero out elements that come from V2 in the V1
6487 // mask, and elements that come from V1 in the V2 mask, so that the two
6488 // results can be OR'd together.
6489 bool TwoInputs = V1Used && V2Used;
6490 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6492 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6494 // Calculate the shuffle mask for the second input, shuffle it, and
6495 // OR it with the first shuffled input.
6496 CommuteVectorShuffleMask(MaskVals, 8);
6497 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6498 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6499 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6502 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6503 // and update MaskVals with new element order.
6504 std::bitset<8> InOrder;
6505 if (BestLoQuad >= 0) {
6506 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6507 for (int i = 0; i != 4; ++i) {
6508 int idx = MaskVals[i];
6511 } else if ((idx / 4) == BestLoQuad) {
6516 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6519 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6520 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6521 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6523 getShufflePSHUFLWImmediate(SVOp), DAG);
6527 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6528 // and update MaskVals with the new element order.
6529 if (BestHiQuad >= 0) {
6530 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6531 for (unsigned i = 4; i != 8; ++i) {
6532 int idx = MaskVals[i];
6535 } else if ((idx / 4) == BestHiQuad) {
6536 MaskV[i] = (idx & 3) + 4;
6540 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6543 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6544 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6545 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6547 getShufflePSHUFHWImmediate(SVOp), DAG);
6551 // In case BestHi & BestLo were both -1, which means each quadword has a word
6552 // from each of the four input quadwords, calculate the InOrder bitvector now
6553 // before falling through to the insert/extract cleanup.
6554 if (BestLoQuad == -1 && BestHiQuad == -1) {
6556 for (int i = 0; i != 8; ++i)
6557 if (MaskVals[i] < 0 || MaskVals[i] == i)
6561 // The other elements are put in the right place using pextrw and pinsrw.
6562 for (unsigned i = 0; i != 8; ++i) {
6565 int EltIdx = MaskVals[i];
6568 SDValue ExtOp = (EltIdx < 8) ?
6569 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6570 DAG.getIntPtrConstant(EltIdx)) :
6571 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6572 DAG.getIntPtrConstant(EltIdx - 8));
6573 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6574 DAG.getIntPtrConstant(i));
6579 /// \brief v16i16 shuffles
6581 /// FIXME: We only support generation of a single pshufb currently. We can
6582 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6583 /// well (e.g 2 x pshufb + 1 x por).
6585 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6586 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6587 SDValue V1 = SVOp->getOperand(0);
6588 SDValue V2 = SVOp->getOperand(1);
6591 if (V2.getOpcode() != ISD::UNDEF)
6594 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6595 return getPSHUFB(MaskVals, V1, dl, DAG);
6598 // v16i8 shuffles - Prefer shuffles in the following order:
6599 // 1. [ssse3] 1 x pshufb
6600 // 2. [ssse3] 2 x pshufb + 1 x por
6601 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6602 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6603 const X86Subtarget* Subtarget,
6604 SelectionDAG &DAG) {
6605 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6606 SDValue V1 = SVOp->getOperand(0);
6607 SDValue V2 = SVOp->getOperand(1);
6609 ArrayRef<int> MaskVals = SVOp->getMask();
6611 // Promote splats to a larger type which usually leads to more efficient code.
6612 // FIXME: Is this true if pshufb is available?
6613 if (SVOp->isSplat())
6614 return PromoteSplat(SVOp, DAG);
6616 // If we have SSSE3, case 1 is generated when all result bytes come from
6617 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6618 // present, fall back to case 3.
6620 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6621 if (Subtarget->hasSSSE3()) {
6622 SmallVector<SDValue,16> pshufbMask;
6624 // If all result elements are from one input vector, then only translate
6625 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6627 // Otherwise, we have elements from both input vectors, and must zero out
6628 // elements that come from V2 in the first mask, and V1 in the second mask
6629 // so that we can OR them together.
6630 for (unsigned i = 0; i != 16; ++i) {
6631 int EltIdx = MaskVals[i];
6632 if (EltIdx < 0 || EltIdx >= 16)
6634 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6636 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6637 DAG.getNode(ISD::BUILD_VECTOR, dl,
6638 MVT::v16i8, &pshufbMask[0], 16));
6640 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6641 // the 2nd operand if it's undefined or zero.
6642 if (V2.getOpcode() == ISD::UNDEF ||
6643 ISD::isBuildVectorAllZeros(V2.getNode()))
6646 // Calculate the shuffle mask for the second input, shuffle it, and
6647 // OR it with the first shuffled input.
6649 for (unsigned i = 0; i != 16; ++i) {
6650 int EltIdx = MaskVals[i];
6651 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6652 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6654 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6655 DAG.getNode(ISD::BUILD_VECTOR, dl,
6656 MVT::v16i8, &pshufbMask[0], 16));
6657 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6660 // No SSSE3 - Calculate in place words and then fix all out of place words
6661 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6662 // the 16 different words that comprise the two doublequadword input vectors.
6663 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6664 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6666 for (int i = 0; i != 8; ++i) {
6667 int Elt0 = MaskVals[i*2];
6668 int Elt1 = MaskVals[i*2+1];
6670 // This word of the result is all undef, skip it.
6671 if (Elt0 < 0 && Elt1 < 0)
6674 // This word of the result is already in the correct place, skip it.
6675 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6678 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6679 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6682 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6683 // using a single extract together, load it and store it.
6684 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6685 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6686 DAG.getIntPtrConstant(Elt1 / 2));
6687 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6688 DAG.getIntPtrConstant(i));
6692 // If Elt1 is defined, extract it from the appropriate source. If the
6693 // source byte is not also odd, shift the extracted word left 8 bits
6694 // otherwise clear the bottom 8 bits if we need to do an or.
6696 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6697 DAG.getIntPtrConstant(Elt1 / 2));
6698 if ((Elt1 & 1) == 0)
6699 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6701 TLI.getShiftAmountTy(InsElt.getValueType())));
6703 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6704 DAG.getConstant(0xFF00, MVT::i16));
6706 // If Elt0 is defined, extract it from the appropriate source. If the
6707 // source byte is not also even, shift the extracted word right 8 bits. If
6708 // Elt1 was also defined, OR the extracted values together before
6709 // inserting them in the result.
6711 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6712 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6713 if ((Elt0 & 1) != 0)
6714 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6716 TLI.getShiftAmountTy(InsElt0.getValueType())));
6718 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6719 DAG.getConstant(0x00FF, MVT::i16));
6720 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6723 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6724 DAG.getIntPtrConstant(i));
6726 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6729 // v32i8 shuffles - Translate to VPSHUFB if possible.
6731 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6732 const X86Subtarget *Subtarget,
6733 SelectionDAG &DAG) {
6734 MVT VT = SVOp->getSimpleValueType(0);
6735 SDValue V1 = SVOp->getOperand(0);
6736 SDValue V2 = SVOp->getOperand(1);
6738 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6740 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6741 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6742 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6744 // VPSHUFB may be generated if
6745 // (1) one of input vector is undefined or zeroinitializer.
6746 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6747 // And (2) the mask indexes don't cross the 128-bit lane.
6748 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6749 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6752 if (V1IsAllZero && !V2IsAllZero) {
6753 CommuteVectorShuffleMask(MaskVals, 32);
6756 return getPSHUFB(MaskVals, V1, dl, DAG);
6759 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6760 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6761 /// done when every pair / quad of shuffle mask elements point to elements in
6762 /// the right sequence. e.g.
6763 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6765 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6766 SelectionDAG &DAG) {
6767 MVT VT = SVOp->getSimpleValueType(0);
6769 unsigned NumElems = VT.getVectorNumElements();
6772 switch (VT.SimpleTy) {
6773 default: llvm_unreachable("Unexpected!");
6774 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6775 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6776 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6777 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6778 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6779 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6782 SmallVector<int, 8> MaskVec;
6783 for (unsigned i = 0; i != NumElems; i += Scale) {
6785 for (unsigned j = 0; j != Scale; ++j) {
6786 int EltIdx = SVOp->getMaskElt(i+j);
6790 StartIdx = (EltIdx / Scale);
6791 if (EltIdx != (int)(StartIdx*Scale + j))
6794 MaskVec.push_back(StartIdx);
6797 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6798 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6799 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6802 /// getVZextMovL - Return a zero-extending vector move low node.
6804 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6805 SDValue SrcOp, SelectionDAG &DAG,
6806 const X86Subtarget *Subtarget, SDLoc dl) {
6807 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6808 LoadSDNode *LD = NULL;
6809 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6810 LD = dyn_cast<LoadSDNode>(SrcOp);
6812 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6814 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6815 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6816 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6817 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6818 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6820 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6821 return DAG.getNode(ISD::BITCAST, dl, VT,
6822 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6823 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6831 return DAG.getNode(ISD::BITCAST, dl, VT,
6832 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6833 DAG.getNode(ISD::BITCAST, dl,
6837 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6838 /// which could not be matched by any known target speficic shuffle
6840 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6842 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6843 if (NewOp.getNode())
6846 MVT VT = SVOp->getSimpleValueType(0);
6848 unsigned NumElems = VT.getVectorNumElements();
6849 unsigned NumLaneElems = NumElems / 2;
6852 MVT EltVT = VT.getVectorElementType();
6853 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6856 SmallVector<int, 16> Mask;
6857 for (unsigned l = 0; l < 2; ++l) {
6858 // Build a shuffle mask for the output, discovering on the fly which
6859 // input vectors to use as shuffle operands (recorded in InputUsed).
6860 // If building a suitable shuffle vector proves too hard, then bail
6861 // out with UseBuildVector set.
6862 bool UseBuildVector = false;
6863 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6864 unsigned LaneStart = l * NumLaneElems;
6865 for (unsigned i = 0; i != NumLaneElems; ++i) {
6866 // The mask element. This indexes into the input.
6867 int Idx = SVOp->getMaskElt(i+LaneStart);
6869 // the mask element does not index into any input vector.
6874 // The input vector this mask element indexes into.
6875 int Input = Idx / NumLaneElems;
6877 // Turn the index into an offset from the start of the input vector.
6878 Idx -= Input * NumLaneElems;
6880 // Find or create a shuffle vector operand to hold this input.
6882 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6883 if (InputUsed[OpNo] == Input)
6884 // This input vector is already an operand.
6886 if (InputUsed[OpNo] < 0) {
6887 // Create a new operand for this input vector.
6888 InputUsed[OpNo] = Input;
6893 if (OpNo >= array_lengthof(InputUsed)) {
6894 // More than two input vectors used! Give up on trying to create a
6895 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6896 UseBuildVector = true;
6900 // Add the mask index for the new shuffle vector.
6901 Mask.push_back(Idx + OpNo * NumLaneElems);
6904 if (UseBuildVector) {
6905 SmallVector<SDValue, 16> SVOps;
6906 for (unsigned i = 0; i != NumLaneElems; ++i) {
6907 // The mask element. This indexes into the input.
6908 int Idx = SVOp->getMaskElt(i+LaneStart);
6910 SVOps.push_back(DAG.getUNDEF(EltVT));
6914 // The input vector this mask element indexes into.
6915 int Input = Idx / NumElems;
6917 // Turn the index into an offset from the start of the input vector.
6918 Idx -= Input * NumElems;
6920 // Extract the vector element by hand.
6921 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6922 SVOp->getOperand(Input),
6923 DAG.getIntPtrConstant(Idx)));
6926 // Construct the output using a BUILD_VECTOR.
6927 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6929 } else if (InputUsed[0] < 0) {
6930 // No input vectors were used! The result is undefined.
6931 Output[l] = DAG.getUNDEF(NVT);
6933 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6934 (InputUsed[0] % 2) * NumLaneElems,
6936 // If only one input was used, use an undefined vector for the other.
6937 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6938 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6939 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6940 // At least one input vector was used. Create a new shuffle vector.
6941 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6947 // Concatenate the result back
6948 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6951 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6952 /// 4 elements, and match them with several different shuffle types.
6954 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6955 SDValue V1 = SVOp->getOperand(0);
6956 SDValue V2 = SVOp->getOperand(1);
6958 MVT VT = SVOp->getSimpleValueType(0);
6960 assert(VT.is128BitVector() && "Unsupported vector size");
6962 std::pair<int, int> Locs[4];
6963 int Mask1[] = { -1, -1, -1, -1 };
6964 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6968 for (unsigned i = 0; i != 4; ++i) {
6969 int Idx = PermMask[i];
6971 Locs[i] = std::make_pair(-1, -1);
6973 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6975 Locs[i] = std::make_pair(0, NumLo);
6979 Locs[i] = std::make_pair(1, NumHi);
6981 Mask1[2+NumHi] = Idx;
6987 if (NumLo <= 2 && NumHi <= 2) {
6988 // If no more than two elements come from either vector. This can be
6989 // implemented with two shuffles. First shuffle gather the elements.
6990 // The second shuffle, which takes the first shuffle as both of its
6991 // vector operands, put the elements into the right order.
6992 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6994 int Mask2[] = { -1, -1, -1, -1 };
6996 for (unsigned i = 0; i != 4; ++i)
6997 if (Locs[i].first != -1) {
6998 unsigned Idx = (i < 2) ? 0 : 4;
6999 Idx += Locs[i].first * 2 + Locs[i].second;
7003 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7006 if (NumLo == 3 || NumHi == 3) {
7007 // Otherwise, we must have three elements from one vector, call it X, and
7008 // one element from the other, call it Y. First, use a shufps to build an
7009 // intermediate vector with the one element from Y and the element from X
7010 // that will be in the same half in the final destination (the indexes don't
7011 // matter). Then, use a shufps to build the final vector, taking the half
7012 // containing the element from Y from the intermediate, and the other half
7015 // Normalize it so the 3 elements come from V1.
7016 CommuteVectorShuffleMask(PermMask, 4);
7020 // Find the element from V2.
7022 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7023 int Val = PermMask[HiIndex];
7030 Mask1[0] = PermMask[HiIndex];
7032 Mask1[2] = PermMask[HiIndex^1];
7034 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7037 Mask1[0] = PermMask[0];
7038 Mask1[1] = PermMask[1];
7039 Mask1[2] = HiIndex & 1 ? 6 : 4;
7040 Mask1[3] = HiIndex & 1 ? 4 : 6;
7041 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7044 Mask1[0] = HiIndex & 1 ? 2 : 0;
7045 Mask1[1] = HiIndex & 1 ? 0 : 2;
7046 Mask1[2] = PermMask[2];
7047 Mask1[3] = PermMask[3];
7052 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7055 // Break it into (shuffle shuffle_hi, shuffle_lo).
7056 int LoMask[] = { -1, -1, -1, -1 };
7057 int HiMask[] = { -1, -1, -1, -1 };
7059 int *MaskPtr = LoMask;
7060 unsigned MaskIdx = 0;
7063 for (unsigned i = 0; i != 4; ++i) {
7070 int Idx = PermMask[i];
7072 Locs[i] = std::make_pair(-1, -1);
7073 } else if (Idx < 4) {
7074 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7075 MaskPtr[LoIdx] = Idx;
7078 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7079 MaskPtr[HiIdx] = Idx;
7084 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7085 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7086 int MaskOps[] = { -1, -1, -1, -1 };
7087 for (unsigned i = 0; i != 4; ++i)
7088 if (Locs[i].first != -1)
7089 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7090 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7093 static bool MayFoldVectorLoad(SDValue V) {
7094 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7095 V = V.getOperand(0);
7097 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7098 V = V.getOperand(0);
7099 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7100 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7101 // BUILD_VECTOR (load), undef
7102 V = V.getOperand(0);
7104 return MayFoldLoad(V);
7108 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7109 MVT VT = Op.getSimpleValueType();
7111 // Canonizalize to v2f64.
7112 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7113 return DAG.getNode(ISD::BITCAST, dl, VT,
7114 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7119 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7121 SDValue V1 = Op.getOperand(0);
7122 SDValue V2 = Op.getOperand(1);
7123 MVT VT = Op.getSimpleValueType();
7125 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7127 if (HasSSE2 && VT == MVT::v2f64)
7128 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7130 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7131 return DAG.getNode(ISD::BITCAST, dl, VT,
7132 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7133 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7134 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7138 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7139 SDValue V1 = Op.getOperand(0);
7140 SDValue V2 = Op.getOperand(1);
7141 MVT VT = Op.getSimpleValueType();
7143 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7144 "unsupported shuffle type");
7146 if (V2.getOpcode() == ISD::UNDEF)
7150 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7154 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7155 SDValue V1 = Op.getOperand(0);
7156 SDValue V2 = Op.getOperand(1);
7157 MVT VT = Op.getSimpleValueType();
7158 unsigned NumElems = VT.getVectorNumElements();
7160 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7161 // operand of these instructions is only memory, so check if there's a
7162 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7164 bool CanFoldLoad = false;
7166 // Trivial case, when V2 comes from a load.
7167 if (MayFoldVectorLoad(V2))
7170 // When V1 is a load, it can be folded later into a store in isel, example:
7171 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7173 // (MOVLPSmr addr:$src1, VR128:$src2)
7174 // So, recognize this potential and also use MOVLPS or MOVLPD
7175 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7178 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7180 if (HasSSE2 && NumElems == 2)
7181 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7184 // If we don't care about the second element, proceed to use movss.
7185 if (SVOp->getMaskElt(1) != -1)
7186 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7189 // movl and movlp will both match v2i64, but v2i64 is never matched by
7190 // movl earlier because we make it strict to avoid messing with the movlp load
7191 // folding logic (see the code above getMOVLP call). Match it here then,
7192 // this is horrible, but will stay like this until we move all shuffle
7193 // matching to x86 specific nodes. Note that for the 1st condition all
7194 // types are matched with movsd.
7196 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7197 // as to remove this logic from here, as much as possible
7198 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7199 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7200 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7203 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7205 // Invert the operand order and use SHUFPS to match it.
7206 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7207 getShuffleSHUFImmediate(SVOp), DAG);
7210 // Reduce a vector shuffle to zext.
7211 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7212 SelectionDAG &DAG) {
7213 // PMOVZX is only available from SSE41.
7214 if (!Subtarget->hasSSE41())
7217 MVT VT = Op.getSimpleValueType();
7219 // Only AVX2 support 256-bit vector integer extending.
7220 if (!Subtarget->hasInt256() && VT.is256BitVector())
7223 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7225 SDValue V1 = Op.getOperand(0);
7226 SDValue V2 = Op.getOperand(1);
7227 unsigned NumElems = VT.getVectorNumElements();
7229 // Extending is an unary operation and the element type of the source vector
7230 // won't be equal to or larger than i64.
7231 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7232 VT.getVectorElementType() == MVT::i64)
7235 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7236 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7237 while ((1U << Shift) < NumElems) {
7238 if (SVOp->getMaskElt(1U << Shift) == 1)
7241 // The maximal ratio is 8, i.e. from i8 to i64.
7246 // Check the shuffle mask.
7247 unsigned Mask = (1U << Shift) - 1;
7248 for (unsigned i = 0; i != NumElems; ++i) {
7249 int EltIdx = SVOp->getMaskElt(i);
7250 if ((i & Mask) != 0 && EltIdx != -1)
7252 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7256 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7257 MVT NeVT = MVT::getIntegerVT(NBits);
7258 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7260 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7263 // Simplify the operand as it's prepared to be fed into shuffle.
7264 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7265 if (V1.getOpcode() == ISD::BITCAST &&
7266 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7267 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7268 V1.getOperand(0).getOperand(0)
7269 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7270 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7271 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7272 ConstantSDNode *CIdx =
7273 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7274 // If it's foldable, i.e. normal load with single use, we will let code
7275 // selection to fold it. Otherwise, we will short the conversion sequence.
7276 if (CIdx && CIdx->getZExtValue() == 0 &&
7277 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7278 MVT FullVT = V.getSimpleValueType();
7279 MVT V1VT = V1.getSimpleValueType();
7280 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7281 // The "ext_vec_elt" node is wider than the result node.
7282 // In this case we should extract subvector from V.
7283 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7284 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7285 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7286 FullVT.getVectorNumElements()/Ratio);
7287 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7288 DAG.getIntPtrConstant(0));
7290 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7294 return DAG.getNode(ISD::BITCAST, DL, VT,
7295 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7299 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7300 SelectionDAG &DAG) {
7301 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7302 MVT VT = Op.getSimpleValueType();
7304 SDValue V1 = Op.getOperand(0);
7305 SDValue V2 = Op.getOperand(1);
7307 if (isZeroShuffle(SVOp))
7308 return getZeroVector(VT, Subtarget, DAG, dl);
7310 // Handle splat operations
7311 if (SVOp->isSplat()) {
7312 // Use vbroadcast whenever the splat comes from a foldable load
7313 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7314 if (Broadcast.getNode())
7318 // Check integer expanding shuffles.
7319 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7320 if (NewOp.getNode())
7323 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7325 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7326 VT == MVT::v16i16 || VT == MVT::v32i8) {
7327 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7328 if (NewOp.getNode())
7329 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7330 } else if ((VT == MVT::v4i32 ||
7331 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7332 // FIXME: Figure out a cleaner way to do this.
7333 // Try to make use of movq to zero out the top part.
7334 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7335 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7336 if (NewOp.getNode()) {
7337 MVT NewVT = NewOp.getSimpleValueType();
7338 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7339 NewVT, true, false))
7340 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7341 DAG, Subtarget, dl);
7343 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7344 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7345 if (NewOp.getNode()) {
7346 MVT NewVT = NewOp.getSimpleValueType();
7347 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7348 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7349 DAG, Subtarget, dl);
7357 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7358 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7359 SDValue V1 = Op.getOperand(0);
7360 SDValue V2 = Op.getOperand(1);
7361 MVT VT = Op.getSimpleValueType();
7363 unsigned NumElems = VT.getVectorNumElements();
7364 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7365 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7366 bool V1IsSplat = false;
7367 bool V2IsSplat = false;
7368 bool HasSSE2 = Subtarget->hasSSE2();
7369 bool HasFp256 = Subtarget->hasFp256();
7370 bool HasInt256 = Subtarget->hasInt256();
7371 MachineFunction &MF = DAG.getMachineFunction();
7372 bool OptForSize = MF.getFunction()->getAttributes().
7373 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7375 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7377 if (V1IsUndef && V2IsUndef)
7378 return DAG.getUNDEF(VT);
7380 // When we create a shuffle node we put the UNDEF node to second operand,
7381 // but in some cases the first operand may be transformed to UNDEF.
7382 // In this case we should just commute the node.
7384 return CommuteVectorShuffle(SVOp, DAG);
7386 // Vector shuffle lowering takes 3 steps:
7388 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7389 // narrowing and commutation of operands should be handled.
7390 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7392 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7393 // so the shuffle can be broken into other shuffles and the legalizer can
7394 // try the lowering again.
7396 // The general idea is that no vector_shuffle operation should be left to
7397 // be matched during isel, all of them must be converted to a target specific
7400 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7401 // narrowing and commutation of operands should be handled. The actual code
7402 // doesn't include all of those, work in progress...
7403 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7404 if (NewOp.getNode())
7407 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7409 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7410 // unpckh_undef). Only use pshufd if speed is more important than size.
7411 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7412 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7413 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7414 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7416 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7417 V2IsUndef && MayFoldVectorLoad(V1))
7418 return getMOVDDup(Op, dl, V1, DAG);
7420 if (isMOVHLPS_v_undef_Mask(M, VT))
7421 return getMOVHighToLow(Op, dl, DAG);
7423 // Use to match splats
7424 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7425 (VT == MVT::v2f64 || VT == MVT::v2i64))
7426 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7428 if (isPSHUFDMask(M, VT)) {
7429 // The actual implementation will match the mask in the if above and then
7430 // during isel it can match several different instructions, not only pshufd
7431 // as its name says, sad but true, emulate the behavior for now...
7432 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7433 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7435 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7437 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7438 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7440 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7441 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7444 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7448 if (isPALIGNRMask(M, VT, Subtarget))
7449 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7450 getShufflePALIGNRImmediate(SVOp),
7453 // Check if this can be converted into a logical shift.
7454 bool isLeft = false;
7457 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7458 if (isShift && ShVal.hasOneUse()) {
7459 // If the shifted value has multiple uses, it may be cheaper to use
7460 // v_set0 + movlhps or movhlps, etc.
7461 MVT EltVT = VT.getVectorElementType();
7462 ShAmt *= EltVT.getSizeInBits();
7463 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7466 if (isMOVLMask(M, VT)) {
7467 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7468 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7469 if (!isMOVLPMask(M, VT)) {
7470 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7471 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7473 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7474 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7478 // FIXME: fold these into legal mask.
7479 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7480 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7482 if (isMOVHLPSMask(M, VT))
7483 return getMOVHighToLow(Op, dl, DAG);
7485 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7486 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7488 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7489 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7491 if (isMOVLPMask(M, VT))
7492 return getMOVLP(Op, dl, DAG, HasSSE2);
7494 if (ShouldXformToMOVHLPS(M, VT) ||
7495 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7496 return CommuteVectorShuffle(SVOp, DAG);
7499 // No better options. Use a vshldq / vsrldq.
7500 MVT EltVT = VT.getVectorElementType();
7501 ShAmt *= EltVT.getSizeInBits();
7502 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7505 bool Commuted = false;
7506 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7507 // 1,1,1,1 -> v8i16 though.
7508 V1IsSplat = isSplatVector(V1.getNode());
7509 V2IsSplat = isSplatVector(V2.getNode());
7511 // Canonicalize the splat or undef, if present, to be on the RHS.
7512 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7513 CommuteVectorShuffleMask(M, NumElems);
7515 std::swap(V1IsSplat, V2IsSplat);
7519 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7520 // Shuffling low element of v1 into undef, just return v1.
7523 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7524 // the instruction selector will not match, so get a canonical MOVL with
7525 // swapped operands to undo the commute.
7526 return getMOVL(DAG, dl, VT, V2, V1);
7529 if (isUNPCKLMask(M, VT, HasInt256))
7530 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7532 if (isUNPCKHMask(M, VT, HasInt256))
7533 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7536 // Normalize mask so all entries that point to V2 points to its first
7537 // element then try to match unpck{h|l} again. If match, return a
7538 // new vector_shuffle with the corrected mask.p
7539 SmallVector<int, 8> NewMask(M.begin(), M.end());
7540 NormalizeMask(NewMask, NumElems);
7541 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7542 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7543 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7544 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7548 // Commute is back and try unpck* again.
7549 // FIXME: this seems wrong.
7550 CommuteVectorShuffleMask(M, NumElems);
7552 std::swap(V1IsSplat, V2IsSplat);
7554 if (isUNPCKLMask(M, VT, HasInt256))
7555 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7557 if (isUNPCKHMask(M, VT, HasInt256))
7558 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7561 // Normalize the node to match x86 shuffle ops if needed
7562 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7563 return CommuteVectorShuffle(SVOp, DAG);
7565 // The checks below are all present in isShuffleMaskLegal, but they are
7566 // inlined here right now to enable us to directly emit target specific
7567 // nodes, and remove one by one until they don't return Op anymore.
7569 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7570 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7571 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7572 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7575 if (isPSHUFHWMask(M, VT, HasInt256))
7576 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7577 getShufflePSHUFHWImmediate(SVOp),
7580 if (isPSHUFLWMask(M, VT, HasInt256))
7581 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7582 getShufflePSHUFLWImmediate(SVOp),
7585 if (isSHUFPMask(M, VT))
7586 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7587 getShuffleSHUFImmediate(SVOp), DAG);
7589 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7590 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7591 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7592 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7594 //===--------------------------------------------------------------------===//
7595 // Generate target specific nodes for 128 or 256-bit shuffles only
7596 // supported in the AVX instruction set.
7599 // Handle VMOVDDUPY permutations
7600 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7601 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7603 // Handle VPERMILPS/D* permutations
7604 if (isVPERMILPMask(M, VT)) {
7605 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7606 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7607 getShuffleSHUFImmediate(SVOp), DAG);
7608 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7609 getShuffleSHUFImmediate(SVOp), DAG);
7612 // Handle VPERM2F128/VPERM2I128 permutations
7613 if (isVPERM2X128Mask(M, VT, HasFp256))
7614 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7615 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7617 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7618 if (BlendOp.getNode())
7622 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7623 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7625 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7626 VT.is512BitVector()) {
7627 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7628 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7629 SmallVector<SDValue, 16> permclMask;
7630 for (unsigned i = 0; i != NumElems; ++i) {
7631 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7634 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7635 &permclMask[0], NumElems);
7637 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7638 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7639 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7640 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7641 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7644 //===--------------------------------------------------------------------===//
7645 // Since no target specific shuffle was selected for this generic one,
7646 // lower it into other known shuffles. FIXME: this isn't true yet, but
7647 // this is the plan.
7650 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7651 if (VT == MVT::v8i16) {
7652 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7653 if (NewOp.getNode())
7657 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7658 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7659 if (NewOp.getNode())
7663 if (VT == MVT::v16i8) {
7664 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7665 if (NewOp.getNode())
7669 if (VT == MVT::v32i8) {
7670 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7671 if (NewOp.getNode())
7675 // Handle all 128-bit wide vectors with 4 elements, and match them with
7676 // several different shuffle types.
7677 if (NumElems == 4 && VT.is128BitVector())
7678 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7680 // Handle general 256-bit shuffles
7681 if (VT.is256BitVector())
7682 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7687 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7688 MVT VT = Op.getSimpleValueType();
7691 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7694 if (VT.getSizeInBits() == 8) {
7695 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7696 Op.getOperand(0), Op.getOperand(1));
7697 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7698 DAG.getValueType(VT));
7699 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7702 if (VT.getSizeInBits() == 16) {
7703 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7704 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7706 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7707 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7708 DAG.getNode(ISD::BITCAST, dl,
7712 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7713 Op.getOperand(0), Op.getOperand(1));
7714 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7715 DAG.getValueType(VT));
7716 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7719 if (VT == MVT::f32) {
7720 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7721 // the result back to FR32 register. It's only worth matching if the
7722 // result has a single use which is a store or a bitcast to i32. And in
7723 // the case of a store, it's not worth it if the index is a constant 0,
7724 // because a MOVSSmr can be used instead, which is smaller and faster.
7725 if (!Op.hasOneUse())
7727 SDNode *User = *Op.getNode()->use_begin();
7728 if ((User->getOpcode() != ISD::STORE ||
7729 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7730 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7731 (User->getOpcode() != ISD::BITCAST ||
7732 User->getValueType(0) != MVT::i32))
7734 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7735 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7738 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7741 if (VT == MVT::i32 || VT == MVT::i64) {
7742 // ExtractPS/pextrq works with constant index.
7743 if (isa<ConstantSDNode>(Op.getOperand(1)))
7749 /// Extract one bit from mask vector, like v16i1 or v8i1.
7750 /// AVX-512 feature.
7752 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7753 SDValue Vec = Op.getOperand(0);
7755 MVT VecVT = Vec.getSimpleValueType();
7756 SDValue Idx = Op.getOperand(1);
7757 MVT EltVT = Op.getSimpleValueType();
7759 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7761 // variable index can't be handled in mask registers,
7762 // extend vector to VR512
7763 if (!isa<ConstantSDNode>(Idx)) {
7764 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7765 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7766 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7767 ExtVT.getVectorElementType(), Ext, Idx);
7768 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7771 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7772 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7773 unsigned MaxSift = rc->getSize()*8 - 1;
7774 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7775 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7776 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7777 DAG.getConstant(MaxSift, MVT::i8));
7778 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7779 DAG.getIntPtrConstant(0));
7783 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7784 SelectionDAG &DAG) const {
7786 SDValue Vec = Op.getOperand(0);
7787 MVT VecVT = Vec.getSimpleValueType();
7788 SDValue Idx = Op.getOperand(1);
7790 if (Op.getSimpleValueType() == MVT::i1)
7791 return ExtractBitFromMaskVector(Op, DAG);
7793 if (!isa<ConstantSDNode>(Idx)) {
7794 if (VecVT.is512BitVector() ||
7795 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7796 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7799 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7800 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7801 MaskEltVT.getSizeInBits());
7803 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7804 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7805 getZeroVector(MaskVT, Subtarget, DAG, dl),
7806 Idx, DAG.getConstant(0, getPointerTy()));
7807 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7808 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7809 Perm, DAG.getConstant(0, getPointerTy()));
7814 // If this is a 256-bit vector result, first extract the 128-bit vector and
7815 // then extract the element from the 128-bit vector.
7816 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7818 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7819 // Get the 128-bit vector.
7820 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7821 MVT EltVT = VecVT.getVectorElementType();
7823 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7825 //if (IdxVal >= NumElems/2)
7826 // IdxVal -= NumElems/2;
7827 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7828 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7829 DAG.getConstant(IdxVal, MVT::i32));
7832 assert(VecVT.is128BitVector() && "Unexpected vector length");
7834 if (Subtarget->hasSSE41()) {
7835 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7840 MVT VT = Op.getSimpleValueType();
7841 // TODO: handle v16i8.
7842 if (VT.getSizeInBits() == 16) {
7843 SDValue Vec = Op.getOperand(0);
7844 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7846 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7847 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7848 DAG.getNode(ISD::BITCAST, dl,
7851 // Transform it so it match pextrw which produces a 32-bit result.
7852 MVT EltVT = MVT::i32;
7853 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7854 Op.getOperand(0), Op.getOperand(1));
7855 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7856 DAG.getValueType(VT));
7857 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7860 if (VT.getSizeInBits() == 32) {
7861 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7865 // SHUFPS the element to the lowest double word, then movss.
7866 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7867 MVT VVT = Op.getOperand(0).getSimpleValueType();
7868 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7869 DAG.getUNDEF(VVT), Mask);
7870 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7871 DAG.getIntPtrConstant(0));
7874 if (VT.getSizeInBits() == 64) {
7875 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7876 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7877 // to match extract_elt for f64.
7878 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7882 // UNPCKHPD the element to the lowest double word, then movsd.
7883 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7884 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7885 int Mask[2] = { 1, -1 };
7886 MVT VVT = Op.getOperand(0).getSimpleValueType();
7887 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7888 DAG.getUNDEF(VVT), Mask);
7889 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7890 DAG.getIntPtrConstant(0));
7896 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7897 MVT VT = Op.getSimpleValueType();
7898 MVT EltVT = VT.getVectorElementType();
7901 SDValue N0 = Op.getOperand(0);
7902 SDValue N1 = Op.getOperand(1);
7903 SDValue N2 = Op.getOperand(2);
7905 if (!VT.is128BitVector())
7908 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7909 isa<ConstantSDNode>(N2)) {
7911 if (VT == MVT::v8i16)
7912 Opc = X86ISD::PINSRW;
7913 else if (VT == MVT::v16i8)
7914 Opc = X86ISD::PINSRB;
7916 Opc = X86ISD::PINSRB;
7918 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7920 if (N1.getValueType() != MVT::i32)
7921 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7922 if (N2.getValueType() != MVT::i32)
7923 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7924 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7927 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7928 // Bits [7:6] of the constant are the source select. This will always be
7929 // zero here. The DAG Combiner may combine an extract_elt index into these
7930 // bits. For example (insert (extract, 3), 2) could be matched by putting
7931 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7932 // Bits [5:4] of the constant are the destination select. This is the
7933 // value of the incoming immediate.
7934 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7935 // combine either bitwise AND or insert of float 0.0 to set these bits.
7936 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7937 // Create this as a scalar to vector..
7938 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7939 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7942 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7943 // PINSR* works with constant index.
7950 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7951 MVT VT = Op.getSimpleValueType();
7952 MVT EltVT = VT.getVectorElementType();
7955 SDValue N0 = Op.getOperand(0);
7956 SDValue N1 = Op.getOperand(1);
7957 SDValue N2 = Op.getOperand(2);
7959 // If this is a 256-bit vector result, first extract the 128-bit vector,
7960 // insert the element into the extracted half and then place it back.
7961 if (VT.is256BitVector() || VT.is512BitVector()) {
7962 if (!isa<ConstantSDNode>(N2))
7965 // Get the desired 128-bit vector half.
7966 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7967 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7969 // Insert the element into the desired half.
7970 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7971 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7973 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7974 DAG.getConstant(IdxIn128, MVT::i32));
7976 // Insert the changed part back to the 256-bit vector
7977 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7980 if (Subtarget->hasSSE41())
7981 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7983 if (EltVT == MVT::i8)
7986 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7987 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7988 // as its second argument.
7989 if (N1.getValueType() != MVT::i32)
7990 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7991 if (N2.getValueType() != MVT::i32)
7992 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7993 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7998 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8000 MVT OpVT = Op.getSimpleValueType();
8002 // If this is a 256-bit vector result, first insert into a 128-bit
8003 // vector and then insert into the 256-bit vector.
8004 if (!OpVT.is128BitVector()) {
8005 // Insert into a 128-bit vector.
8006 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8007 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8008 OpVT.getVectorNumElements() / SizeFactor);
8010 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8012 // Insert the 128-bit vector.
8013 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8016 if (OpVT == MVT::v1i64 &&
8017 Op.getOperand(0).getValueType() == MVT::i64)
8018 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8020 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8021 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8022 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8023 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8026 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8027 // a simple subregister reference or explicit instructions to grab
8028 // upper bits of a vector.
8029 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8030 SelectionDAG &DAG) {
8032 SDValue In = Op.getOperand(0);
8033 SDValue Idx = Op.getOperand(1);
8034 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8035 MVT ResVT = Op.getSimpleValueType();
8036 MVT InVT = In.getSimpleValueType();
8038 if (Subtarget->hasFp256()) {
8039 if (ResVT.is128BitVector() &&
8040 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8041 isa<ConstantSDNode>(Idx)) {
8042 return Extract128BitVector(In, IdxVal, DAG, dl);
8044 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8045 isa<ConstantSDNode>(Idx)) {
8046 return Extract256BitVector(In, IdxVal, DAG, dl);
8052 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8053 // simple superregister reference or explicit instructions to insert
8054 // the upper bits of a vector.
8055 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8056 SelectionDAG &DAG) {
8057 if (Subtarget->hasFp256()) {
8058 SDLoc dl(Op.getNode());
8059 SDValue Vec = Op.getNode()->getOperand(0);
8060 SDValue SubVec = Op.getNode()->getOperand(1);
8061 SDValue Idx = Op.getNode()->getOperand(2);
8063 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8064 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8065 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8066 isa<ConstantSDNode>(Idx)) {
8067 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8068 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8071 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8072 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8073 isa<ConstantSDNode>(Idx)) {
8074 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8075 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8081 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8082 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8083 // one of the above mentioned nodes. It has to be wrapped because otherwise
8084 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8085 // be used to form addressing mode. These wrapped nodes will be selected
8088 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8089 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8091 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8093 unsigned char OpFlag = 0;
8094 unsigned WrapperKind = X86ISD::Wrapper;
8095 CodeModel::Model M = getTargetMachine().getCodeModel();
8097 if (Subtarget->isPICStyleRIPRel() &&
8098 (M == CodeModel::Small || M == CodeModel::Kernel))
8099 WrapperKind = X86ISD::WrapperRIP;
8100 else if (Subtarget->isPICStyleGOT())
8101 OpFlag = X86II::MO_GOTOFF;
8102 else if (Subtarget->isPICStyleStubPIC())
8103 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8105 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8107 CP->getOffset(), OpFlag);
8109 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8110 // With PIC, the address is actually $g + Offset.
8112 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8113 DAG.getNode(X86ISD::GlobalBaseReg,
8114 SDLoc(), getPointerTy()),
8121 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8122 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8124 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8126 unsigned char OpFlag = 0;
8127 unsigned WrapperKind = X86ISD::Wrapper;
8128 CodeModel::Model M = getTargetMachine().getCodeModel();
8130 if (Subtarget->isPICStyleRIPRel() &&
8131 (M == CodeModel::Small || M == CodeModel::Kernel))
8132 WrapperKind = X86ISD::WrapperRIP;
8133 else if (Subtarget->isPICStyleGOT())
8134 OpFlag = X86II::MO_GOTOFF;
8135 else if (Subtarget->isPICStyleStubPIC())
8136 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8138 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8141 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8143 // With PIC, the address is actually $g + Offset.
8145 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8146 DAG.getNode(X86ISD::GlobalBaseReg,
8147 SDLoc(), getPointerTy()),
8154 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8155 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8157 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8159 unsigned char OpFlag = 0;
8160 unsigned WrapperKind = X86ISD::Wrapper;
8161 CodeModel::Model M = getTargetMachine().getCodeModel();
8163 if (Subtarget->isPICStyleRIPRel() &&
8164 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8165 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8166 OpFlag = X86II::MO_GOTPCREL;
8167 WrapperKind = X86ISD::WrapperRIP;
8168 } else if (Subtarget->isPICStyleGOT()) {
8169 OpFlag = X86II::MO_GOT;
8170 } else if (Subtarget->isPICStyleStubPIC()) {
8171 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8172 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8173 OpFlag = X86II::MO_DARWIN_NONLAZY;
8176 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8179 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8181 // With PIC, the address is actually $g + Offset.
8182 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8183 !Subtarget->is64Bit()) {
8184 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8185 DAG.getNode(X86ISD::GlobalBaseReg,
8186 SDLoc(), getPointerTy()),
8190 // For symbols that require a load from a stub to get the address, emit the
8192 if (isGlobalStubReference(OpFlag))
8193 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8194 MachinePointerInfo::getGOT(), false, false, false, 0);
8200 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8201 // Create the TargetBlockAddressAddress node.
8202 unsigned char OpFlags =
8203 Subtarget->ClassifyBlockAddressReference();
8204 CodeModel::Model M = getTargetMachine().getCodeModel();
8205 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8206 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8208 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8211 if (Subtarget->isPICStyleRIPRel() &&
8212 (M == CodeModel::Small || M == CodeModel::Kernel))
8213 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8215 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8217 // With PIC, the address is actually $g + Offset.
8218 if (isGlobalRelativeToPICBase(OpFlags)) {
8219 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8220 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8228 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8229 int64_t Offset, SelectionDAG &DAG) const {
8230 // Create the TargetGlobalAddress node, folding in the constant
8231 // offset if it is legal.
8232 unsigned char OpFlags =
8233 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8234 CodeModel::Model M = getTargetMachine().getCodeModel();
8236 if (OpFlags == X86II::MO_NO_FLAG &&
8237 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8238 // A direct static reference to a global.
8239 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8242 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8245 if (Subtarget->isPICStyleRIPRel() &&
8246 (M == CodeModel::Small || M == CodeModel::Kernel))
8247 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8249 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8251 // With PIC, the address is actually $g + Offset.
8252 if (isGlobalRelativeToPICBase(OpFlags)) {
8253 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8254 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8258 // For globals that require a load from a stub to get the address, emit the
8260 if (isGlobalStubReference(OpFlags))
8261 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8262 MachinePointerInfo::getGOT(), false, false, false, 0);
8264 // If there was a non-zero offset that we didn't fold, create an explicit
8267 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8268 DAG.getConstant(Offset, getPointerTy()));
8274 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8275 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8276 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8277 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8281 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8282 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8283 unsigned char OperandFlags, bool LocalDynamic = false) {
8284 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8285 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8287 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8288 GA->getValueType(0),
8292 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8296 SDValue Ops[] = { Chain, TGA, *InFlag };
8297 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8299 SDValue Ops[] = { Chain, TGA };
8300 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8303 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8304 MFI->setAdjustsStack(true);
8306 SDValue Flag = Chain.getValue(1);
8307 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8310 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8312 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8315 SDLoc dl(GA); // ? function entry point might be better
8316 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8317 DAG.getNode(X86ISD::GlobalBaseReg,
8318 SDLoc(), PtrVT), InFlag);
8319 InFlag = Chain.getValue(1);
8321 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8324 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8326 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8328 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8329 X86::RAX, X86II::MO_TLSGD);
8332 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8338 // Get the start address of the TLS block for this module.
8339 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8340 .getInfo<X86MachineFunctionInfo>();
8341 MFI->incNumLocalDynamicTLSAccesses();
8345 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8346 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8349 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8350 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8351 InFlag = Chain.getValue(1);
8352 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8353 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8356 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8360 unsigned char OperandFlags = X86II::MO_DTPOFF;
8361 unsigned WrapperKind = X86ISD::Wrapper;
8362 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8363 GA->getValueType(0),
8364 GA->getOffset(), OperandFlags);
8365 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8367 // Add x@dtpoff with the base.
8368 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8371 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8372 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8373 const EVT PtrVT, TLSModel::Model model,
8374 bool is64Bit, bool isPIC) {
8377 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8378 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8379 is64Bit ? 257 : 256));
8381 SDValue ThreadPointer =
8382 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8383 MachinePointerInfo(Ptr), false, false, false, 0);
8385 unsigned char OperandFlags = 0;
8386 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8388 unsigned WrapperKind = X86ISD::Wrapper;
8389 if (model == TLSModel::LocalExec) {
8390 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8391 } else if (model == TLSModel::InitialExec) {
8393 OperandFlags = X86II::MO_GOTTPOFF;
8394 WrapperKind = X86ISD::WrapperRIP;
8396 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8399 llvm_unreachable("Unexpected model");
8402 // emit "addl x@ntpoff,%eax" (local exec)
8403 // or "addl x@indntpoff,%eax" (initial exec)
8404 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8406 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8407 GA->getOffset(), OperandFlags);
8408 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8410 if (model == TLSModel::InitialExec) {
8411 if (isPIC && !is64Bit) {
8412 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8413 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8417 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8418 MachinePointerInfo::getGOT(), false, false, false, 0);
8421 // The address of the thread local variable is the add of the thread
8422 // pointer with the offset of the variable.
8423 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8427 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8429 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8430 const GlobalValue *GV = GA->getGlobal();
8432 if (Subtarget->isTargetELF()) {
8433 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8436 case TLSModel::GeneralDynamic:
8437 if (Subtarget->is64Bit())
8438 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8439 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8440 case TLSModel::LocalDynamic:
8441 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8442 Subtarget->is64Bit());
8443 case TLSModel::InitialExec:
8444 case TLSModel::LocalExec:
8445 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8446 Subtarget->is64Bit(),
8447 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8449 llvm_unreachable("Unknown TLS model.");
8452 if (Subtarget->isTargetDarwin()) {
8453 // Darwin only has one model of TLS. Lower to that.
8454 unsigned char OpFlag = 0;
8455 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8456 X86ISD::WrapperRIP : X86ISD::Wrapper;
8458 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8460 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8461 !Subtarget->is64Bit();
8463 OpFlag = X86II::MO_TLVP_PIC_BASE;
8465 OpFlag = X86II::MO_TLVP;
8467 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8468 GA->getValueType(0),
8469 GA->getOffset(), OpFlag);
8470 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8472 // With PIC32, the address is actually $g + Offset.
8474 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8475 DAG.getNode(X86ISD::GlobalBaseReg,
8476 SDLoc(), getPointerTy()),
8479 // Lowering the machine isd will make sure everything is in the right
8481 SDValue Chain = DAG.getEntryNode();
8482 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8483 SDValue Args[] = { Chain, Offset };
8484 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8486 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8487 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8488 MFI->setAdjustsStack(true);
8490 // And our return value (tls address) is in the standard call return value
8492 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8493 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8497 if (Subtarget->isTargetKnownWindowsMSVC() || Subtarget->isTargetMingw()) {
8498 // Just use the implicit TLS architecture
8499 // Need to generate someting similar to:
8500 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8502 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8503 // mov rcx, qword [rdx+rcx*8]
8504 // mov eax, .tls$:tlsvar
8505 // [rax+rcx] contains the address
8506 // Windows 64bit: gs:0x58
8507 // Windows 32bit: fs:__tls_array
8509 // If GV is an alias then use the aliasee for determining
8510 // thread-localness.
8511 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8512 GV = GA->getAliasedGlobal();
8514 SDValue Chain = DAG.getEntryNode();
8516 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8517 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8518 // use its literal value of 0x2C.
8519 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8520 ? Type::getInt8PtrTy(*DAG.getContext(),
8522 : Type::getInt32PtrTy(*DAG.getContext(),
8525 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8526 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8527 DAG.getExternalSymbol("_tls_array", getPointerTy()));
8529 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8530 MachinePointerInfo(Ptr),
8531 false, false, false, 0);
8533 // Load the _tls_index variable
8534 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8535 if (Subtarget->is64Bit())
8536 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8537 IDX, MachinePointerInfo(), MVT::i32,
8540 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8541 false, false, false, 0);
8543 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8545 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8547 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8548 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8549 false, false, false, 0);
8551 // Get the offset of start of .tls section
8552 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8553 GA->getValueType(0),
8554 GA->getOffset(), X86II::MO_SECREL);
8555 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8557 // The address of the thread local variable is the add of the thread
8558 // pointer with the offset of the variable.
8559 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8562 llvm_unreachable("TLS not implemented for this target.");
8565 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8566 /// and take a 2 x i32 value to shift plus a shift amount.
8567 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8568 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8569 MVT VT = Op.getSimpleValueType();
8570 unsigned VTBits = VT.getSizeInBits();
8572 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8573 SDValue ShOpLo = Op.getOperand(0);
8574 SDValue ShOpHi = Op.getOperand(1);
8575 SDValue ShAmt = Op.getOperand(2);
8576 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8577 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8579 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8580 DAG.getConstant(VTBits - 1, MVT::i8));
8581 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8582 DAG.getConstant(VTBits - 1, MVT::i8))
8583 : DAG.getConstant(0, VT);
8586 if (Op.getOpcode() == ISD::SHL_PARTS) {
8587 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8588 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8590 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8591 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8594 // If the shift amount is larger or equal than the width of a part we can't
8595 // rely on the results of shld/shrd. Insert a test and select the appropriate
8596 // values for large shift amounts.
8597 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8598 DAG.getConstant(VTBits, MVT::i8));
8599 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8600 AndNode, DAG.getConstant(0, MVT::i8));
8603 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8604 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8605 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8607 if (Op.getOpcode() == ISD::SHL_PARTS) {
8608 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8609 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8611 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8612 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8615 SDValue Ops[2] = { Lo, Hi };
8616 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8619 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8620 SelectionDAG &DAG) const {
8621 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8623 if (SrcVT.isVector())
8626 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8627 "Unknown SINT_TO_FP to lower!");
8629 // These are really Legal; return the operand so the caller accepts it as
8631 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8633 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8634 Subtarget->is64Bit()) {
8639 unsigned Size = SrcVT.getSizeInBits()/8;
8640 MachineFunction &MF = DAG.getMachineFunction();
8641 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8642 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8643 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8645 MachinePointerInfo::getFixedStack(SSFI),
8647 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8650 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8652 SelectionDAG &DAG) const {
8656 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8658 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8660 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8662 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8664 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8665 MachineMemOperand *MMO;
8667 int SSFI = FI->getIndex();
8669 DAG.getMachineFunction()
8670 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8671 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8673 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8674 StackSlot = StackSlot.getOperand(1);
8676 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8677 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8679 Tys, Ops, array_lengthof(Ops),
8683 Chain = Result.getValue(1);
8684 SDValue InFlag = Result.getValue(2);
8686 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8687 // shouldn't be necessary except that RFP cannot be live across
8688 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8689 MachineFunction &MF = DAG.getMachineFunction();
8690 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8691 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8692 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8693 Tys = DAG.getVTList(MVT::Other);
8695 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8697 MachineMemOperand *MMO =
8698 DAG.getMachineFunction()
8699 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8700 MachineMemOperand::MOStore, SSFISize, SSFISize);
8702 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8703 Ops, array_lengthof(Ops),
8704 Op.getValueType(), MMO);
8705 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8706 MachinePointerInfo::getFixedStack(SSFI),
8707 false, false, false, 0);
8713 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8714 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8715 SelectionDAG &DAG) const {
8716 // This algorithm is not obvious. Here it is what we're trying to output:
8719 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8720 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8724 pshufd $0x4e, %xmm0, %xmm1
8730 LLVMContext *Context = DAG.getContext();
8732 // Build some magic constants.
8733 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8734 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8735 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8737 SmallVector<Constant*,2> CV1;
8739 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8740 APInt(64, 0x4330000000000000ULL))));
8742 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8743 APInt(64, 0x4530000000000000ULL))));
8744 Constant *C1 = ConstantVector::get(CV1);
8745 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8747 // Load the 64-bit value into an XMM register.
8748 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8750 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8751 MachinePointerInfo::getConstantPool(),
8752 false, false, false, 16);
8753 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8754 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8757 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8758 MachinePointerInfo::getConstantPool(),
8759 false, false, false, 16);
8760 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8761 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8764 if (Subtarget->hasSSE3()) {
8765 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8766 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8768 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8769 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8771 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8772 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8776 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8777 DAG.getIntPtrConstant(0));
8780 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8781 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8782 SelectionDAG &DAG) const {
8784 // FP constant to bias correct the final result.
8785 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8788 // Load the 32-bit value into an XMM register.
8789 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8792 // Zero out the upper parts of the register.
8793 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8795 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8796 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8797 DAG.getIntPtrConstant(0));
8799 // Or the load with the bias.
8800 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8801 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8802 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8804 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8805 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8806 MVT::v2f64, Bias)));
8807 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8808 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8809 DAG.getIntPtrConstant(0));
8811 // Subtract the bias.
8812 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8814 // Handle final rounding.
8815 EVT DestVT = Op.getValueType();
8817 if (DestVT.bitsLT(MVT::f64))
8818 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8819 DAG.getIntPtrConstant(0));
8820 if (DestVT.bitsGT(MVT::f64))
8821 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8823 // Handle final rounding.
8827 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8828 SelectionDAG &DAG) const {
8829 SDValue N0 = Op.getOperand(0);
8830 MVT SVT = N0.getSimpleValueType();
8833 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8834 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8835 "Custom UINT_TO_FP is not supported!");
8837 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8838 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8839 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8842 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8843 SelectionDAG &DAG) const {
8844 SDValue N0 = Op.getOperand(0);
8847 if (Op.getValueType().isVector())
8848 return lowerUINT_TO_FP_vec(Op, DAG);
8850 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8851 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8852 // the optimization here.
8853 if (DAG.SignBitIsZero(N0))
8854 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8856 MVT SrcVT = N0.getSimpleValueType();
8857 MVT DstVT = Op.getSimpleValueType();
8858 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8859 return LowerUINT_TO_FP_i64(Op, DAG);
8860 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8861 return LowerUINT_TO_FP_i32(Op, DAG);
8862 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8865 // Make a 64-bit buffer, and use it to build an FILD.
8866 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8867 if (SrcVT == MVT::i32) {
8868 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8869 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8870 getPointerTy(), StackSlot, WordOff);
8871 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8872 StackSlot, MachinePointerInfo(),
8874 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8875 OffsetSlot, MachinePointerInfo(),
8877 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8881 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8882 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8883 StackSlot, MachinePointerInfo(),
8885 // For i64 source, we need to add the appropriate power of 2 if the input
8886 // was negative. This is the same as the optimization in
8887 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8888 // we must be careful to do the computation in x87 extended precision, not
8889 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8890 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8891 MachineMemOperand *MMO =
8892 DAG.getMachineFunction()
8893 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8894 MachineMemOperand::MOLoad, 8, 8);
8896 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8897 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8898 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8899 array_lengthof(Ops), MVT::i64, MMO);
8901 APInt FF(32, 0x5F800000ULL);
8903 // Check whether the sign bit is set.
8904 SDValue SignSet = DAG.getSetCC(dl,
8905 getSetCCResultType(*DAG.getContext(), MVT::i64),
8906 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8909 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8910 SDValue FudgePtr = DAG.getConstantPool(
8911 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8914 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8915 SDValue Zero = DAG.getIntPtrConstant(0);
8916 SDValue Four = DAG.getIntPtrConstant(4);
8917 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8919 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8921 // Load the value out, extending it from f32 to f80.
8922 // FIXME: Avoid the extend by constructing the right constant pool?
8923 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8924 FudgePtr, MachinePointerInfo::getConstantPool(),
8925 MVT::f32, false, false, 4);
8926 // Extend everything to 80 bits to force it to be done on x87.
8927 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8928 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8931 std::pair<SDValue,SDValue>
8932 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8933 bool IsSigned, bool IsReplace) const {
8936 EVT DstTy = Op.getValueType();
8938 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8939 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8943 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8944 DstTy.getSimpleVT() >= MVT::i16 &&
8945 "Unknown FP_TO_INT to lower!");
8947 // These are really Legal.
8948 if (DstTy == MVT::i32 &&
8949 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8950 return std::make_pair(SDValue(), SDValue());
8951 if (Subtarget->is64Bit() &&
8952 DstTy == MVT::i64 &&
8953 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8954 return std::make_pair(SDValue(), SDValue());
8956 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8957 // stack slot, or into the FTOL runtime function.
8958 MachineFunction &MF = DAG.getMachineFunction();
8959 unsigned MemSize = DstTy.getSizeInBits()/8;
8960 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8961 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8964 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8965 Opc = X86ISD::WIN_FTOL;
8967 switch (DstTy.getSimpleVT().SimpleTy) {
8968 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8969 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8970 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8971 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8974 SDValue Chain = DAG.getEntryNode();
8975 SDValue Value = Op.getOperand(0);
8976 EVT TheVT = Op.getOperand(0).getValueType();
8977 // FIXME This causes a redundant load/store if the SSE-class value is already
8978 // in memory, such as if it is on the callstack.
8979 if (isScalarFPTypeInSSEReg(TheVT)) {
8980 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8981 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8982 MachinePointerInfo::getFixedStack(SSFI),
8984 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8986 Chain, StackSlot, DAG.getValueType(TheVT)
8989 MachineMemOperand *MMO =
8990 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8991 MachineMemOperand::MOLoad, MemSize, MemSize);
8992 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8993 array_lengthof(Ops), DstTy, MMO);
8994 Chain = Value.getValue(1);
8995 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8996 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8999 MachineMemOperand *MMO =
9000 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9001 MachineMemOperand::MOStore, MemSize, MemSize);
9003 if (Opc != X86ISD::WIN_FTOL) {
9004 // Build the FP_TO_INT*_IN_MEM
9005 SDValue Ops[] = { Chain, Value, StackSlot };
9006 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9007 Ops, array_lengthof(Ops), DstTy,
9009 return std::make_pair(FIST, StackSlot);
9011 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9012 DAG.getVTList(MVT::Other, MVT::Glue),
9014 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9015 MVT::i32, ftol.getValue(1));
9016 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9017 MVT::i32, eax.getValue(2));
9018 SDValue Ops[] = { eax, edx };
9019 SDValue pair = IsReplace
9020 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9021 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9022 return std::make_pair(pair, SDValue());
9026 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9027 const X86Subtarget *Subtarget) {
9028 MVT VT = Op->getSimpleValueType(0);
9029 SDValue In = Op->getOperand(0);
9030 MVT InVT = In.getSimpleValueType();
9033 // Optimize vectors in AVX mode:
9036 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9037 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9038 // Concat upper and lower parts.
9041 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9042 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9043 // Concat upper and lower parts.
9046 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9047 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9048 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9051 if (Subtarget->hasInt256())
9052 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9054 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9055 SDValue Undef = DAG.getUNDEF(InVT);
9056 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9057 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9058 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9060 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9061 VT.getVectorNumElements()/2);
9063 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9064 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9066 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9069 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9070 SelectionDAG &DAG) {
9071 MVT VT = Op->getSimpleValueType(0);
9072 SDValue In = Op->getOperand(0);
9073 MVT InVT = In.getSimpleValueType();
9075 unsigned int NumElts = VT.getVectorNumElements();
9076 if (NumElts != 8 && NumElts != 16)
9079 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9080 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9082 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9083 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9084 // Now we have only mask extension
9085 assert(InVT.getVectorElementType() == MVT::i1);
9086 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9087 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9088 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9089 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9090 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9091 MachinePointerInfo::getConstantPool(),
9092 false, false, false, Alignment);
9094 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9095 if (VT.is512BitVector())
9097 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9100 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9101 SelectionDAG &DAG) {
9102 if (Subtarget->hasFp256()) {
9103 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9111 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9112 SelectionDAG &DAG) {
9114 MVT VT = Op.getSimpleValueType();
9115 SDValue In = Op.getOperand(0);
9116 MVT SVT = In.getSimpleValueType();
9118 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9119 return LowerZERO_EXTEND_AVX512(Op, DAG);
9121 if (Subtarget->hasFp256()) {
9122 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9127 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9128 VT.getVectorNumElements() != SVT.getVectorNumElements());
9132 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9134 MVT VT = Op.getSimpleValueType();
9135 SDValue In = Op.getOperand(0);
9136 MVT InVT = In.getSimpleValueType();
9138 if (VT == MVT::i1) {
9139 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9140 "Invalid scalar TRUNCATE operation");
9141 if (InVT == MVT::i32)
9143 if (InVT.getSizeInBits() == 64)
9144 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9145 else if (InVT.getSizeInBits() < 32)
9146 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9147 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9149 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9150 "Invalid TRUNCATE operation");
9152 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9153 if (VT.getVectorElementType().getSizeInBits() >=8)
9154 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9156 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9157 unsigned NumElts = InVT.getVectorNumElements();
9158 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9159 if (InVT.getSizeInBits() < 512) {
9160 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9161 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9165 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9166 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9167 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9168 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9169 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9170 MachinePointerInfo::getConstantPool(),
9171 false, false, false, Alignment);
9172 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9173 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9174 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9177 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9178 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9179 if (Subtarget->hasInt256()) {
9180 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9181 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9182 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9184 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9185 DAG.getIntPtrConstant(0));
9188 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9189 DAG.getIntPtrConstant(0));
9190 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9191 DAG.getIntPtrConstant(2));
9192 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9193 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9194 static const int ShufMask[] = {0, 2, 4, 6};
9195 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9198 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9199 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9200 if (Subtarget->hasInt256()) {
9201 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9203 SmallVector<SDValue,32> pshufbMask;
9204 for (unsigned i = 0; i < 2; ++i) {
9205 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9206 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9207 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9208 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9209 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9210 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9211 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9212 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9213 for (unsigned j = 0; j < 8; ++j)
9214 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9216 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9217 &pshufbMask[0], 32);
9218 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9219 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9221 static const int ShufMask[] = {0, 2, -1, -1};
9222 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9224 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9225 DAG.getIntPtrConstant(0));
9226 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9229 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9230 DAG.getIntPtrConstant(0));
9232 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9233 DAG.getIntPtrConstant(4));
9235 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9236 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9239 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9240 -1, -1, -1, -1, -1, -1, -1, -1};
9242 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9243 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9244 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9246 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9247 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9249 // The MOVLHPS Mask:
9250 static const int ShufMask2[] = {0, 1, 4, 5};
9251 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9252 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9255 // Handle truncation of V256 to V128 using shuffles.
9256 if (!VT.is128BitVector() || !InVT.is256BitVector())
9259 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9261 unsigned NumElems = VT.getVectorNumElements();
9262 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9264 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9265 // Prepare truncation shuffle mask
9266 for (unsigned i = 0; i != NumElems; ++i)
9268 SDValue V = DAG.getVectorShuffle(NVT, DL,
9269 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9270 DAG.getUNDEF(NVT), &MaskVec[0]);
9271 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9272 DAG.getIntPtrConstant(0));
9275 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9276 SelectionDAG &DAG) const {
9277 assert(!Op.getSimpleValueType().isVector());
9279 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9280 /*IsSigned=*/ true, /*IsReplace=*/ false);
9281 SDValue FIST = Vals.first, StackSlot = Vals.second;
9282 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9283 if (FIST.getNode() == 0) return Op;
9285 if (StackSlot.getNode())
9287 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9288 FIST, StackSlot, MachinePointerInfo(),
9289 false, false, false, 0);
9291 // The node is the result.
9295 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9296 SelectionDAG &DAG) const {
9297 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9298 /*IsSigned=*/ false, /*IsReplace=*/ false);
9299 SDValue FIST = Vals.first, StackSlot = Vals.second;
9300 assert(FIST.getNode() && "Unexpected failure");
9302 if (StackSlot.getNode())
9304 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9305 FIST, StackSlot, MachinePointerInfo(),
9306 false, false, false, 0);
9308 // The node is the result.
9312 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9314 MVT VT = Op.getSimpleValueType();
9315 SDValue In = Op.getOperand(0);
9316 MVT SVT = In.getSimpleValueType();
9318 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9320 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9321 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9322 In, DAG.getUNDEF(SVT)));
9325 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9326 LLVMContext *Context = DAG.getContext();
9328 MVT VT = Op.getSimpleValueType();
9330 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9331 if (VT.isVector()) {
9332 EltVT = VT.getVectorElementType();
9333 NumElts = VT.getVectorNumElements();
9336 if (EltVT == MVT::f64)
9337 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9338 APInt(64, ~(1ULL << 63))));
9340 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9341 APInt(32, ~(1U << 31))));
9342 C = ConstantVector::getSplat(NumElts, C);
9343 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9344 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9345 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9346 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9347 MachinePointerInfo::getConstantPool(),
9348 false, false, false, Alignment);
9349 if (VT.isVector()) {
9350 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9351 return DAG.getNode(ISD::BITCAST, dl, VT,
9352 DAG.getNode(ISD::AND, dl, ANDVT,
9353 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9355 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9357 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9360 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9361 LLVMContext *Context = DAG.getContext();
9363 MVT VT = Op.getSimpleValueType();
9365 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9366 if (VT.isVector()) {
9367 EltVT = VT.getVectorElementType();
9368 NumElts = VT.getVectorNumElements();
9371 if (EltVT == MVT::f64)
9372 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9373 APInt(64, 1ULL << 63)));
9375 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9376 APInt(32, 1U << 31)));
9377 C = ConstantVector::getSplat(NumElts, C);
9378 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9379 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9380 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9381 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9382 MachinePointerInfo::getConstantPool(),
9383 false, false, false, Alignment);
9384 if (VT.isVector()) {
9385 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9386 return DAG.getNode(ISD::BITCAST, dl, VT,
9387 DAG.getNode(ISD::XOR, dl, XORVT,
9388 DAG.getNode(ISD::BITCAST, dl, XORVT,
9390 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9393 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9396 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9397 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9398 LLVMContext *Context = DAG.getContext();
9399 SDValue Op0 = Op.getOperand(0);
9400 SDValue Op1 = Op.getOperand(1);
9402 MVT VT = Op.getSimpleValueType();
9403 MVT SrcVT = Op1.getSimpleValueType();
9405 // If second operand is smaller, extend it first.
9406 if (SrcVT.bitsLT(VT)) {
9407 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9410 // And if it is bigger, shrink it first.
9411 if (SrcVT.bitsGT(VT)) {
9412 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9416 // At this point the operands and the result should have the same
9417 // type, and that won't be f80 since that is not custom lowered.
9419 // First get the sign bit of second operand.
9420 SmallVector<Constant*,4> CV;
9421 if (SrcVT == MVT::f64) {
9422 const fltSemantics &Sem = APFloat::IEEEdouble;
9423 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9424 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9426 const fltSemantics &Sem = APFloat::IEEEsingle;
9427 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9428 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9429 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9430 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9432 Constant *C = ConstantVector::get(CV);
9433 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9434 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9435 MachinePointerInfo::getConstantPool(),
9436 false, false, false, 16);
9437 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9439 // Shift sign bit right or left if the two operands have different types.
9440 if (SrcVT.bitsGT(VT)) {
9441 // Op0 is MVT::f32, Op1 is MVT::f64.
9442 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9443 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9444 DAG.getConstant(32, MVT::i32));
9445 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9446 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9447 DAG.getIntPtrConstant(0));
9450 // Clear first operand sign bit.
9452 if (VT == MVT::f64) {
9453 const fltSemantics &Sem = APFloat::IEEEdouble;
9454 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9455 APInt(64, ~(1ULL << 63)))));
9456 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9458 const fltSemantics &Sem = APFloat::IEEEsingle;
9459 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9460 APInt(32, ~(1U << 31)))));
9461 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9462 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9463 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9465 C = ConstantVector::get(CV);
9466 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9467 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9468 MachinePointerInfo::getConstantPool(),
9469 false, false, false, 16);
9470 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9472 // Or the value with the sign bit.
9473 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9476 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9477 SDValue N0 = Op.getOperand(0);
9479 MVT VT = Op.getSimpleValueType();
9481 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9482 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9483 DAG.getConstant(1, VT));
9484 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9487 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9489 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9490 SelectionDAG &DAG) {
9491 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9493 if (!Subtarget->hasSSE41())
9496 if (!Op->hasOneUse())
9499 SDNode *N = Op.getNode();
9502 SmallVector<SDValue, 8> Opnds;
9503 DenseMap<SDValue, unsigned> VecInMap;
9504 SmallVector<SDValue, 8> VecIns;
9505 EVT VT = MVT::Other;
9507 // Recognize a special case where a vector is casted into wide integer to
9509 Opnds.push_back(N->getOperand(0));
9510 Opnds.push_back(N->getOperand(1));
9512 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9513 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9514 // BFS traverse all OR'd operands.
9515 if (I->getOpcode() == ISD::OR) {
9516 Opnds.push_back(I->getOperand(0));
9517 Opnds.push_back(I->getOperand(1));
9518 // Re-evaluate the number of nodes to be traversed.
9519 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9523 // Quit if a non-EXTRACT_VECTOR_ELT
9524 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9527 // Quit if without a constant index.
9528 SDValue Idx = I->getOperand(1);
9529 if (!isa<ConstantSDNode>(Idx))
9532 SDValue ExtractedFromVec = I->getOperand(0);
9533 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9534 if (M == VecInMap.end()) {
9535 VT = ExtractedFromVec.getValueType();
9536 // Quit if not 128/256-bit vector.
9537 if (!VT.is128BitVector() && !VT.is256BitVector())
9539 // Quit if not the same type.
9540 if (VecInMap.begin() != VecInMap.end() &&
9541 VT != VecInMap.begin()->first.getValueType())
9543 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9544 VecIns.push_back(ExtractedFromVec);
9546 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9549 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9550 "Not extracted from 128-/256-bit vector.");
9552 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9554 for (DenseMap<SDValue, unsigned>::const_iterator
9555 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9556 // Quit if not all elements are used.
9557 if (I->second != FullMask)
9561 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9563 // Cast all vectors into TestVT for PTEST.
9564 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9565 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9567 // If more than one full vectors are evaluated, OR them first before PTEST.
9568 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9569 // Each iteration will OR 2 nodes and append the result until there is only
9570 // 1 node left, i.e. the final OR'd value of all vectors.
9571 SDValue LHS = VecIns[Slot];
9572 SDValue RHS = VecIns[Slot + 1];
9573 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9576 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9577 VecIns.back(), VecIns.back());
9580 /// Emit nodes that will be selected as "test Op0,Op0", or something
9582 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9583 SelectionDAG &DAG) const {
9586 if (Op.getValueType() == MVT::i1)
9587 // KORTEST instruction should be selected
9588 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9589 DAG.getConstant(0, Op.getValueType()));
9591 // CF and OF aren't always set the way we want. Determine which
9592 // of these we need.
9593 bool NeedCF = false;
9594 bool NeedOF = false;
9597 case X86::COND_A: case X86::COND_AE:
9598 case X86::COND_B: case X86::COND_BE:
9601 case X86::COND_G: case X86::COND_GE:
9602 case X86::COND_L: case X86::COND_LE:
9603 case X86::COND_O: case X86::COND_NO:
9607 // See if we can use the EFLAGS value from the operand instead of
9608 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9609 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9610 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9611 // Emit a CMP with 0, which is the TEST pattern.
9612 //if (Op.getValueType() == MVT::i1)
9613 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9614 // DAG.getConstant(0, MVT::i1));
9615 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9616 DAG.getConstant(0, Op.getValueType()));
9618 unsigned Opcode = 0;
9619 unsigned NumOperands = 0;
9621 // Truncate operations may prevent the merge of the SETCC instruction
9622 // and the arithmetic instruction before it. Attempt to truncate the operands
9623 // of the arithmetic instruction and use a reduced bit-width instruction.
9624 bool NeedTruncation = false;
9625 SDValue ArithOp = Op;
9626 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9627 SDValue Arith = Op->getOperand(0);
9628 // Both the trunc and the arithmetic op need to have one user each.
9629 if (Arith->hasOneUse())
9630 switch (Arith.getOpcode()) {
9637 NeedTruncation = true;
9643 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9644 // which may be the result of a CAST. We use the variable 'Op', which is the
9645 // non-casted variable when we check for possible users.
9646 switch (ArithOp.getOpcode()) {
9648 // Due to an isel shortcoming, be conservative if this add is likely to be
9649 // selected as part of a load-modify-store instruction. When the root node
9650 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9651 // uses of other nodes in the match, such as the ADD in this case. This
9652 // leads to the ADD being left around and reselected, with the result being
9653 // two adds in the output. Alas, even if none our users are stores, that
9654 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9655 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9656 // climbing the DAG back to the root, and it doesn't seem to be worth the
9658 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9659 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9660 if (UI->getOpcode() != ISD::CopyToReg &&
9661 UI->getOpcode() != ISD::SETCC &&
9662 UI->getOpcode() != ISD::STORE)
9665 if (ConstantSDNode *C =
9666 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9667 // An add of one will be selected as an INC.
9668 if (C->getAPIntValue() == 1) {
9669 Opcode = X86ISD::INC;
9674 // An add of negative one (subtract of one) will be selected as a DEC.
9675 if (C->getAPIntValue().isAllOnesValue()) {
9676 Opcode = X86ISD::DEC;
9682 // Otherwise use a regular EFLAGS-setting add.
9683 Opcode = X86ISD::ADD;
9687 // If the primary and result isn't used, don't bother using X86ISD::AND,
9688 // because a TEST instruction will be better.
9689 bool NonFlagUse = false;
9690 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9691 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9693 unsigned UOpNo = UI.getOperandNo();
9694 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9695 // Look pass truncate.
9696 UOpNo = User->use_begin().getOperandNo();
9697 User = *User->use_begin();
9700 if (User->getOpcode() != ISD::BRCOND &&
9701 User->getOpcode() != ISD::SETCC &&
9702 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9715 // Due to the ISEL shortcoming noted above, be conservative if this op is
9716 // likely to be selected as part of a load-modify-store instruction.
9717 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9718 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9719 if (UI->getOpcode() == ISD::STORE)
9722 // Otherwise use a regular EFLAGS-setting instruction.
9723 switch (ArithOp.getOpcode()) {
9724 default: llvm_unreachable("unexpected operator!");
9725 case ISD::SUB: Opcode = X86ISD::SUB; break;
9726 case ISD::XOR: Opcode = X86ISD::XOR; break;
9727 case ISD::AND: Opcode = X86ISD::AND; break;
9729 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9730 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9731 if (EFLAGS.getNode())
9734 Opcode = X86ISD::OR;
9748 return SDValue(Op.getNode(), 1);
9754 // If we found that truncation is beneficial, perform the truncation and
9756 if (NeedTruncation) {
9757 EVT VT = Op.getValueType();
9758 SDValue WideVal = Op->getOperand(0);
9759 EVT WideVT = WideVal.getValueType();
9760 unsigned ConvertedOp = 0;
9761 // Use a target machine opcode to prevent further DAGCombine
9762 // optimizations that may separate the arithmetic operations
9763 // from the setcc node.
9764 switch (WideVal.getOpcode()) {
9766 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9767 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9768 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9769 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9770 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9774 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9775 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9776 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9777 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9778 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9784 // Emit a CMP with 0, which is the TEST pattern.
9785 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9786 DAG.getConstant(0, Op.getValueType()));
9788 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9789 SmallVector<SDValue, 4> Ops;
9790 for (unsigned i = 0; i != NumOperands; ++i)
9791 Ops.push_back(Op.getOperand(i));
9793 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9794 DAG.ReplaceAllUsesWith(Op, New);
9795 return SDValue(New.getNode(), 1);
9798 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9800 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9801 SelectionDAG &DAG) const {
9803 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9804 if (C->getAPIntValue() == 0)
9805 return EmitTest(Op0, X86CC, DAG);
9807 if (Op0.getValueType() == MVT::i1)
9808 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
9811 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9812 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9813 // Do the comparison at i32 if it's smaller, besides the Atom case.
9814 // This avoids subregister aliasing issues. Keep the smaller reference
9815 // if we're optimizing for size, however, as that'll allow better folding
9816 // of memory operations.
9817 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9818 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9819 AttributeSet::FunctionIndex, Attribute::MinSize) &&
9820 !Subtarget->isAtom()) {
9822 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9823 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9824 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9826 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9827 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9828 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9830 return SDValue(Sub.getNode(), 1);
9832 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9835 /// Convert a comparison if required by the subtarget.
9836 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9837 SelectionDAG &DAG) const {
9838 // If the subtarget does not support the FUCOMI instruction, floating-point
9839 // comparisons have to be converted.
9840 if (Subtarget->hasCMov() ||
9841 Cmp.getOpcode() != X86ISD::CMP ||
9842 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9843 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9846 // The instruction selector will select an FUCOM instruction instead of
9847 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9848 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9849 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9851 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9852 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9853 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9854 DAG.getConstant(8, MVT::i8));
9855 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9856 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9859 static bool isAllOnes(SDValue V) {
9860 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9861 return C && C->isAllOnesValue();
9864 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9865 /// if it's possible.
9866 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9867 SDLoc dl, SelectionDAG &DAG) const {
9868 SDValue Op0 = And.getOperand(0);
9869 SDValue Op1 = And.getOperand(1);
9870 if (Op0.getOpcode() == ISD::TRUNCATE)
9871 Op0 = Op0.getOperand(0);
9872 if (Op1.getOpcode() == ISD::TRUNCATE)
9873 Op1 = Op1.getOperand(0);
9876 if (Op1.getOpcode() == ISD::SHL)
9877 std::swap(Op0, Op1);
9878 if (Op0.getOpcode() == ISD::SHL) {
9879 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9880 if (And00C->getZExtValue() == 1) {
9881 // If we looked past a truncate, check that it's only truncating away
9883 unsigned BitWidth = Op0.getValueSizeInBits();
9884 unsigned AndBitWidth = And.getValueSizeInBits();
9885 if (BitWidth > AndBitWidth) {
9887 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9888 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9892 RHS = Op0.getOperand(1);
9894 } else if (Op1.getOpcode() == ISD::Constant) {
9895 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9896 uint64_t AndRHSVal = AndRHS->getZExtValue();
9897 SDValue AndLHS = Op0;
9899 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9900 LHS = AndLHS.getOperand(0);
9901 RHS = AndLHS.getOperand(1);
9904 // Use BT if the immediate can't be encoded in a TEST instruction.
9905 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9907 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9911 if (LHS.getNode()) {
9912 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9913 // instruction. Since the shift amount is in-range-or-undefined, we know
9914 // that doing a bittest on the i32 value is ok. We extend to i32 because
9915 // the encoding for the i16 version is larger than the i32 version.
9916 // Also promote i16 to i32 for performance / code size reason.
9917 if (LHS.getValueType() == MVT::i8 ||
9918 LHS.getValueType() == MVT::i16)
9919 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9921 // If the operand types disagree, extend the shift amount to match. Since
9922 // BT ignores high bits (like shifts) we can use anyextend.
9923 if (LHS.getValueType() != RHS.getValueType())
9924 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9926 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9927 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9928 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9929 DAG.getConstant(Cond, MVT::i8), BT);
9935 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9937 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9942 // SSE Condition code mapping:
9951 switch (SetCCOpcode) {
9952 default: llvm_unreachable("Unexpected SETCC condition");
9954 case ISD::SETEQ: SSECC = 0; break;
9956 case ISD::SETGT: Swap = true; // Fallthrough
9958 case ISD::SETOLT: SSECC = 1; break;
9960 case ISD::SETGE: Swap = true; // Fallthrough
9962 case ISD::SETOLE: SSECC = 2; break;
9963 case ISD::SETUO: SSECC = 3; break;
9965 case ISD::SETNE: SSECC = 4; break;
9966 case ISD::SETULE: Swap = true; // Fallthrough
9967 case ISD::SETUGE: SSECC = 5; break;
9968 case ISD::SETULT: Swap = true; // Fallthrough
9969 case ISD::SETUGT: SSECC = 6; break;
9970 case ISD::SETO: SSECC = 7; break;
9972 case ISD::SETONE: SSECC = 8; break;
9975 std::swap(Op0, Op1);
9980 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9981 // ones, and then concatenate the result back.
9982 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9983 MVT VT = Op.getSimpleValueType();
9985 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9986 "Unsupported value type for operation");
9988 unsigned NumElems = VT.getVectorNumElements();
9990 SDValue CC = Op.getOperand(2);
9992 // Extract the LHS vectors
9993 SDValue LHS = Op.getOperand(0);
9994 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9995 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9997 // Extract the RHS vectors
9998 SDValue RHS = Op.getOperand(1);
9999 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10000 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10002 // Issue the operation on the smaller types and concatenate the result back
10003 MVT EltVT = VT.getVectorElementType();
10004 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10005 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10006 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10007 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10010 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10011 const X86Subtarget *Subtarget) {
10012 SDValue Op0 = Op.getOperand(0);
10013 SDValue Op1 = Op.getOperand(1);
10014 SDValue CC = Op.getOperand(2);
10015 MVT VT = Op.getSimpleValueType();
10018 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10019 Op.getValueType().getScalarType() == MVT::i1 &&
10020 "Cannot set masked compare for this operation");
10022 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10024 bool Unsigned = false;
10027 switch (SetCCOpcode) {
10028 default: llvm_unreachable("Unexpected SETCC condition");
10029 case ISD::SETNE: SSECC = 4; break;
10030 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10031 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10032 case ISD::SETLT: Swap = true; //fall-through
10033 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10034 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10035 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10036 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10037 case ISD::SETULE: Unsigned = true; //fall-through
10038 case ISD::SETLE: SSECC = 2; break;
10042 std::swap(Op0, Op1);
10044 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10045 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10046 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10047 DAG.getConstant(SSECC, MVT::i8));
10050 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10051 /// operand \p Op1. If non-trivial (for example because it's not constant)
10052 /// return an empty value.
10053 static SDValue ChangeVSETULTtoVSETULE(SDValue Op1, SelectionDAG &DAG)
10055 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10059 MVT VT = Op1.getSimpleValueType();
10060 MVT EVT = VT.getVectorElementType();
10061 unsigned n = VT.getVectorNumElements();
10062 SmallVector<SDValue, 8> ULTOp1;
10064 for (unsigned i = 0; i < n; ++i) {
10065 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10066 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10069 // Avoid underflow.
10070 APInt Val = Elt->getAPIntValue();
10074 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10077 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op1), VT, ULTOp1.data(),
10081 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10082 SelectionDAG &DAG) {
10083 SDValue Op0 = Op.getOperand(0);
10084 SDValue Op1 = Op.getOperand(1);
10085 SDValue CC = Op.getOperand(2);
10086 MVT VT = Op.getSimpleValueType();
10087 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10088 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10093 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10094 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10097 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10098 unsigned Opc = X86ISD::CMPP;
10099 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10100 assert(VT.getVectorNumElements() <= 16);
10101 Opc = X86ISD::CMPM;
10103 // In the two special cases we can't handle, emit two comparisons.
10106 unsigned CombineOpc;
10107 if (SetCCOpcode == ISD::SETUEQ) {
10108 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10110 assert(SetCCOpcode == ISD::SETONE);
10111 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10114 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10115 DAG.getConstant(CC0, MVT::i8));
10116 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10117 DAG.getConstant(CC1, MVT::i8));
10118 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10120 // Handle all other FP comparisons here.
10121 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10122 DAG.getConstant(SSECC, MVT::i8));
10125 // Break 256-bit integer vector compare into smaller ones.
10126 if (VT.is256BitVector() && !Subtarget->hasInt256())
10127 return Lower256IntVSETCC(Op, DAG);
10129 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10130 EVT OpVT = Op1.getValueType();
10131 if (Subtarget->hasAVX512()) {
10132 if (Op1.getValueType().is512BitVector() ||
10133 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10134 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10136 // In AVX-512 architecture setcc returns mask with i1 elements,
10137 // But there is no compare instruction for i8 and i16 elements.
10138 // We are not talking about 512-bit operands in this case, these
10139 // types are illegal.
10141 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10142 OpVT.getVectorElementType().getSizeInBits() >= 8))
10143 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10144 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10147 // We are handling one of the integer comparisons here. Since SSE only has
10148 // GT and EQ comparisons for integer, swapping operands and multiple
10149 // operations may be required for some comparisons.
10151 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10152 bool Subus = false;
10154 switch (SetCCOpcode) {
10155 default: llvm_unreachable("Unexpected SETCC condition");
10156 case ISD::SETNE: Invert = true;
10157 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10158 case ISD::SETLT: Swap = true;
10159 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10160 case ISD::SETGE: Swap = true;
10161 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10162 Invert = true; break;
10163 case ISD::SETULT: Swap = true;
10164 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10165 FlipSigns = true; break;
10166 case ISD::SETUGE: Swap = true;
10167 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10168 FlipSigns = true; Invert = true; break;
10171 // Special case: Use min/max operations for SETULE/SETUGE
10172 MVT VET = VT.getVectorElementType();
10174 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10175 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10178 switch (SetCCOpcode) {
10180 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10181 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10184 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10187 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10188 if (!MinMax && hasSubus) {
10189 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10191 // t = psubus Op0, Op1
10192 // pcmpeq t, <0..0>
10193 switch (SetCCOpcode) {
10195 case ISD::SETULT: {
10196 // If the comparison is against a constant we can turn this into a
10197 // setule. With psubus, setule does not require a swap. This is
10198 // beneficial because the constant in the register is no longer
10199 // destructed as the destination so it can be hoisted out of a loop.
10200 // Only do this pre-AVX since vpcmp* is no longer destructive.
10201 if (Subtarget->hasAVX())
10203 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(Op1, DAG);
10204 if (ULEOp1.getNode()) {
10206 Subus = true; Invert = false; Swap = false;
10210 // Psubus is better than flip-sign because it requires no inversion.
10211 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10212 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10216 Opc = X86ISD::SUBUS;
10222 std::swap(Op0, Op1);
10224 // Check that the operation in question is available (most are plain SSE2,
10225 // but PCMPGTQ and PCMPEQQ have different requirements).
10226 if (VT == MVT::v2i64) {
10227 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10228 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10230 // First cast everything to the right type.
10231 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10232 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10234 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10235 // bits of the inputs before performing those operations. The lower
10236 // compare is always unsigned.
10239 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10241 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10242 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10243 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10244 Sign, Zero, Sign, Zero);
10246 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10247 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10249 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10250 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10251 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10253 // Create masks for only the low parts/high parts of the 64 bit integers.
10254 static const int MaskHi[] = { 1, 1, 3, 3 };
10255 static const int MaskLo[] = { 0, 0, 2, 2 };
10256 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10257 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10258 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10260 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10261 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10264 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10266 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10269 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10270 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10271 // pcmpeqd + pshufd + pand.
10272 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10274 // First cast everything to the right type.
10275 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10276 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10279 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10281 // Make sure the lower and upper halves are both all-ones.
10282 static const int Mask[] = { 1, 0, 3, 2 };
10283 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10284 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10287 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10289 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10293 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10294 // bits of the inputs before performing those operations.
10296 EVT EltVT = VT.getVectorElementType();
10297 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10298 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10299 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10302 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10304 // If the logical-not of the result is required, perform that now.
10306 Result = DAG.getNOT(dl, Result, VT);
10309 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10312 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10313 getZeroVector(VT, Subtarget, DAG, dl));
10318 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10320 MVT VT = Op.getSimpleValueType();
10322 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10324 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10325 && "SetCC type must be 8-bit or 1-bit integer");
10326 SDValue Op0 = Op.getOperand(0);
10327 SDValue Op1 = Op.getOperand(1);
10329 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10331 // Optimize to BT if possible.
10332 // Lower (X & (1 << N)) == 0 to BT(X, N).
10333 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10334 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10335 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10336 Op1.getOpcode() == ISD::Constant &&
10337 cast<ConstantSDNode>(Op1)->isNullValue() &&
10338 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10339 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10340 if (NewSetCC.getNode())
10344 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10346 if (Op1.getOpcode() == ISD::Constant &&
10347 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10348 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10349 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10351 // If the input is a setcc, then reuse the input setcc or use a new one with
10352 // the inverted condition.
10353 if (Op0.getOpcode() == X86ISD::SETCC) {
10354 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10355 bool Invert = (CC == ISD::SETNE) ^
10356 cast<ConstantSDNode>(Op1)->isNullValue();
10360 CCode = X86::GetOppositeBranchCondition(CCode);
10361 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10362 DAG.getConstant(CCode, MVT::i8),
10363 Op0.getOperand(1));
10365 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10369 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10370 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10371 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10373 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10374 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10377 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10378 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10379 if (X86CC == X86::COND_INVALID)
10382 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10383 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10384 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10385 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10387 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10391 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10392 static bool isX86LogicalCmp(SDValue Op) {
10393 unsigned Opc = Op.getNode()->getOpcode();
10394 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10395 Opc == X86ISD::SAHF)
10397 if (Op.getResNo() == 1 &&
10398 (Opc == X86ISD::ADD ||
10399 Opc == X86ISD::SUB ||
10400 Opc == X86ISD::ADC ||
10401 Opc == X86ISD::SBB ||
10402 Opc == X86ISD::SMUL ||
10403 Opc == X86ISD::UMUL ||
10404 Opc == X86ISD::INC ||
10405 Opc == X86ISD::DEC ||
10406 Opc == X86ISD::OR ||
10407 Opc == X86ISD::XOR ||
10408 Opc == X86ISD::AND))
10411 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10417 static bool isZero(SDValue V) {
10418 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10419 return C && C->isNullValue();
10422 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10423 if (V.getOpcode() != ISD::TRUNCATE)
10426 SDValue VOp0 = V.getOperand(0);
10427 unsigned InBits = VOp0.getValueSizeInBits();
10428 unsigned Bits = V.getValueSizeInBits();
10429 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10432 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10433 bool addTest = true;
10434 SDValue Cond = Op.getOperand(0);
10435 SDValue Op1 = Op.getOperand(1);
10436 SDValue Op2 = Op.getOperand(2);
10438 EVT VT = Op1.getValueType();
10441 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10442 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10443 // sequence later on.
10444 if (Cond.getOpcode() == ISD::SETCC &&
10445 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10446 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10447 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10448 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10449 int SSECC = translateX86FSETCC(
10450 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10453 if (Subtarget->hasAVX512()) {
10454 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10455 DAG.getConstant(SSECC, MVT::i8));
10456 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10458 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10459 DAG.getConstant(SSECC, MVT::i8));
10460 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10461 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10462 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10466 if (Cond.getOpcode() == ISD::SETCC) {
10467 SDValue NewCond = LowerSETCC(Cond, DAG);
10468 if (NewCond.getNode())
10472 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10473 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10474 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10475 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10476 if (Cond.getOpcode() == X86ISD::SETCC &&
10477 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10478 isZero(Cond.getOperand(1).getOperand(1))) {
10479 SDValue Cmp = Cond.getOperand(1);
10481 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10483 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10484 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10485 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10487 SDValue CmpOp0 = Cmp.getOperand(0);
10488 // Apply further optimizations for special cases
10489 // (select (x != 0), -1, 0) -> neg & sbb
10490 // (select (x == 0), 0, -1) -> neg & sbb
10491 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10492 if (YC->isNullValue() &&
10493 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10494 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10495 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10496 DAG.getConstant(0, CmpOp0.getValueType()),
10498 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10499 DAG.getConstant(X86::COND_B, MVT::i8),
10500 SDValue(Neg.getNode(), 1));
10504 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10505 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10506 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10508 SDValue Res = // Res = 0 or -1.
10509 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10510 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10512 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10513 Res = DAG.getNOT(DL, Res, Res.getValueType());
10515 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10516 if (N2C == 0 || !N2C->isNullValue())
10517 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10522 // Look past (and (setcc_carry (cmp ...)), 1).
10523 if (Cond.getOpcode() == ISD::AND &&
10524 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10525 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10526 if (C && C->getAPIntValue() == 1)
10527 Cond = Cond.getOperand(0);
10530 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10531 // setting operand in place of the X86ISD::SETCC.
10532 unsigned CondOpcode = Cond.getOpcode();
10533 if (CondOpcode == X86ISD::SETCC ||
10534 CondOpcode == X86ISD::SETCC_CARRY) {
10535 CC = Cond.getOperand(0);
10537 SDValue Cmp = Cond.getOperand(1);
10538 unsigned Opc = Cmp.getOpcode();
10539 MVT VT = Op.getSimpleValueType();
10541 bool IllegalFPCMov = false;
10542 if (VT.isFloatingPoint() && !VT.isVector() &&
10543 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10544 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10546 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10547 Opc == X86ISD::BT) { // FIXME
10551 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10552 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10553 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10554 Cond.getOperand(0).getValueType() != MVT::i8)) {
10555 SDValue LHS = Cond.getOperand(0);
10556 SDValue RHS = Cond.getOperand(1);
10557 unsigned X86Opcode;
10560 switch (CondOpcode) {
10561 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10562 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10563 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10564 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10565 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10566 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10567 default: llvm_unreachable("unexpected overflowing operator");
10569 if (CondOpcode == ISD::UMULO)
10570 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10573 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10575 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10577 if (CondOpcode == ISD::UMULO)
10578 Cond = X86Op.getValue(2);
10580 Cond = X86Op.getValue(1);
10582 CC = DAG.getConstant(X86Cond, MVT::i8);
10587 // Look pass the truncate if the high bits are known zero.
10588 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10589 Cond = Cond.getOperand(0);
10591 // We know the result of AND is compared against zero. Try to match
10593 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10594 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10595 if (NewSetCC.getNode()) {
10596 CC = NewSetCC.getOperand(0);
10597 Cond = NewSetCC.getOperand(1);
10604 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10605 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10608 // a < b ? -1 : 0 -> RES = ~setcc_carry
10609 // a < b ? 0 : -1 -> RES = setcc_carry
10610 // a >= b ? -1 : 0 -> RES = setcc_carry
10611 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10612 if (Cond.getOpcode() == X86ISD::SUB) {
10613 Cond = ConvertCmpIfNecessary(Cond, DAG);
10614 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10616 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10617 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10618 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10619 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10620 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10621 return DAG.getNOT(DL, Res, Res.getValueType());
10626 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10627 // widen the cmov and push the truncate through. This avoids introducing a new
10628 // branch during isel and doesn't add any extensions.
10629 if (Op.getValueType() == MVT::i8 &&
10630 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10631 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10632 if (T1.getValueType() == T2.getValueType() &&
10633 // Blacklist CopyFromReg to avoid partial register stalls.
10634 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10635 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10636 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10637 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10641 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10642 // condition is true.
10643 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10644 SDValue Ops[] = { Op2, Op1, CC, Cond };
10645 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10648 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10649 MVT VT = Op->getSimpleValueType(0);
10650 SDValue In = Op->getOperand(0);
10651 MVT InVT = In.getSimpleValueType();
10654 unsigned int NumElts = VT.getVectorNumElements();
10655 if (NumElts != 8 && NumElts != 16)
10658 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10659 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10661 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10662 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10664 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10665 Constant *C = ConstantInt::get(*DAG.getContext(),
10666 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10668 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10669 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10670 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10671 MachinePointerInfo::getConstantPool(),
10672 false, false, false, Alignment);
10673 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10674 if (VT.is512BitVector())
10676 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10679 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10680 SelectionDAG &DAG) {
10681 MVT VT = Op->getSimpleValueType(0);
10682 SDValue In = Op->getOperand(0);
10683 MVT InVT = In.getSimpleValueType();
10686 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10687 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10689 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10690 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10691 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10694 if (Subtarget->hasInt256())
10695 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10697 // Optimize vectors in AVX mode
10698 // Sign extend v8i16 to v8i32 and
10701 // Divide input vector into two parts
10702 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10703 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10704 // concat the vectors to original VT
10706 unsigned NumElems = InVT.getVectorNumElements();
10707 SDValue Undef = DAG.getUNDEF(InVT);
10709 SmallVector<int,8> ShufMask1(NumElems, -1);
10710 for (unsigned i = 0; i != NumElems/2; ++i)
10713 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10715 SmallVector<int,8> ShufMask2(NumElems, -1);
10716 for (unsigned i = 0; i != NumElems/2; ++i)
10717 ShufMask2[i] = i + NumElems/2;
10719 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10721 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10722 VT.getVectorNumElements()/2);
10724 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10725 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10727 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10730 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10731 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10732 // from the AND / OR.
10733 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10734 Opc = Op.getOpcode();
10735 if (Opc != ISD::OR && Opc != ISD::AND)
10737 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10738 Op.getOperand(0).hasOneUse() &&
10739 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10740 Op.getOperand(1).hasOneUse());
10743 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10744 // 1 and that the SETCC node has a single use.
10745 static bool isXor1OfSetCC(SDValue Op) {
10746 if (Op.getOpcode() != ISD::XOR)
10748 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10749 if (N1C && N1C->getAPIntValue() == 1) {
10750 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10751 Op.getOperand(0).hasOneUse();
10756 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10757 bool addTest = true;
10758 SDValue Chain = Op.getOperand(0);
10759 SDValue Cond = Op.getOperand(1);
10760 SDValue Dest = Op.getOperand(2);
10763 bool Inverted = false;
10765 if (Cond.getOpcode() == ISD::SETCC) {
10766 // Check for setcc([su]{add,sub,mul}o == 0).
10767 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10768 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10769 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10770 Cond.getOperand(0).getResNo() == 1 &&
10771 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10772 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10773 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10774 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10775 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10776 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10778 Cond = Cond.getOperand(0);
10780 SDValue NewCond = LowerSETCC(Cond, DAG);
10781 if (NewCond.getNode())
10786 // FIXME: LowerXALUO doesn't handle these!!
10787 else if (Cond.getOpcode() == X86ISD::ADD ||
10788 Cond.getOpcode() == X86ISD::SUB ||
10789 Cond.getOpcode() == X86ISD::SMUL ||
10790 Cond.getOpcode() == X86ISD::UMUL)
10791 Cond = LowerXALUO(Cond, DAG);
10794 // Look pass (and (setcc_carry (cmp ...)), 1).
10795 if (Cond.getOpcode() == ISD::AND &&
10796 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10797 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10798 if (C && C->getAPIntValue() == 1)
10799 Cond = Cond.getOperand(0);
10802 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10803 // setting operand in place of the X86ISD::SETCC.
10804 unsigned CondOpcode = Cond.getOpcode();
10805 if (CondOpcode == X86ISD::SETCC ||
10806 CondOpcode == X86ISD::SETCC_CARRY) {
10807 CC = Cond.getOperand(0);
10809 SDValue Cmp = Cond.getOperand(1);
10810 unsigned Opc = Cmp.getOpcode();
10811 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10812 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10816 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10820 // These can only come from an arithmetic instruction with overflow,
10821 // e.g. SADDO, UADDO.
10822 Cond = Cond.getNode()->getOperand(1);
10828 CondOpcode = Cond.getOpcode();
10829 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10830 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10831 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10832 Cond.getOperand(0).getValueType() != MVT::i8)) {
10833 SDValue LHS = Cond.getOperand(0);
10834 SDValue RHS = Cond.getOperand(1);
10835 unsigned X86Opcode;
10838 // Keep this in sync with LowerXALUO, otherwise we might create redundant
10839 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10841 switch (CondOpcode) {
10842 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10844 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10846 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10849 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10850 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10852 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10854 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10857 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10858 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10859 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10860 default: llvm_unreachable("unexpected overflowing operator");
10863 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10864 if (CondOpcode == ISD::UMULO)
10865 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10868 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10870 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10872 if (CondOpcode == ISD::UMULO)
10873 Cond = X86Op.getValue(2);
10875 Cond = X86Op.getValue(1);
10877 CC = DAG.getConstant(X86Cond, MVT::i8);
10881 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10882 SDValue Cmp = Cond.getOperand(0).getOperand(1);
10883 if (CondOpc == ISD::OR) {
10884 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10885 // two branches instead of an explicit OR instruction with a
10887 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10888 isX86LogicalCmp(Cmp)) {
10889 CC = Cond.getOperand(0).getOperand(0);
10890 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10891 Chain, Dest, CC, Cmp);
10892 CC = Cond.getOperand(1).getOperand(0);
10896 } else { // ISD::AND
10897 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10898 // two branches instead of an explicit AND instruction with a
10899 // separate test. However, we only do this if this block doesn't
10900 // have a fall-through edge, because this requires an explicit
10901 // jmp when the condition is false.
10902 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10903 isX86LogicalCmp(Cmp) &&
10904 Op.getNode()->hasOneUse()) {
10905 X86::CondCode CCode =
10906 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10907 CCode = X86::GetOppositeBranchCondition(CCode);
10908 CC = DAG.getConstant(CCode, MVT::i8);
10909 SDNode *User = *Op.getNode()->use_begin();
10910 // Look for an unconditional branch following this conditional branch.
10911 // We need this because we need to reverse the successors in order
10912 // to implement FCMP_OEQ.
10913 if (User->getOpcode() == ISD::BR) {
10914 SDValue FalseBB = User->getOperand(1);
10916 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10917 assert(NewBR == User);
10921 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10922 Chain, Dest, CC, Cmp);
10923 X86::CondCode CCode =
10924 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10925 CCode = X86::GetOppositeBranchCondition(CCode);
10926 CC = DAG.getConstant(CCode, MVT::i8);
10932 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10933 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10934 // It should be transformed during dag combiner except when the condition
10935 // is set by a arithmetics with overflow node.
10936 X86::CondCode CCode =
10937 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10938 CCode = X86::GetOppositeBranchCondition(CCode);
10939 CC = DAG.getConstant(CCode, MVT::i8);
10940 Cond = Cond.getOperand(0).getOperand(1);
10942 } else if (Cond.getOpcode() == ISD::SETCC &&
10943 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10944 // For FCMP_OEQ, we can emit
10945 // two branches instead of an explicit AND instruction with a
10946 // separate test. However, we only do this if this block doesn't
10947 // have a fall-through edge, because this requires an explicit
10948 // jmp when the condition is false.
10949 if (Op.getNode()->hasOneUse()) {
10950 SDNode *User = *Op.getNode()->use_begin();
10951 // Look for an unconditional branch following this conditional branch.
10952 // We need this because we need to reverse the successors in order
10953 // to implement FCMP_OEQ.
10954 if (User->getOpcode() == ISD::BR) {
10955 SDValue FalseBB = User->getOperand(1);
10957 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10958 assert(NewBR == User);
10962 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10963 Cond.getOperand(0), Cond.getOperand(1));
10964 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10965 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10966 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10967 Chain, Dest, CC, Cmp);
10968 CC = DAG.getConstant(X86::COND_P, MVT::i8);
10973 } else if (Cond.getOpcode() == ISD::SETCC &&
10974 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10975 // For FCMP_UNE, we can emit
10976 // two branches instead of an explicit AND instruction with a
10977 // separate test. However, we only do this if this block doesn't
10978 // have a fall-through edge, because this requires an explicit
10979 // jmp when the condition is false.
10980 if (Op.getNode()->hasOneUse()) {
10981 SDNode *User = *Op.getNode()->use_begin();
10982 // Look for an unconditional branch following this conditional branch.
10983 // We need this because we need to reverse the successors in order
10984 // to implement FCMP_UNE.
10985 if (User->getOpcode() == ISD::BR) {
10986 SDValue FalseBB = User->getOperand(1);
10988 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10989 assert(NewBR == User);
10992 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10993 Cond.getOperand(0), Cond.getOperand(1));
10994 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10995 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10996 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10997 Chain, Dest, CC, Cmp);
10998 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11008 // Look pass the truncate if the high bits are known zero.
11009 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11010 Cond = Cond.getOperand(0);
11012 // We know the result of AND is compared against zero. Try to match
11014 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11015 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11016 if (NewSetCC.getNode()) {
11017 CC = NewSetCC.getOperand(0);
11018 Cond = NewSetCC.getOperand(1);
11025 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11026 Cond = EmitTest(Cond, X86::COND_NE, DAG);
11028 Cond = ConvertCmpIfNecessary(Cond, DAG);
11029 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11030 Chain, Dest, CC, Cond);
11033 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11034 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11035 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11036 // that the guard pages used by the OS virtual memory manager are allocated in
11037 // correct sequence.
11039 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11040 SelectionDAG &DAG) const {
11041 assert((Subtarget->isOSWindows() ||
11042 getTargetMachine().Options.EnableSegmentedStacks) &&
11043 "This should be used only on Windows targets or when segmented stacks "
11045 assert(!Subtarget->isTargetMacho() && "Not implemented");
11049 SDValue Chain = Op.getOperand(0);
11050 SDValue Size = Op.getOperand(1);
11051 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11052 EVT VT = Op.getNode()->getValueType(0);
11054 bool Is64Bit = Subtarget->is64Bit();
11055 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11057 if (getTargetMachine().Options.EnableSegmentedStacks) {
11058 MachineFunction &MF = DAG.getMachineFunction();
11059 MachineRegisterInfo &MRI = MF.getRegInfo();
11062 // The 64 bit implementation of segmented stacks needs to clobber both r10
11063 // r11. This makes it impossible to use it along with nested parameters.
11064 const Function *F = MF.getFunction();
11066 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11068 if (I->hasNestAttr())
11069 report_fatal_error("Cannot use segmented stacks with functions that "
11070 "have nested arguments.");
11073 const TargetRegisterClass *AddrRegClass =
11074 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11075 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11076 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11077 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11078 DAG.getRegister(Vreg, SPTy));
11079 SDValue Ops1[2] = { Value, Chain };
11080 return DAG.getMergeValues(Ops1, 2, dl);
11083 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11085 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11086 Flag = Chain.getValue(1);
11087 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11089 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11091 const X86RegisterInfo *RegInfo =
11092 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11093 unsigned SPReg = RegInfo->getStackRegister();
11094 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11095 Chain = SP.getValue(1);
11098 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11099 DAG.getConstant(-(uint64_t)Align, VT));
11100 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11103 SDValue Ops1[2] = { SP, Chain };
11104 return DAG.getMergeValues(Ops1, 2, dl);
11108 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11109 MachineFunction &MF = DAG.getMachineFunction();
11110 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11112 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11115 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11116 // vastart just stores the address of the VarArgsFrameIndex slot into the
11117 // memory location argument.
11118 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11120 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11121 MachinePointerInfo(SV), false, false, 0);
11125 // gp_offset (0 - 6 * 8)
11126 // fp_offset (48 - 48 + 8 * 16)
11127 // overflow_arg_area (point to parameters coming in memory).
11129 SmallVector<SDValue, 8> MemOps;
11130 SDValue FIN = Op.getOperand(1);
11132 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11133 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11135 FIN, MachinePointerInfo(SV), false, false, 0);
11136 MemOps.push_back(Store);
11139 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11140 FIN, DAG.getIntPtrConstant(4));
11141 Store = DAG.getStore(Op.getOperand(0), DL,
11142 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11144 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11145 MemOps.push_back(Store);
11147 // Store ptr to overflow_arg_area
11148 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11149 FIN, DAG.getIntPtrConstant(4));
11150 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11152 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11153 MachinePointerInfo(SV, 8),
11155 MemOps.push_back(Store);
11157 // Store ptr to reg_save_area.
11158 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11159 FIN, DAG.getIntPtrConstant(8));
11160 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11162 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11163 MachinePointerInfo(SV, 16), false, false, 0);
11164 MemOps.push_back(Store);
11165 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11166 &MemOps[0], MemOps.size());
11169 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11170 assert(Subtarget->is64Bit() &&
11171 "LowerVAARG only handles 64-bit va_arg!");
11172 assert((Subtarget->isTargetLinux() ||
11173 Subtarget->isTargetDarwin()) &&
11174 "Unhandled target in LowerVAARG");
11175 assert(Op.getNode()->getNumOperands() == 4);
11176 SDValue Chain = Op.getOperand(0);
11177 SDValue SrcPtr = Op.getOperand(1);
11178 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11179 unsigned Align = Op.getConstantOperandVal(3);
11182 EVT ArgVT = Op.getNode()->getValueType(0);
11183 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11184 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11187 // Decide which area this value should be read from.
11188 // TODO: Implement the AMD64 ABI in its entirety. This simple
11189 // selection mechanism works only for the basic types.
11190 if (ArgVT == MVT::f80) {
11191 llvm_unreachable("va_arg for f80 not yet implemented");
11192 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11193 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11194 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11195 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11197 llvm_unreachable("Unhandled argument type in LowerVAARG");
11200 if (ArgMode == 2) {
11201 // Sanity Check: Make sure using fp_offset makes sense.
11202 assert(!getTargetMachine().Options.UseSoftFloat &&
11203 !(DAG.getMachineFunction()
11204 .getFunction()->getAttributes()
11205 .hasAttribute(AttributeSet::FunctionIndex,
11206 Attribute::NoImplicitFloat)) &&
11207 Subtarget->hasSSE1());
11210 // Insert VAARG_64 node into the DAG
11211 // VAARG_64 returns two values: Variable Argument Address, Chain
11212 SmallVector<SDValue, 11> InstOps;
11213 InstOps.push_back(Chain);
11214 InstOps.push_back(SrcPtr);
11215 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11216 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11217 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11218 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11219 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11220 VTs, &InstOps[0], InstOps.size(),
11222 MachinePointerInfo(SV),
11224 /*Volatile=*/false,
11226 /*WriteMem=*/true);
11227 Chain = VAARG.getValue(1);
11229 // Load the next argument and return it
11230 return DAG.getLoad(ArgVT, dl,
11233 MachinePointerInfo(),
11234 false, false, false, 0);
11237 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11238 SelectionDAG &DAG) {
11239 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11240 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11241 SDValue Chain = Op.getOperand(0);
11242 SDValue DstPtr = Op.getOperand(1);
11243 SDValue SrcPtr = Op.getOperand(2);
11244 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11245 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11248 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11249 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11251 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11254 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11255 // amount is a constant. Takes immediate version of shift as input.
11256 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11257 SDValue SrcOp, uint64_t ShiftAmt,
11258 SelectionDAG &DAG) {
11259 MVT ElementType = VT.getVectorElementType();
11261 // Check for ShiftAmt >= element width
11262 if (ShiftAmt >= ElementType.getSizeInBits()) {
11263 if (Opc == X86ISD::VSRAI)
11264 ShiftAmt = ElementType.getSizeInBits() - 1;
11266 return DAG.getConstant(0, VT);
11269 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11270 && "Unknown target vector shift-by-constant node");
11272 // Fold this packed vector shift into a build vector if SrcOp is a
11273 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11274 if (VT == SrcOp.getSimpleValueType() &&
11275 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11276 SmallVector<SDValue, 8> Elts;
11277 unsigned NumElts = SrcOp->getNumOperands();
11278 ConstantSDNode *ND;
11281 default: llvm_unreachable(0);
11282 case X86ISD::VSHLI:
11283 for (unsigned i=0; i!=NumElts; ++i) {
11284 SDValue CurrentOp = SrcOp->getOperand(i);
11285 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11286 Elts.push_back(CurrentOp);
11289 ND = cast<ConstantSDNode>(CurrentOp);
11290 const APInt &C = ND->getAPIntValue();
11291 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11294 case X86ISD::VSRLI:
11295 for (unsigned i=0; i!=NumElts; ++i) {
11296 SDValue CurrentOp = SrcOp->getOperand(i);
11297 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11298 Elts.push_back(CurrentOp);
11301 ND = cast<ConstantSDNode>(CurrentOp);
11302 const APInt &C = ND->getAPIntValue();
11303 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11306 case X86ISD::VSRAI:
11307 for (unsigned i=0; i!=NumElts; ++i) {
11308 SDValue CurrentOp = SrcOp->getOperand(i);
11309 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11310 Elts.push_back(CurrentOp);
11313 ND = cast<ConstantSDNode>(CurrentOp);
11314 const APInt &C = ND->getAPIntValue();
11315 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11320 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11323 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11326 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11327 // may or may not be a constant. Takes immediate version of shift as input.
11328 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11329 SDValue SrcOp, SDValue ShAmt,
11330 SelectionDAG &DAG) {
11331 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11333 // Catch shift-by-constant.
11334 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11335 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11336 CShAmt->getZExtValue(), DAG);
11338 // Change opcode to non-immediate version
11340 default: llvm_unreachable("Unknown target vector shift node");
11341 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11342 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11343 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11346 // Need to build a vector containing shift amount
11347 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11350 ShOps[1] = DAG.getConstant(0, MVT::i32);
11351 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11352 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11354 // The return type has to be a 128-bit type with the same element
11355 // type as the input type.
11356 MVT EltVT = VT.getVectorElementType();
11357 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11359 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11360 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11363 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11365 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11367 default: return SDValue(); // Don't custom lower most intrinsics.
11368 // Comparison intrinsics.
11369 case Intrinsic::x86_sse_comieq_ss:
11370 case Intrinsic::x86_sse_comilt_ss:
11371 case Intrinsic::x86_sse_comile_ss:
11372 case Intrinsic::x86_sse_comigt_ss:
11373 case Intrinsic::x86_sse_comige_ss:
11374 case Intrinsic::x86_sse_comineq_ss:
11375 case Intrinsic::x86_sse_ucomieq_ss:
11376 case Intrinsic::x86_sse_ucomilt_ss:
11377 case Intrinsic::x86_sse_ucomile_ss:
11378 case Intrinsic::x86_sse_ucomigt_ss:
11379 case Intrinsic::x86_sse_ucomige_ss:
11380 case Intrinsic::x86_sse_ucomineq_ss:
11381 case Intrinsic::x86_sse2_comieq_sd:
11382 case Intrinsic::x86_sse2_comilt_sd:
11383 case Intrinsic::x86_sse2_comile_sd:
11384 case Intrinsic::x86_sse2_comigt_sd:
11385 case Intrinsic::x86_sse2_comige_sd:
11386 case Intrinsic::x86_sse2_comineq_sd:
11387 case Intrinsic::x86_sse2_ucomieq_sd:
11388 case Intrinsic::x86_sse2_ucomilt_sd:
11389 case Intrinsic::x86_sse2_ucomile_sd:
11390 case Intrinsic::x86_sse2_ucomigt_sd:
11391 case Intrinsic::x86_sse2_ucomige_sd:
11392 case Intrinsic::x86_sse2_ucomineq_sd: {
11396 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11397 case Intrinsic::x86_sse_comieq_ss:
11398 case Intrinsic::x86_sse2_comieq_sd:
11399 Opc = X86ISD::COMI;
11402 case Intrinsic::x86_sse_comilt_ss:
11403 case Intrinsic::x86_sse2_comilt_sd:
11404 Opc = X86ISD::COMI;
11407 case Intrinsic::x86_sse_comile_ss:
11408 case Intrinsic::x86_sse2_comile_sd:
11409 Opc = X86ISD::COMI;
11412 case Intrinsic::x86_sse_comigt_ss:
11413 case Intrinsic::x86_sse2_comigt_sd:
11414 Opc = X86ISD::COMI;
11417 case Intrinsic::x86_sse_comige_ss:
11418 case Intrinsic::x86_sse2_comige_sd:
11419 Opc = X86ISD::COMI;
11422 case Intrinsic::x86_sse_comineq_ss:
11423 case Intrinsic::x86_sse2_comineq_sd:
11424 Opc = X86ISD::COMI;
11427 case Intrinsic::x86_sse_ucomieq_ss:
11428 case Intrinsic::x86_sse2_ucomieq_sd:
11429 Opc = X86ISD::UCOMI;
11432 case Intrinsic::x86_sse_ucomilt_ss:
11433 case Intrinsic::x86_sse2_ucomilt_sd:
11434 Opc = X86ISD::UCOMI;
11437 case Intrinsic::x86_sse_ucomile_ss:
11438 case Intrinsic::x86_sse2_ucomile_sd:
11439 Opc = X86ISD::UCOMI;
11442 case Intrinsic::x86_sse_ucomigt_ss:
11443 case Intrinsic::x86_sse2_ucomigt_sd:
11444 Opc = X86ISD::UCOMI;
11447 case Intrinsic::x86_sse_ucomige_ss:
11448 case Intrinsic::x86_sse2_ucomige_sd:
11449 Opc = X86ISD::UCOMI;
11452 case Intrinsic::x86_sse_ucomineq_ss:
11453 case Intrinsic::x86_sse2_ucomineq_sd:
11454 Opc = X86ISD::UCOMI;
11459 SDValue LHS = Op.getOperand(1);
11460 SDValue RHS = Op.getOperand(2);
11461 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11462 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11463 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11464 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11465 DAG.getConstant(X86CC, MVT::i8), Cond);
11466 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11469 // Arithmetic intrinsics.
11470 case Intrinsic::x86_sse2_pmulu_dq:
11471 case Intrinsic::x86_avx2_pmulu_dq:
11472 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11473 Op.getOperand(1), Op.getOperand(2));
11475 // SSE2/AVX2 sub with unsigned saturation intrinsics
11476 case Intrinsic::x86_sse2_psubus_b:
11477 case Intrinsic::x86_sse2_psubus_w:
11478 case Intrinsic::x86_avx2_psubus_b:
11479 case Intrinsic::x86_avx2_psubus_w:
11480 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11481 Op.getOperand(1), Op.getOperand(2));
11483 // SSE3/AVX horizontal add/sub intrinsics
11484 case Intrinsic::x86_sse3_hadd_ps:
11485 case Intrinsic::x86_sse3_hadd_pd:
11486 case Intrinsic::x86_avx_hadd_ps_256:
11487 case Intrinsic::x86_avx_hadd_pd_256:
11488 case Intrinsic::x86_sse3_hsub_ps:
11489 case Intrinsic::x86_sse3_hsub_pd:
11490 case Intrinsic::x86_avx_hsub_ps_256:
11491 case Intrinsic::x86_avx_hsub_pd_256:
11492 case Intrinsic::x86_ssse3_phadd_w_128:
11493 case Intrinsic::x86_ssse3_phadd_d_128:
11494 case Intrinsic::x86_avx2_phadd_w:
11495 case Intrinsic::x86_avx2_phadd_d:
11496 case Intrinsic::x86_ssse3_phsub_w_128:
11497 case Intrinsic::x86_ssse3_phsub_d_128:
11498 case Intrinsic::x86_avx2_phsub_w:
11499 case Intrinsic::x86_avx2_phsub_d: {
11502 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11503 case Intrinsic::x86_sse3_hadd_ps:
11504 case Intrinsic::x86_sse3_hadd_pd:
11505 case Intrinsic::x86_avx_hadd_ps_256:
11506 case Intrinsic::x86_avx_hadd_pd_256:
11507 Opcode = X86ISD::FHADD;
11509 case Intrinsic::x86_sse3_hsub_ps:
11510 case Intrinsic::x86_sse3_hsub_pd:
11511 case Intrinsic::x86_avx_hsub_ps_256:
11512 case Intrinsic::x86_avx_hsub_pd_256:
11513 Opcode = X86ISD::FHSUB;
11515 case Intrinsic::x86_ssse3_phadd_w_128:
11516 case Intrinsic::x86_ssse3_phadd_d_128:
11517 case Intrinsic::x86_avx2_phadd_w:
11518 case Intrinsic::x86_avx2_phadd_d:
11519 Opcode = X86ISD::HADD;
11521 case Intrinsic::x86_ssse3_phsub_w_128:
11522 case Intrinsic::x86_ssse3_phsub_d_128:
11523 case Intrinsic::x86_avx2_phsub_w:
11524 case Intrinsic::x86_avx2_phsub_d:
11525 Opcode = X86ISD::HSUB;
11528 return DAG.getNode(Opcode, dl, Op.getValueType(),
11529 Op.getOperand(1), Op.getOperand(2));
11532 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11533 case Intrinsic::x86_sse2_pmaxu_b:
11534 case Intrinsic::x86_sse41_pmaxuw:
11535 case Intrinsic::x86_sse41_pmaxud:
11536 case Intrinsic::x86_avx2_pmaxu_b:
11537 case Intrinsic::x86_avx2_pmaxu_w:
11538 case Intrinsic::x86_avx2_pmaxu_d:
11539 case Intrinsic::x86_sse2_pminu_b:
11540 case Intrinsic::x86_sse41_pminuw:
11541 case Intrinsic::x86_sse41_pminud:
11542 case Intrinsic::x86_avx2_pminu_b:
11543 case Intrinsic::x86_avx2_pminu_w:
11544 case Intrinsic::x86_avx2_pminu_d:
11545 case Intrinsic::x86_sse41_pmaxsb:
11546 case Intrinsic::x86_sse2_pmaxs_w:
11547 case Intrinsic::x86_sse41_pmaxsd:
11548 case Intrinsic::x86_avx2_pmaxs_b:
11549 case Intrinsic::x86_avx2_pmaxs_w:
11550 case Intrinsic::x86_avx2_pmaxs_d:
11551 case Intrinsic::x86_sse41_pminsb:
11552 case Intrinsic::x86_sse2_pmins_w:
11553 case Intrinsic::x86_sse41_pminsd:
11554 case Intrinsic::x86_avx2_pmins_b:
11555 case Intrinsic::x86_avx2_pmins_w:
11556 case Intrinsic::x86_avx2_pmins_d: {
11559 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11560 case Intrinsic::x86_sse2_pmaxu_b:
11561 case Intrinsic::x86_sse41_pmaxuw:
11562 case Intrinsic::x86_sse41_pmaxud:
11563 case Intrinsic::x86_avx2_pmaxu_b:
11564 case Intrinsic::x86_avx2_pmaxu_w:
11565 case Intrinsic::x86_avx2_pmaxu_d:
11566 Opcode = X86ISD::UMAX;
11568 case Intrinsic::x86_sse2_pminu_b:
11569 case Intrinsic::x86_sse41_pminuw:
11570 case Intrinsic::x86_sse41_pminud:
11571 case Intrinsic::x86_avx2_pminu_b:
11572 case Intrinsic::x86_avx2_pminu_w:
11573 case Intrinsic::x86_avx2_pminu_d:
11574 Opcode = X86ISD::UMIN;
11576 case Intrinsic::x86_sse41_pmaxsb:
11577 case Intrinsic::x86_sse2_pmaxs_w:
11578 case Intrinsic::x86_sse41_pmaxsd:
11579 case Intrinsic::x86_avx2_pmaxs_b:
11580 case Intrinsic::x86_avx2_pmaxs_w:
11581 case Intrinsic::x86_avx2_pmaxs_d:
11582 Opcode = X86ISD::SMAX;
11584 case Intrinsic::x86_sse41_pminsb:
11585 case Intrinsic::x86_sse2_pmins_w:
11586 case Intrinsic::x86_sse41_pminsd:
11587 case Intrinsic::x86_avx2_pmins_b:
11588 case Intrinsic::x86_avx2_pmins_w:
11589 case Intrinsic::x86_avx2_pmins_d:
11590 Opcode = X86ISD::SMIN;
11593 return DAG.getNode(Opcode, dl, Op.getValueType(),
11594 Op.getOperand(1), Op.getOperand(2));
11597 // SSE/SSE2/AVX floating point max/min intrinsics.
11598 case Intrinsic::x86_sse_max_ps:
11599 case Intrinsic::x86_sse2_max_pd:
11600 case Intrinsic::x86_avx_max_ps_256:
11601 case Intrinsic::x86_avx_max_pd_256:
11602 case Intrinsic::x86_sse_min_ps:
11603 case Intrinsic::x86_sse2_min_pd:
11604 case Intrinsic::x86_avx_min_ps_256:
11605 case Intrinsic::x86_avx_min_pd_256: {
11608 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11609 case Intrinsic::x86_sse_max_ps:
11610 case Intrinsic::x86_sse2_max_pd:
11611 case Intrinsic::x86_avx_max_ps_256:
11612 case Intrinsic::x86_avx_max_pd_256:
11613 Opcode = X86ISD::FMAX;
11615 case Intrinsic::x86_sse_min_ps:
11616 case Intrinsic::x86_sse2_min_pd:
11617 case Intrinsic::x86_avx_min_ps_256:
11618 case Intrinsic::x86_avx_min_pd_256:
11619 Opcode = X86ISD::FMIN;
11622 return DAG.getNode(Opcode, dl, Op.getValueType(),
11623 Op.getOperand(1), Op.getOperand(2));
11626 // AVX2 variable shift intrinsics
11627 case Intrinsic::x86_avx2_psllv_d:
11628 case Intrinsic::x86_avx2_psllv_q:
11629 case Intrinsic::x86_avx2_psllv_d_256:
11630 case Intrinsic::x86_avx2_psllv_q_256:
11631 case Intrinsic::x86_avx2_psrlv_d:
11632 case Intrinsic::x86_avx2_psrlv_q:
11633 case Intrinsic::x86_avx2_psrlv_d_256:
11634 case Intrinsic::x86_avx2_psrlv_q_256:
11635 case Intrinsic::x86_avx2_psrav_d:
11636 case Intrinsic::x86_avx2_psrav_d_256: {
11639 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11640 case Intrinsic::x86_avx2_psllv_d:
11641 case Intrinsic::x86_avx2_psllv_q:
11642 case Intrinsic::x86_avx2_psllv_d_256:
11643 case Intrinsic::x86_avx2_psllv_q_256:
11646 case Intrinsic::x86_avx2_psrlv_d:
11647 case Intrinsic::x86_avx2_psrlv_q:
11648 case Intrinsic::x86_avx2_psrlv_d_256:
11649 case Intrinsic::x86_avx2_psrlv_q_256:
11652 case Intrinsic::x86_avx2_psrav_d:
11653 case Intrinsic::x86_avx2_psrav_d_256:
11657 return DAG.getNode(Opcode, dl, Op.getValueType(),
11658 Op.getOperand(1), Op.getOperand(2));
11661 case Intrinsic::x86_ssse3_pshuf_b_128:
11662 case Intrinsic::x86_avx2_pshuf_b:
11663 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11664 Op.getOperand(1), Op.getOperand(2));
11666 case Intrinsic::x86_ssse3_psign_b_128:
11667 case Intrinsic::x86_ssse3_psign_w_128:
11668 case Intrinsic::x86_ssse3_psign_d_128:
11669 case Intrinsic::x86_avx2_psign_b:
11670 case Intrinsic::x86_avx2_psign_w:
11671 case Intrinsic::x86_avx2_psign_d:
11672 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11673 Op.getOperand(1), Op.getOperand(2));
11675 case Intrinsic::x86_sse41_insertps:
11676 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11677 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11679 case Intrinsic::x86_avx_vperm2f128_ps_256:
11680 case Intrinsic::x86_avx_vperm2f128_pd_256:
11681 case Intrinsic::x86_avx_vperm2f128_si_256:
11682 case Intrinsic::x86_avx2_vperm2i128:
11683 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11684 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11686 case Intrinsic::x86_avx2_permd:
11687 case Intrinsic::x86_avx2_permps:
11688 // Operands intentionally swapped. Mask is last operand to intrinsic,
11689 // but second operand for node/instruction.
11690 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11691 Op.getOperand(2), Op.getOperand(1));
11693 case Intrinsic::x86_sse_sqrt_ps:
11694 case Intrinsic::x86_sse2_sqrt_pd:
11695 case Intrinsic::x86_avx_sqrt_ps_256:
11696 case Intrinsic::x86_avx_sqrt_pd_256:
11697 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11699 // ptest and testp intrinsics. The intrinsic these come from are designed to
11700 // return an integer value, not just an instruction so lower it to the ptest
11701 // or testp pattern and a setcc for the result.
11702 case Intrinsic::x86_sse41_ptestz:
11703 case Intrinsic::x86_sse41_ptestc:
11704 case Intrinsic::x86_sse41_ptestnzc:
11705 case Intrinsic::x86_avx_ptestz_256:
11706 case Intrinsic::x86_avx_ptestc_256:
11707 case Intrinsic::x86_avx_ptestnzc_256:
11708 case Intrinsic::x86_avx_vtestz_ps:
11709 case Intrinsic::x86_avx_vtestc_ps:
11710 case Intrinsic::x86_avx_vtestnzc_ps:
11711 case Intrinsic::x86_avx_vtestz_pd:
11712 case Intrinsic::x86_avx_vtestc_pd:
11713 case Intrinsic::x86_avx_vtestnzc_pd:
11714 case Intrinsic::x86_avx_vtestz_ps_256:
11715 case Intrinsic::x86_avx_vtestc_ps_256:
11716 case Intrinsic::x86_avx_vtestnzc_ps_256:
11717 case Intrinsic::x86_avx_vtestz_pd_256:
11718 case Intrinsic::x86_avx_vtestc_pd_256:
11719 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11720 bool IsTestPacked = false;
11723 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11724 case Intrinsic::x86_avx_vtestz_ps:
11725 case Intrinsic::x86_avx_vtestz_pd:
11726 case Intrinsic::x86_avx_vtestz_ps_256:
11727 case Intrinsic::x86_avx_vtestz_pd_256:
11728 IsTestPacked = true; // Fallthrough
11729 case Intrinsic::x86_sse41_ptestz:
11730 case Intrinsic::x86_avx_ptestz_256:
11732 X86CC = X86::COND_E;
11734 case Intrinsic::x86_avx_vtestc_ps:
11735 case Intrinsic::x86_avx_vtestc_pd:
11736 case Intrinsic::x86_avx_vtestc_ps_256:
11737 case Intrinsic::x86_avx_vtestc_pd_256:
11738 IsTestPacked = true; // Fallthrough
11739 case Intrinsic::x86_sse41_ptestc:
11740 case Intrinsic::x86_avx_ptestc_256:
11742 X86CC = X86::COND_B;
11744 case Intrinsic::x86_avx_vtestnzc_ps:
11745 case Intrinsic::x86_avx_vtestnzc_pd:
11746 case Intrinsic::x86_avx_vtestnzc_ps_256:
11747 case Intrinsic::x86_avx_vtestnzc_pd_256:
11748 IsTestPacked = true; // Fallthrough
11749 case Intrinsic::x86_sse41_ptestnzc:
11750 case Intrinsic::x86_avx_ptestnzc_256:
11752 X86CC = X86::COND_A;
11756 SDValue LHS = Op.getOperand(1);
11757 SDValue RHS = Op.getOperand(2);
11758 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11759 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11760 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11761 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11762 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11764 case Intrinsic::x86_avx512_kortestz_w:
11765 case Intrinsic::x86_avx512_kortestc_w: {
11766 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11767 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11768 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11769 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11770 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11771 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11772 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11775 // SSE/AVX shift intrinsics
11776 case Intrinsic::x86_sse2_psll_w:
11777 case Intrinsic::x86_sse2_psll_d:
11778 case Intrinsic::x86_sse2_psll_q:
11779 case Intrinsic::x86_avx2_psll_w:
11780 case Intrinsic::x86_avx2_psll_d:
11781 case Intrinsic::x86_avx2_psll_q:
11782 case Intrinsic::x86_sse2_psrl_w:
11783 case Intrinsic::x86_sse2_psrl_d:
11784 case Intrinsic::x86_sse2_psrl_q:
11785 case Intrinsic::x86_avx2_psrl_w:
11786 case Intrinsic::x86_avx2_psrl_d:
11787 case Intrinsic::x86_avx2_psrl_q:
11788 case Intrinsic::x86_sse2_psra_w:
11789 case Intrinsic::x86_sse2_psra_d:
11790 case Intrinsic::x86_avx2_psra_w:
11791 case Intrinsic::x86_avx2_psra_d: {
11794 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11795 case Intrinsic::x86_sse2_psll_w:
11796 case Intrinsic::x86_sse2_psll_d:
11797 case Intrinsic::x86_sse2_psll_q:
11798 case Intrinsic::x86_avx2_psll_w:
11799 case Intrinsic::x86_avx2_psll_d:
11800 case Intrinsic::x86_avx2_psll_q:
11801 Opcode = X86ISD::VSHL;
11803 case Intrinsic::x86_sse2_psrl_w:
11804 case Intrinsic::x86_sse2_psrl_d:
11805 case Intrinsic::x86_sse2_psrl_q:
11806 case Intrinsic::x86_avx2_psrl_w:
11807 case Intrinsic::x86_avx2_psrl_d:
11808 case Intrinsic::x86_avx2_psrl_q:
11809 Opcode = X86ISD::VSRL;
11811 case Intrinsic::x86_sse2_psra_w:
11812 case Intrinsic::x86_sse2_psra_d:
11813 case Intrinsic::x86_avx2_psra_w:
11814 case Intrinsic::x86_avx2_psra_d:
11815 Opcode = X86ISD::VSRA;
11818 return DAG.getNode(Opcode, dl, Op.getValueType(),
11819 Op.getOperand(1), Op.getOperand(2));
11822 // SSE/AVX immediate shift intrinsics
11823 case Intrinsic::x86_sse2_pslli_w:
11824 case Intrinsic::x86_sse2_pslli_d:
11825 case Intrinsic::x86_sse2_pslli_q:
11826 case Intrinsic::x86_avx2_pslli_w:
11827 case Intrinsic::x86_avx2_pslli_d:
11828 case Intrinsic::x86_avx2_pslli_q:
11829 case Intrinsic::x86_sse2_psrli_w:
11830 case Intrinsic::x86_sse2_psrli_d:
11831 case Intrinsic::x86_sse2_psrli_q:
11832 case Intrinsic::x86_avx2_psrli_w:
11833 case Intrinsic::x86_avx2_psrli_d:
11834 case Intrinsic::x86_avx2_psrli_q:
11835 case Intrinsic::x86_sse2_psrai_w:
11836 case Intrinsic::x86_sse2_psrai_d:
11837 case Intrinsic::x86_avx2_psrai_w:
11838 case Intrinsic::x86_avx2_psrai_d: {
11841 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11842 case Intrinsic::x86_sse2_pslli_w:
11843 case Intrinsic::x86_sse2_pslli_d:
11844 case Intrinsic::x86_sse2_pslli_q:
11845 case Intrinsic::x86_avx2_pslli_w:
11846 case Intrinsic::x86_avx2_pslli_d:
11847 case Intrinsic::x86_avx2_pslli_q:
11848 Opcode = X86ISD::VSHLI;
11850 case Intrinsic::x86_sse2_psrli_w:
11851 case Intrinsic::x86_sse2_psrli_d:
11852 case Intrinsic::x86_sse2_psrli_q:
11853 case Intrinsic::x86_avx2_psrli_w:
11854 case Intrinsic::x86_avx2_psrli_d:
11855 case Intrinsic::x86_avx2_psrli_q:
11856 Opcode = X86ISD::VSRLI;
11858 case Intrinsic::x86_sse2_psrai_w:
11859 case Intrinsic::x86_sse2_psrai_d:
11860 case Intrinsic::x86_avx2_psrai_w:
11861 case Intrinsic::x86_avx2_psrai_d:
11862 Opcode = X86ISD::VSRAI;
11865 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11866 Op.getOperand(1), Op.getOperand(2), DAG);
11869 case Intrinsic::x86_sse42_pcmpistria128:
11870 case Intrinsic::x86_sse42_pcmpestria128:
11871 case Intrinsic::x86_sse42_pcmpistric128:
11872 case Intrinsic::x86_sse42_pcmpestric128:
11873 case Intrinsic::x86_sse42_pcmpistrio128:
11874 case Intrinsic::x86_sse42_pcmpestrio128:
11875 case Intrinsic::x86_sse42_pcmpistris128:
11876 case Intrinsic::x86_sse42_pcmpestris128:
11877 case Intrinsic::x86_sse42_pcmpistriz128:
11878 case Intrinsic::x86_sse42_pcmpestriz128: {
11882 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11883 case Intrinsic::x86_sse42_pcmpistria128:
11884 Opcode = X86ISD::PCMPISTRI;
11885 X86CC = X86::COND_A;
11887 case Intrinsic::x86_sse42_pcmpestria128:
11888 Opcode = X86ISD::PCMPESTRI;
11889 X86CC = X86::COND_A;
11891 case Intrinsic::x86_sse42_pcmpistric128:
11892 Opcode = X86ISD::PCMPISTRI;
11893 X86CC = X86::COND_B;
11895 case Intrinsic::x86_sse42_pcmpestric128:
11896 Opcode = X86ISD::PCMPESTRI;
11897 X86CC = X86::COND_B;
11899 case Intrinsic::x86_sse42_pcmpistrio128:
11900 Opcode = X86ISD::PCMPISTRI;
11901 X86CC = X86::COND_O;
11903 case Intrinsic::x86_sse42_pcmpestrio128:
11904 Opcode = X86ISD::PCMPESTRI;
11905 X86CC = X86::COND_O;
11907 case Intrinsic::x86_sse42_pcmpistris128:
11908 Opcode = X86ISD::PCMPISTRI;
11909 X86CC = X86::COND_S;
11911 case Intrinsic::x86_sse42_pcmpestris128:
11912 Opcode = X86ISD::PCMPESTRI;
11913 X86CC = X86::COND_S;
11915 case Intrinsic::x86_sse42_pcmpistriz128:
11916 Opcode = X86ISD::PCMPISTRI;
11917 X86CC = X86::COND_E;
11919 case Intrinsic::x86_sse42_pcmpestriz128:
11920 Opcode = X86ISD::PCMPESTRI;
11921 X86CC = X86::COND_E;
11924 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11925 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11926 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11927 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11928 DAG.getConstant(X86CC, MVT::i8),
11929 SDValue(PCMP.getNode(), 1));
11930 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11933 case Intrinsic::x86_sse42_pcmpistri128:
11934 case Intrinsic::x86_sse42_pcmpestri128: {
11936 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11937 Opcode = X86ISD::PCMPISTRI;
11939 Opcode = X86ISD::PCMPESTRI;
11941 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11942 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11943 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11945 case Intrinsic::x86_fma_vfmadd_ps:
11946 case Intrinsic::x86_fma_vfmadd_pd:
11947 case Intrinsic::x86_fma_vfmsub_ps:
11948 case Intrinsic::x86_fma_vfmsub_pd:
11949 case Intrinsic::x86_fma_vfnmadd_ps:
11950 case Intrinsic::x86_fma_vfnmadd_pd:
11951 case Intrinsic::x86_fma_vfnmsub_ps:
11952 case Intrinsic::x86_fma_vfnmsub_pd:
11953 case Intrinsic::x86_fma_vfmaddsub_ps:
11954 case Intrinsic::x86_fma_vfmaddsub_pd:
11955 case Intrinsic::x86_fma_vfmsubadd_ps:
11956 case Intrinsic::x86_fma_vfmsubadd_pd:
11957 case Intrinsic::x86_fma_vfmadd_ps_256:
11958 case Intrinsic::x86_fma_vfmadd_pd_256:
11959 case Intrinsic::x86_fma_vfmsub_ps_256:
11960 case Intrinsic::x86_fma_vfmsub_pd_256:
11961 case Intrinsic::x86_fma_vfnmadd_ps_256:
11962 case Intrinsic::x86_fma_vfnmadd_pd_256:
11963 case Intrinsic::x86_fma_vfnmsub_ps_256:
11964 case Intrinsic::x86_fma_vfnmsub_pd_256:
11965 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11966 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11967 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11968 case Intrinsic::x86_fma_vfmsubadd_pd_256:
11969 case Intrinsic::x86_fma_vfmadd_ps_512:
11970 case Intrinsic::x86_fma_vfmadd_pd_512:
11971 case Intrinsic::x86_fma_vfmsub_ps_512:
11972 case Intrinsic::x86_fma_vfmsub_pd_512:
11973 case Intrinsic::x86_fma_vfnmadd_ps_512:
11974 case Intrinsic::x86_fma_vfnmadd_pd_512:
11975 case Intrinsic::x86_fma_vfnmsub_ps_512:
11976 case Intrinsic::x86_fma_vfnmsub_pd_512:
11977 case Intrinsic::x86_fma_vfmaddsub_ps_512:
11978 case Intrinsic::x86_fma_vfmaddsub_pd_512:
11979 case Intrinsic::x86_fma_vfmsubadd_ps_512:
11980 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11983 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11984 case Intrinsic::x86_fma_vfmadd_ps:
11985 case Intrinsic::x86_fma_vfmadd_pd:
11986 case Intrinsic::x86_fma_vfmadd_ps_256:
11987 case Intrinsic::x86_fma_vfmadd_pd_256:
11988 case Intrinsic::x86_fma_vfmadd_ps_512:
11989 case Intrinsic::x86_fma_vfmadd_pd_512:
11990 Opc = X86ISD::FMADD;
11992 case Intrinsic::x86_fma_vfmsub_ps:
11993 case Intrinsic::x86_fma_vfmsub_pd:
11994 case Intrinsic::x86_fma_vfmsub_ps_256:
11995 case Intrinsic::x86_fma_vfmsub_pd_256:
11996 case Intrinsic::x86_fma_vfmsub_ps_512:
11997 case Intrinsic::x86_fma_vfmsub_pd_512:
11998 Opc = X86ISD::FMSUB;
12000 case Intrinsic::x86_fma_vfnmadd_ps:
12001 case Intrinsic::x86_fma_vfnmadd_pd:
12002 case Intrinsic::x86_fma_vfnmadd_ps_256:
12003 case Intrinsic::x86_fma_vfnmadd_pd_256:
12004 case Intrinsic::x86_fma_vfnmadd_ps_512:
12005 case Intrinsic::x86_fma_vfnmadd_pd_512:
12006 Opc = X86ISD::FNMADD;
12008 case Intrinsic::x86_fma_vfnmsub_ps:
12009 case Intrinsic::x86_fma_vfnmsub_pd:
12010 case Intrinsic::x86_fma_vfnmsub_ps_256:
12011 case Intrinsic::x86_fma_vfnmsub_pd_256:
12012 case Intrinsic::x86_fma_vfnmsub_ps_512:
12013 case Intrinsic::x86_fma_vfnmsub_pd_512:
12014 Opc = X86ISD::FNMSUB;
12016 case Intrinsic::x86_fma_vfmaddsub_ps:
12017 case Intrinsic::x86_fma_vfmaddsub_pd:
12018 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12019 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12020 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12021 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12022 Opc = X86ISD::FMADDSUB;
12024 case Intrinsic::x86_fma_vfmsubadd_ps:
12025 case Intrinsic::x86_fma_vfmsubadd_pd:
12026 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12027 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12028 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12029 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12030 Opc = X86ISD::FMSUBADD;
12034 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12035 Op.getOperand(2), Op.getOperand(3));
12040 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12041 SDValue Base, SDValue Index,
12042 SDValue ScaleOp, SDValue Chain,
12043 const X86Subtarget * Subtarget) {
12045 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12046 assert(C && "Invalid scale type");
12047 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12048 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12049 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12050 Index.getSimpleValueType().getVectorNumElements());
12051 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12052 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12053 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12054 SDValue Segment = DAG.getRegister(0, MVT::i32);
12055 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12056 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12057 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12058 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12061 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12062 SDValue Src, SDValue Mask, SDValue Base,
12063 SDValue Index, SDValue ScaleOp, SDValue Chain,
12064 const X86Subtarget * Subtarget) {
12066 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12067 assert(C && "Invalid scale type");
12068 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12069 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12070 Index.getSimpleValueType().getVectorNumElements());
12071 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12072 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12073 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12074 SDValue Segment = DAG.getRegister(0, MVT::i32);
12075 if (Src.getOpcode() == ISD::UNDEF)
12076 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12077 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12078 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12079 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12080 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12083 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12084 SDValue Src, SDValue Base, SDValue Index,
12085 SDValue ScaleOp, SDValue Chain) {
12087 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12088 assert(C && "Invalid scale type");
12089 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12090 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12091 SDValue Segment = DAG.getRegister(0, MVT::i32);
12092 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12093 Index.getSimpleValueType().getVectorNumElements());
12094 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12095 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12096 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12097 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12098 return SDValue(Res, 1);
12101 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12102 SDValue Src, SDValue Mask, SDValue Base,
12103 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12105 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12106 assert(C && "Invalid scale type");
12107 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12108 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12109 SDValue Segment = DAG.getRegister(0, MVT::i32);
12110 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12111 Index.getSimpleValueType().getVectorNumElements());
12112 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12113 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12114 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12115 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12116 return SDValue(Res, 1);
12119 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12120 SelectionDAG &DAG) {
12122 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12124 default: return SDValue(); // Don't custom lower most intrinsics.
12126 // RDRAND/RDSEED intrinsics.
12127 case Intrinsic::x86_rdrand_16:
12128 case Intrinsic::x86_rdrand_32:
12129 case Intrinsic::x86_rdrand_64:
12130 case Intrinsic::x86_rdseed_16:
12131 case Intrinsic::x86_rdseed_32:
12132 case Intrinsic::x86_rdseed_64: {
12133 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12134 IntNo == Intrinsic::x86_rdseed_32 ||
12135 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12137 // Emit the node with the right value type.
12138 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12139 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12141 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12142 // Otherwise return the value from Rand, which is always 0, casted to i32.
12143 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12144 DAG.getConstant(1, Op->getValueType(1)),
12145 DAG.getConstant(X86::COND_B, MVT::i32),
12146 SDValue(Result.getNode(), 1) };
12147 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12148 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12149 Ops, array_lengthof(Ops));
12151 // Return { result, isValid, chain }.
12152 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12153 SDValue(Result.getNode(), 2));
12155 //int_gather(index, base, scale);
12156 case Intrinsic::x86_avx512_gather_qpd_512:
12157 case Intrinsic::x86_avx512_gather_qps_512:
12158 case Intrinsic::x86_avx512_gather_dpd_512:
12159 case Intrinsic::x86_avx512_gather_qpi_512:
12160 case Intrinsic::x86_avx512_gather_qpq_512:
12161 case Intrinsic::x86_avx512_gather_dpq_512:
12162 case Intrinsic::x86_avx512_gather_dps_512:
12163 case Intrinsic::x86_avx512_gather_dpi_512: {
12166 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12167 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12168 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12169 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12170 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12171 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12172 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12173 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12174 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12176 SDValue Chain = Op.getOperand(0);
12177 SDValue Index = Op.getOperand(2);
12178 SDValue Base = Op.getOperand(3);
12179 SDValue Scale = Op.getOperand(4);
12180 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12182 //int_gather_mask(v1, mask, index, base, scale);
12183 case Intrinsic::x86_avx512_gather_qps_mask_512:
12184 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12185 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12186 case Intrinsic::x86_avx512_gather_dps_mask_512:
12187 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12188 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12189 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12190 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12193 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12194 case Intrinsic::x86_avx512_gather_qps_mask_512:
12195 Opc = X86::VGATHERQPSZrm; break;
12196 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12197 Opc = X86::VGATHERQPDZrm; break;
12198 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12199 Opc = X86::VGATHERDPDZrm; break;
12200 case Intrinsic::x86_avx512_gather_dps_mask_512:
12201 Opc = X86::VGATHERDPSZrm; break;
12202 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12203 Opc = X86::VPGATHERQDZrm; break;
12204 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12205 Opc = X86::VPGATHERQQZrm; break;
12206 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12207 Opc = X86::VPGATHERDDZrm; break;
12208 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12209 Opc = X86::VPGATHERDQZrm; break;
12211 SDValue Chain = Op.getOperand(0);
12212 SDValue Src = Op.getOperand(2);
12213 SDValue Mask = Op.getOperand(3);
12214 SDValue Index = Op.getOperand(4);
12215 SDValue Base = Op.getOperand(5);
12216 SDValue Scale = Op.getOperand(6);
12217 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12220 //int_scatter(base, index, v1, scale);
12221 case Intrinsic::x86_avx512_scatter_qpd_512:
12222 case Intrinsic::x86_avx512_scatter_qps_512:
12223 case Intrinsic::x86_avx512_scatter_dpd_512:
12224 case Intrinsic::x86_avx512_scatter_qpi_512:
12225 case Intrinsic::x86_avx512_scatter_qpq_512:
12226 case Intrinsic::x86_avx512_scatter_dpq_512:
12227 case Intrinsic::x86_avx512_scatter_dps_512:
12228 case Intrinsic::x86_avx512_scatter_dpi_512: {
12231 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12232 case Intrinsic::x86_avx512_scatter_qpd_512:
12233 Opc = X86::VSCATTERQPDZmr; break;
12234 case Intrinsic::x86_avx512_scatter_qps_512:
12235 Opc = X86::VSCATTERQPSZmr; break;
12236 case Intrinsic::x86_avx512_scatter_dpd_512:
12237 Opc = X86::VSCATTERDPDZmr; break;
12238 case Intrinsic::x86_avx512_scatter_dps_512:
12239 Opc = X86::VSCATTERDPSZmr; break;
12240 case Intrinsic::x86_avx512_scatter_qpi_512:
12241 Opc = X86::VPSCATTERQDZmr; break;
12242 case Intrinsic::x86_avx512_scatter_qpq_512:
12243 Opc = X86::VPSCATTERQQZmr; break;
12244 case Intrinsic::x86_avx512_scatter_dpq_512:
12245 Opc = X86::VPSCATTERDQZmr; break;
12246 case Intrinsic::x86_avx512_scatter_dpi_512:
12247 Opc = X86::VPSCATTERDDZmr; break;
12249 SDValue Chain = Op.getOperand(0);
12250 SDValue Base = Op.getOperand(2);
12251 SDValue Index = Op.getOperand(3);
12252 SDValue Src = Op.getOperand(4);
12253 SDValue Scale = Op.getOperand(5);
12254 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12256 //int_scatter_mask(base, mask, index, v1, scale);
12257 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12258 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12259 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12260 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12261 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12262 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12263 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12264 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12267 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12268 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12269 Opc = X86::VSCATTERQPDZmr; break;
12270 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12271 Opc = X86::VSCATTERQPSZmr; break;
12272 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12273 Opc = X86::VSCATTERDPDZmr; break;
12274 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12275 Opc = X86::VSCATTERDPSZmr; break;
12276 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12277 Opc = X86::VPSCATTERQDZmr; break;
12278 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12279 Opc = X86::VPSCATTERQQZmr; break;
12280 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12281 Opc = X86::VPSCATTERDQZmr; break;
12282 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12283 Opc = X86::VPSCATTERDDZmr; break;
12285 SDValue Chain = Op.getOperand(0);
12286 SDValue Base = Op.getOperand(2);
12287 SDValue Mask = Op.getOperand(3);
12288 SDValue Index = Op.getOperand(4);
12289 SDValue Src = Op.getOperand(5);
12290 SDValue Scale = Op.getOperand(6);
12291 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12293 // XTEST intrinsics.
12294 case Intrinsic::x86_xtest: {
12295 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12296 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12297 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12298 DAG.getConstant(X86::COND_NE, MVT::i8),
12300 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12301 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12302 Ret, SDValue(InTrans.getNode(), 1));
12307 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12308 SelectionDAG &DAG) const {
12309 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12310 MFI->setReturnAddressIsTaken(true);
12312 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12315 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12317 EVT PtrVT = getPointerTy();
12320 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12321 const X86RegisterInfo *RegInfo =
12322 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12323 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12324 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12325 DAG.getNode(ISD::ADD, dl, PtrVT,
12326 FrameAddr, Offset),
12327 MachinePointerInfo(), false, false, false, 0);
12330 // Just load the return address.
12331 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12332 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12333 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12336 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12337 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12338 MFI->setFrameAddressIsTaken(true);
12340 EVT VT = Op.getValueType();
12341 SDLoc dl(Op); // FIXME probably not meaningful
12342 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12343 const X86RegisterInfo *RegInfo =
12344 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12345 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12346 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12347 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12348 "Invalid Frame Register!");
12349 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12351 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12352 MachinePointerInfo(),
12353 false, false, false, 0);
12357 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12358 SelectionDAG &DAG) const {
12359 const X86RegisterInfo *RegInfo =
12360 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12361 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12364 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12365 SDValue Chain = Op.getOperand(0);
12366 SDValue Offset = Op.getOperand(1);
12367 SDValue Handler = Op.getOperand(2);
12370 EVT PtrVT = getPointerTy();
12371 const X86RegisterInfo *RegInfo =
12372 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12373 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12374 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12375 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12376 "Invalid Frame Register!");
12377 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12378 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12380 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12381 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12382 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12383 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12385 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12387 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12388 DAG.getRegister(StoreAddrReg, PtrVT));
12391 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12392 SelectionDAG &DAG) const {
12394 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12395 DAG.getVTList(MVT::i32, MVT::Other),
12396 Op.getOperand(0), Op.getOperand(1));
12399 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12400 SelectionDAG &DAG) const {
12402 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12403 Op.getOperand(0), Op.getOperand(1));
12406 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12407 return Op.getOperand(0);
12410 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12411 SelectionDAG &DAG) const {
12412 SDValue Root = Op.getOperand(0);
12413 SDValue Trmp = Op.getOperand(1); // trampoline
12414 SDValue FPtr = Op.getOperand(2); // nested function
12415 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12418 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12419 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12421 if (Subtarget->is64Bit()) {
12422 SDValue OutChains[6];
12424 // Large code-model.
12425 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12426 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12428 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12429 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12431 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12433 // Load the pointer to the nested function into R11.
12434 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12435 SDValue Addr = Trmp;
12436 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12437 Addr, MachinePointerInfo(TrmpAddr),
12440 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12441 DAG.getConstant(2, MVT::i64));
12442 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12443 MachinePointerInfo(TrmpAddr, 2),
12446 // Load the 'nest' parameter value into R10.
12447 // R10 is specified in X86CallingConv.td
12448 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12449 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12450 DAG.getConstant(10, MVT::i64));
12451 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12452 Addr, MachinePointerInfo(TrmpAddr, 10),
12455 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12456 DAG.getConstant(12, MVT::i64));
12457 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12458 MachinePointerInfo(TrmpAddr, 12),
12461 // Jump to the nested function.
12462 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12463 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12464 DAG.getConstant(20, MVT::i64));
12465 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12466 Addr, MachinePointerInfo(TrmpAddr, 20),
12469 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12470 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12471 DAG.getConstant(22, MVT::i64));
12472 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12473 MachinePointerInfo(TrmpAddr, 22),
12476 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12478 const Function *Func =
12479 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12480 CallingConv::ID CC = Func->getCallingConv();
12485 llvm_unreachable("Unsupported calling convention");
12486 case CallingConv::C:
12487 case CallingConv::X86_StdCall: {
12488 // Pass 'nest' parameter in ECX.
12489 // Must be kept in sync with X86CallingConv.td
12490 NestReg = X86::ECX;
12492 // Check that ECX wasn't needed by an 'inreg' parameter.
12493 FunctionType *FTy = Func->getFunctionType();
12494 const AttributeSet &Attrs = Func->getAttributes();
12496 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12497 unsigned InRegCount = 0;
12500 for (FunctionType::param_iterator I = FTy->param_begin(),
12501 E = FTy->param_end(); I != E; ++I, ++Idx)
12502 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12503 // FIXME: should only count parameters that are lowered to integers.
12504 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12506 if (InRegCount > 2) {
12507 report_fatal_error("Nest register in use - reduce number of inreg"
12513 case CallingConv::X86_FastCall:
12514 case CallingConv::X86_ThisCall:
12515 case CallingConv::Fast:
12516 // Pass 'nest' parameter in EAX.
12517 // Must be kept in sync with X86CallingConv.td
12518 NestReg = X86::EAX;
12522 SDValue OutChains[4];
12523 SDValue Addr, Disp;
12525 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12526 DAG.getConstant(10, MVT::i32));
12527 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12529 // This is storing the opcode for MOV32ri.
12530 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12531 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12532 OutChains[0] = DAG.getStore(Root, dl,
12533 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12534 Trmp, MachinePointerInfo(TrmpAddr),
12537 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12538 DAG.getConstant(1, MVT::i32));
12539 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12540 MachinePointerInfo(TrmpAddr, 1),
12543 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12544 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12545 DAG.getConstant(5, MVT::i32));
12546 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12547 MachinePointerInfo(TrmpAddr, 5),
12550 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12551 DAG.getConstant(6, MVT::i32));
12552 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12553 MachinePointerInfo(TrmpAddr, 6),
12556 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12560 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12561 SelectionDAG &DAG) const {
12563 The rounding mode is in bits 11:10 of FPSR, and has the following
12565 00 Round to nearest
12570 FLT_ROUNDS, on the other hand, expects the following:
12577 To perform the conversion, we do:
12578 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12581 MachineFunction &MF = DAG.getMachineFunction();
12582 const TargetMachine &TM = MF.getTarget();
12583 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12584 unsigned StackAlignment = TFI.getStackAlignment();
12585 MVT VT = Op.getSimpleValueType();
12588 // Save FP Control Word to stack slot
12589 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12590 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12592 MachineMemOperand *MMO =
12593 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12594 MachineMemOperand::MOStore, 2, 2);
12596 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12597 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12598 DAG.getVTList(MVT::Other),
12599 Ops, array_lengthof(Ops), MVT::i16,
12602 // Load FP Control Word from stack slot
12603 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12604 MachinePointerInfo(), false, false, false, 0);
12606 // Transform as necessary
12608 DAG.getNode(ISD::SRL, DL, MVT::i16,
12609 DAG.getNode(ISD::AND, DL, MVT::i16,
12610 CWD, DAG.getConstant(0x800, MVT::i16)),
12611 DAG.getConstant(11, MVT::i8));
12613 DAG.getNode(ISD::SRL, DL, MVT::i16,
12614 DAG.getNode(ISD::AND, DL, MVT::i16,
12615 CWD, DAG.getConstant(0x400, MVT::i16)),
12616 DAG.getConstant(9, MVT::i8));
12619 DAG.getNode(ISD::AND, DL, MVT::i16,
12620 DAG.getNode(ISD::ADD, DL, MVT::i16,
12621 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12622 DAG.getConstant(1, MVT::i16)),
12623 DAG.getConstant(3, MVT::i16));
12625 return DAG.getNode((VT.getSizeInBits() < 16 ?
12626 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12629 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12630 MVT VT = Op.getSimpleValueType();
12632 unsigned NumBits = VT.getSizeInBits();
12635 Op = Op.getOperand(0);
12636 if (VT == MVT::i8) {
12637 // Zero extend to i32 since there is not an i8 bsr.
12639 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12642 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12643 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12644 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12646 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12649 DAG.getConstant(NumBits+NumBits-1, OpVT),
12650 DAG.getConstant(X86::COND_E, MVT::i8),
12653 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12655 // Finally xor with NumBits-1.
12656 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12659 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12663 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12664 MVT VT = Op.getSimpleValueType();
12666 unsigned NumBits = VT.getSizeInBits();
12669 Op = Op.getOperand(0);
12670 if (VT == MVT::i8) {
12671 // Zero extend to i32 since there is not an i8 bsr.
12673 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12676 // Issue a bsr (scan bits in reverse).
12677 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12678 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12680 // And xor with NumBits-1.
12681 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12684 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12688 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12689 MVT VT = Op.getSimpleValueType();
12690 unsigned NumBits = VT.getSizeInBits();
12692 Op = Op.getOperand(0);
12694 // Issue a bsf (scan bits forward) which also sets EFLAGS.
12695 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12696 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12698 // If src is zero (i.e. bsf sets ZF), returns NumBits.
12701 DAG.getConstant(NumBits, VT),
12702 DAG.getConstant(X86::COND_E, MVT::i8),
12705 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12708 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12709 // ones, and then concatenate the result back.
12710 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12711 MVT VT = Op.getSimpleValueType();
12713 assert(VT.is256BitVector() && VT.isInteger() &&
12714 "Unsupported value type for operation");
12716 unsigned NumElems = VT.getVectorNumElements();
12719 // Extract the LHS vectors
12720 SDValue LHS = Op.getOperand(0);
12721 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12722 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12724 // Extract the RHS vectors
12725 SDValue RHS = Op.getOperand(1);
12726 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12727 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12729 MVT EltVT = VT.getVectorElementType();
12730 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12732 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12733 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12734 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12737 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12738 assert(Op.getSimpleValueType().is256BitVector() &&
12739 Op.getSimpleValueType().isInteger() &&
12740 "Only handle AVX 256-bit vector integer operation");
12741 return Lower256IntArith(Op, DAG);
12744 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12745 assert(Op.getSimpleValueType().is256BitVector() &&
12746 Op.getSimpleValueType().isInteger() &&
12747 "Only handle AVX 256-bit vector integer operation");
12748 return Lower256IntArith(Op, DAG);
12751 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12752 SelectionDAG &DAG) {
12754 MVT VT = Op.getSimpleValueType();
12756 // Decompose 256-bit ops into smaller 128-bit ops.
12757 if (VT.is256BitVector() && !Subtarget->hasInt256())
12758 return Lower256IntArith(Op, DAG);
12760 SDValue A = Op.getOperand(0);
12761 SDValue B = Op.getOperand(1);
12763 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12764 if (VT == MVT::v4i32) {
12765 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12766 "Should not custom lower when pmuldq is available!");
12768 // Extract the odd parts.
12769 static const int UnpackMask[] = { 1, -1, 3, -1 };
12770 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12771 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12773 // Multiply the even parts.
12774 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12775 // Now multiply odd parts.
12776 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12778 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12779 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12781 // Merge the two vectors back together with a shuffle. This expands into 2
12783 static const int ShufMask[] = { 0, 4, 2, 6 };
12784 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12787 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12788 "Only know how to lower V2I64/V4I64/V8I64 multiply");
12790 // Ahi = psrlqi(a, 32);
12791 // Bhi = psrlqi(b, 32);
12793 // AloBlo = pmuludq(a, b);
12794 // AloBhi = pmuludq(a, Bhi);
12795 // AhiBlo = pmuludq(Ahi, b);
12797 // AloBhi = psllqi(AloBhi, 32);
12798 // AhiBlo = psllqi(AhiBlo, 32);
12799 // return AloBlo + AloBhi + AhiBlo;
12801 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12802 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12804 // Bit cast to 32-bit vectors for MULUDQ
12805 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12806 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12807 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12808 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12809 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12810 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12812 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12813 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12814 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12816 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12817 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12819 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12820 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12823 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12824 MVT VT = Op.getSimpleValueType();
12825 MVT EltTy = VT.getVectorElementType();
12826 unsigned NumElts = VT.getVectorNumElements();
12827 SDValue N0 = Op.getOperand(0);
12830 // Lower sdiv X, pow2-const.
12831 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12835 APInt SplatValue, SplatUndef;
12836 unsigned SplatBitSize;
12838 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12840 EltTy.getSizeInBits() < SplatBitSize)
12843 if ((SplatValue != 0) &&
12844 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12845 unsigned Lg2 = SplatValue.countTrailingZeros();
12846 // Splat the sign bit.
12847 SmallVector<SDValue, 16> Sz(NumElts,
12848 DAG.getConstant(EltTy.getSizeInBits() - 1,
12850 SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12851 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12853 // Add (N0 < 0) ? abs2 - 1 : 0;
12854 SmallVector<SDValue, 16> Amt(NumElts,
12855 DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12857 SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12858 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12860 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12861 SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12862 SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12863 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12866 // If we're dividing by a positive value, we're done. Otherwise, we must
12867 // negate the result.
12868 if (SplatValue.isNonNegative())
12871 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12872 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12873 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12878 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12879 const X86Subtarget *Subtarget) {
12880 MVT VT = Op.getSimpleValueType();
12882 SDValue R = Op.getOperand(0);
12883 SDValue Amt = Op.getOperand(1);
12885 // Optimize shl/srl/sra with constant shift amount.
12886 if (isSplatVector(Amt.getNode())) {
12887 SDValue SclrAmt = Amt->getOperand(0);
12888 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12889 uint64_t ShiftAmt = C->getZExtValue();
12891 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12892 (Subtarget->hasInt256() &&
12893 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12894 (Subtarget->hasAVX512() &&
12895 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12896 if (Op.getOpcode() == ISD::SHL)
12897 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12899 if (Op.getOpcode() == ISD::SRL)
12900 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12902 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12903 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12907 if (VT == MVT::v16i8) {
12908 if (Op.getOpcode() == ISD::SHL) {
12909 // Make a large shift.
12910 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12911 MVT::v8i16, R, ShiftAmt,
12913 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12914 // Zero out the rightmost bits.
12915 SmallVector<SDValue, 16> V(16,
12916 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12918 return DAG.getNode(ISD::AND, dl, VT, SHL,
12919 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12921 if (Op.getOpcode() == ISD::SRL) {
12922 // Make a large shift.
12923 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12924 MVT::v8i16, R, ShiftAmt,
12926 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12927 // Zero out the leftmost bits.
12928 SmallVector<SDValue, 16> V(16,
12929 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12931 return DAG.getNode(ISD::AND, dl, VT, SRL,
12932 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12934 if (Op.getOpcode() == ISD::SRA) {
12935 if (ShiftAmt == 7) {
12936 // R s>> 7 === R s< 0
12937 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12938 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12941 // R s>> a === ((R u>> a) ^ m) - m
12942 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12943 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12945 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12946 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12947 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12950 llvm_unreachable("Unknown shift opcode.");
12953 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12954 if (Op.getOpcode() == ISD::SHL) {
12955 // Make a large shift.
12956 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12957 MVT::v16i16, R, ShiftAmt,
12959 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12960 // Zero out the rightmost bits.
12961 SmallVector<SDValue, 32> V(32,
12962 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12964 return DAG.getNode(ISD::AND, dl, VT, SHL,
12965 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12967 if (Op.getOpcode() == ISD::SRL) {
12968 // Make a large shift.
12969 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12970 MVT::v16i16, R, ShiftAmt,
12972 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12973 // Zero out the leftmost bits.
12974 SmallVector<SDValue, 32> V(32,
12975 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12977 return DAG.getNode(ISD::AND, dl, VT, SRL,
12978 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12980 if (Op.getOpcode() == ISD::SRA) {
12981 if (ShiftAmt == 7) {
12982 // R s>> 7 === R s< 0
12983 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12984 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12987 // R s>> a === ((R u>> a) ^ m) - m
12988 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12989 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12991 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12992 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12993 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12996 llvm_unreachable("Unknown shift opcode.");
13001 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13002 if (!Subtarget->is64Bit() &&
13003 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13004 Amt.getOpcode() == ISD::BITCAST &&
13005 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13006 Amt = Amt.getOperand(0);
13007 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13008 VT.getVectorNumElements();
13009 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13010 uint64_t ShiftAmt = 0;
13011 for (unsigned i = 0; i != Ratio; ++i) {
13012 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13016 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13018 // Check remaining shift amounts.
13019 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13020 uint64_t ShAmt = 0;
13021 for (unsigned j = 0; j != Ratio; ++j) {
13022 ConstantSDNode *C =
13023 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13027 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13029 if (ShAmt != ShiftAmt)
13032 switch (Op.getOpcode()) {
13034 llvm_unreachable("Unknown shift opcode!");
13036 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13039 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13042 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13050 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13051 const X86Subtarget* Subtarget) {
13052 MVT VT = Op.getSimpleValueType();
13054 SDValue R = Op.getOperand(0);
13055 SDValue Amt = Op.getOperand(1);
13057 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13058 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13059 (Subtarget->hasInt256() &&
13060 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13061 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13062 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13064 EVT EltVT = VT.getVectorElementType();
13066 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13067 unsigned NumElts = VT.getVectorNumElements();
13069 for (i = 0; i != NumElts; ++i) {
13070 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13074 for (j = i; j != NumElts; ++j) {
13075 SDValue Arg = Amt.getOperand(j);
13076 if (Arg.getOpcode() == ISD::UNDEF) continue;
13077 if (Arg != Amt.getOperand(i))
13080 if (i != NumElts && j == NumElts)
13081 BaseShAmt = Amt.getOperand(i);
13083 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13084 Amt = Amt.getOperand(0);
13085 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13086 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13087 SDValue InVec = Amt.getOperand(0);
13088 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13089 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13091 for (; i != NumElts; ++i) {
13092 SDValue Arg = InVec.getOperand(i);
13093 if (Arg.getOpcode() == ISD::UNDEF) continue;
13097 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13098 if (ConstantSDNode *C =
13099 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13100 unsigned SplatIdx =
13101 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13102 if (C->getZExtValue() == SplatIdx)
13103 BaseShAmt = InVec.getOperand(1);
13106 if (BaseShAmt.getNode() == 0)
13107 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13108 DAG.getIntPtrConstant(0));
13112 if (BaseShAmt.getNode()) {
13113 if (EltVT.bitsGT(MVT::i32))
13114 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13115 else if (EltVT.bitsLT(MVT::i32))
13116 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13118 switch (Op.getOpcode()) {
13120 llvm_unreachable("Unknown shift opcode!");
13122 switch (VT.SimpleTy) {
13123 default: return SDValue();
13132 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13135 switch (VT.SimpleTy) {
13136 default: return SDValue();
13143 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13146 switch (VT.SimpleTy) {
13147 default: return SDValue();
13156 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13162 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13163 if (!Subtarget->is64Bit() &&
13164 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13165 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13166 Amt.getOpcode() == ISD::BITCAST &&
13167 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13168 Amt = Amt.getOperand(0);
13169 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13170 VT.getVectorNumElements();
13171 std::vector<SDValue> Vals(Ratio);
13172 for (unsigned i = 0; i != Ratio; ++i)
13173 Vals[i] = Amt.getOperand(i);
13174 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13175 for (unsigned j = 0; j != Ratio; ++j)
13176 if (Vals[j] != Amt.getOperand(i + j))
13179 switch (Op.getOpcode()) {
13181 llvm_unreachable("Unknown shift opcode!");
13183 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13185 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13187 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13194 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13195 SelectionDAG &DAG) {
13197 MVT VT = Op.getSimpleValueType();
13199 SDValue R = Op.getOperand(0);
13200 SDValue Amt = Op.getOperand(1);
13203 if (!Subtarget->hasSSE2())
13206 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13210 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13214 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13216 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13217 if (Subtarget->hasInt256()) {
13218 if (Op.getOpcode() == ISD::SRL &&
13219 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13220 VT == MVT::v4i64 || VT == MVT::v8i32))
13222 if (Op.getOpcode() == ISD::SHL &&
13223 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13224 VT == MVT::v4i64 || VT == MVT::v8i32))
13226 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13230 // If possible, lower this packed shift into a vector multiply instead of
13231 // expanding it into a sequence of scalar shifts.
13232 // Do this only if the vector shift count is a constant build_vector.
13233 if (Op.getOpcode() == ISD::SHL &&
13234 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13235 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13236 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13237 SmallVector<SDValue, 8> Elts;
13238 EVT SVT = VT.getScalarType();
13239 unsigned SVTBits = SVT.getSizeInBits();
13240 const APInt &One = APInt(SVTBits, 1);
13241 unsigned NumElems = VT.getVectorNumElements();
13243 for (unsigned i=0; i !=NumElems; ++i) {
13244 SDValue Op = Amt->getOperand(i);
13245 if (Op->getOpcode() == ISD::UNDEF) {
13246 Elts.push_back(Op);
13250 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13251 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13252 uint64_t ShAmt = C.getZExtValue();
13253 if (ShAmt >= SVTBits) {
13254 Elts.push_back(DAG.getUNDEF(SVT));
13257 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13259 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13260 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13263 // Lower SHL with variable shift amount.
13264 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13265 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13267 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13268 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13269 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13270 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13273 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13274 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13277 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13278 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13280 // Turn 'a' into a mask suitable for VSELECT
13281 SDValue VSelM = DAG.getConstant(0x80, VT);
13282 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13283 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13285 SDValue CM1 = DAG.getConstant(0x0f, VT);
13286 SDValue CM2 = DAG.getConstant(0x3f, VT);
13288 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13289 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13290 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13291 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13292 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13295 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13296 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13297 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13299 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13300 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13301 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13302 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13303 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13306 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13307 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13308 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13310 // return VSELECT(r, r+r, a);
13311 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13312 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13316 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13317 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13318 // solution better.
13319 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13320 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13322 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13323 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13324 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13325 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13326 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13329 // Decompose 256-bit shifts into smaller 128-bit shifts.
13330 if (VT.is256BitVector()) {
13331 unsigned NumElems = VT.getVectorNumElements();
13332 MVT EltVT = VT.getVectorElementType();
13333 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13335 // Extract the two vectors
13336 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13337 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13339 // Recreate the shift amount vectors
13340 SDValue Amt1, Amt2;
13341 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13342 // Constant shift amount
13343 SmallVector<SDValue, 4> Amt1Csts;
13344 SmallVector<SDValue, 4> Amt2Csts;
13345 for (unsigned i = 0; i != NumElems/2; ++i)
13346 Amt1Csts.push_back(Amt->getOperand(i));
13347 for (unsigned i = NumElems/2; i != NumElems; ++i)
13348 Amt2Csts.push_back(Amt->getOperand(i));
13350 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13351 &Amt1Csts[0], NumElems/2);
13352 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13353 &Amt2Csts[0], NumElems/2);
13355 // Variable shift amount
13356 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13357 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13360 // Issue new vector shifts for the smaller types
13361 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13362 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13364 // Concatenate the result back
13365 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13371 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13372 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13373 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13374 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13375 // has only one use.
13376 SDNode *N = Op.getNode();
13377 SDValue LHS = N->getOperand(0);
13378 SDValue RHS = N->getOperand(1);
13379 unsigned BaseOp = 0;
13382 switch (Op.getOpcode()) {
13383 default: llvm_unreachable("Unknown ovf instruction!");
13385 // A subtract of one will be selected as a INC. Note that INC doesn't
13386 // set CF, so we can't do this for UADDO.
13387 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13389 BaseOp = X86ISD::INC;
13390 Cond = X86::COND_O;
13393 BaseOp = X86ISD::ADD;
13394 Cond = X86::COND_O;
13397 BaseOp = X86ISD::ADD;
13398 Cond = X86::COND_B;
13401 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13402 // set CF, so we can't do this for USUBO.
13403 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13405 BaseOp = X86ISD::DEC;
13406 Cond = X86::COND_O;
13409 BaseOp = X86ISD::SUB;
13410 Cond = X86::COND_O;
13413 BaseOp = X86ISD::SUB;
13414 Cond = X86::COND_B;
13417 BaseOp = X86ISD::SMUL;
13418 Cond = X86::COND_O;
13420 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13421 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13423 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13426 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13427 DAG.getConstant(X86::COND_O, MVT::i32),
13428 SDValue(Sum.getNode(), 2));
13430 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13434 // Also sets EFLAGS.
13435 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13436 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13439 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13440 DAG.getConstant(Cond, MVT::i32),
13441 SDValue(Sum.getNode(), 1));
13443 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13446 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13447 SelectionDAG &DAG) const {
13449 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13450 MVT VT = Op.getSimpleValueType();
13452 if (!Subtarget->hasSSE2() || !VT.isVector())
13455 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13456 ExtraVT.getScalarType().getSizeInBits();
13458 switch (VT.SimpleTy) {
13459 default: return SDValue();
13462 if (!Subtarget->hasFp256())
13464 if (!Subtarget->hasInt256()) {
13465 // needs to be split
13466 unsigned NumElems = VT.getVectorNumElements();
13468 // Extract the LHS vectors
13469 SDValue LHS = Op.getOperand(0);
13470 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13471 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13473 MVT EltVT = VT.getVectorElementType();
13474 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13476 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13477 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13478 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13480 SDValue Extra = DAG.getValueType(ExtraVT);
13482 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13483 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13485 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13490 SDValue Op0 = Op.getOperand(0);
13491 SDValue Op00 = Op0.getOperand(0);
13493 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13494 if (Op0.getOpcode() == ISD::BITCAST &&
13495 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13496 // (sext (vzext x)) -> (vsext x)
13497 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13498 if (Tmp1.getNode()) {
13499 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13500 // This folding is only valid when the in-reg type is a vector of i8,
13502 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13503 ExtraEltVT == MVT::i32) {
13504 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13505 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13506 "This optimization is invalid without a VZEXT.");
13507 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13513 // If the above didn't work, then just use Shift-Left + Shift-Right.
13514 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13516 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13522 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13523 SelectionDAG &DAG) {
13525 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13526 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13527 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13528 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13530 // The only fence that needs an instruction is a sequentially-consistent
13531 // cross-thread fence.
13532 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13533 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13534 // no-sse2). There isn't any reason to disable it if the target processor
13536 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13537 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13539 SDValue Chain = Op.getOperand(0);
13540 SDValue Zero = DAG.getConstant(0, MVT::i32);
13542 DAG.getRegister(X86::ESP, MVT::i32), // Base
13543 DAG.getTargetConstant(1, MVT::i8), // Scale
13544 DAG.getRegister(0, MVT::i32), // Index
13545 DAG.getTargetConstant(0, MVT::i32), // Disp
13546 DAG.getRegister(0, MVT::i32), // Segment.
13550 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13551 return SDValue(Res, 0);
13554 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13555 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13558 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13559 SelectionDAG &DAG) {
13560 MVT T = Op.getSimpleValueType();
13564 switch(T.SimpleTy) {
13565 default: llvm_unreachable("Invalid value type!");
13566 case MVT::i8: Reg = X86::AL; size = 1; break;
13567 case MVT::i16: Reg = X86::AX; size = 2; break;
13568 case MVT::i32: Reg = X86::EAX; size = 4; break;
13570 assert(Subtarget->is64Bit() && "Node not type legal!");
13571 Reg = X86::RAX; size = 8;
13574 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13575 Op.getOperand(2), SDValue());
13576 SDValue Ops[] = { cpIn.getValue(0),
13579 DAG.getTargetConstant(size, MVT::i8),
13580 cpIn.getValue(1) };
13581 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13582 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13583 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13584 Ops, array_lengthof(Ops), T, MMO);
13586 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13590 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13591 SelectionDAG &DAG) {
13592 assert(Subtarget->is64Bit() && "Result not type legalized?");
13593 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13594 SDValue TheChain = Op.getOperand(0);
13596 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13597 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13598 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13600 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13601 DAG.getConstant(32, MVT::i8));
13603 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13606 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13609 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13610 SelectionDAG &DAG) {
13611 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13612 MVT DstVT = Op.getSimpleValueType();
13613 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13614 Subtarget->hasMMX() && "Unexpected custom BITCAST");
13615 assert((DstVT == MVT::i64 ||
13616 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13617 "Unexpected custom BITCAST");
13618 // i64 <=> MMX conversions are Legal.
13619 if (SrcVT==MVT::i64 && DstVT.isVector())
13621 if (DstVT==MVT::i64 && SrcVT.isVector())
13623 // MMX <=> MMX conversions are Legal.
13624 if (SrcVT.isVector() && DstVT.isVector())
13626 // All other conversions need to be expanded.
13630 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13631 SDNode *Node = Op.getNode();
13633 EVT T = Node->getValueType(0);
13634 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13635 DAG.getConstant(0, T), Node->getOperand(2));
13636 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13637 cast<AtomicSDNode>(Node)->getMemoryVT(),
13638 Node->getOperand(0),
13639 Node->getOperand(1), negOp,
13640 cast<AtomicSDNode>(Node)->getSrcValue(),
13641 cast<AtomicSDNode>(Node)->getAlignment(),
13642 cast<AtomicSDNode>(Node)->getOrdering(),
13643 cast<AtomicSDNode>(Node)->getSynchScope());
13646 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13647 SDNode *Node = Op.getNode();
13649 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13651 // Convert seq_cst store -> xchg
13652 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13653 // FIXME: On 32-bit, store -> fist or movq would be more efficient
13654 // (The only way to get a 16-byte store is cmpxchg16b)
13655 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13656 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13657 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13658 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13659 cast<AtomicSDNode>(Node)->getMemoryVT(),
13660 Node->getOperand(0),
13661 Node->getOperand(1), Node->getOperand(2),
13662 cast<AtomicSDNode>(Node)->getMemOperand(),
13663 cast<AtomicSDNode>(Node)->getOrdering(),
13664 cast<AtomicSDNode>(Node)->getSynchScope());
13665 return Swap.getValue(1);
13667 // Other atomic stores have a simple pattern.
13671 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13672 EVT VT = Op.getNode()->getSimpleValueType(0);
13674 // Let legalize expand this if it isn't a legal type yet.
13675 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13678 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13681 bool ExtraOp = false;
13682 switch (Op.getOpcode()) {
13683 default: llvm_unreachable("Invalid code");
13684 case ISD::ADDC: Opc = X86ISD::ADD; break;
13685 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13686 case ISD::SUBC: Opc = X86ISD::SUB; break;
13687 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13691 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13693 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13694 Op.getOperand(1), Op.getOperand(2));
13697 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13698 SelectionDAG &DAG) {
13699 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13701 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13702 // which returns the values as { float, float } (in XMM0) or
13703 // { double, double } (which is returned in XMM0, XMM1).
13705 SDValue Arg = Op.getOperand(0);
13706 EVT ArgVT = Arg.getValueType();
13707 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13709 TargetLowering::ArgListTy Args;
13710 TargetLowering::ArgListEntry Entry;
13714 Entry.isSExt = false;
13715 Entry.isZExt = false;
13716 Args.push_back(Entry);
13718 bool isF64 = ArgVT == MVT::f64;
13719 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13720 // the small struct {f32, f32} is returned in (eax, edx). For f64,
13721 // the results are returned via SRet in memory.
13722 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
13723 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13724 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13726 Type *RetTy = isF64
13727 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13728 : (Type*)VectorType::get(ArgTy, 4);
13730 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13731 false, false, false, false, 0,
13732 CallingConv::C, /*isTaillCall=*/false,
13733 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13734 Callee, Args, DAG, dl);
13735 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13738 // Returned in xmm0 and xmm1.
13739 return CallResult.first;
13741 // Returned in bits 0:31 and 32:64 xmm0.
13742 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13743 CallResult.first, DAG.getIntPtrConstant(0));
13744 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13745 CallResult.first, DAG.getIntPtrConstant(1));
13746 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13747 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13750 /// LowerOperation - Provide custom lowering hooks for some operations.
13752 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13753 switch (Op.getOpcode()) {
13754 default: llvm_unreachable("Should not custom lower this!");
13755 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
13756 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13757 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
13758 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
13759 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
13760 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
13761 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
13762 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
13763 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13764 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
13765 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13766 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13767 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
13768 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
13769 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
13770 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
13771 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
13772 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
13773 case ISD::SHL_PARTS:
13774 case ISD::SRA_PARTS:
13775 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
13776 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
13777 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
13778 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
13779 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
13780 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13781 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
13782 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
13783 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
13784 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
13785 case ISD::FABS: return LowerFABS(Op, DAG);
13786 case ISD::FNEG: return LowerFNEG(Op, DAG);
13787 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
13788 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
13789 case ISD::SETCC: return LowerSETCC(Op, DAG);
13790 case ISD::SELECT: return LowerSELECT(Op, DAG);
13791 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
13792 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
13793 case ISD::VASTART: return LowerVASTART(Op, DAG);
13794 case ISD::VAARG: return LowerVAARG(Op, DAG);
13795 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
13796 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13797 case ISD::INTRINSIC_VOID:
13798 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13799 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
13800 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
13801 case ISD::FRAME_TO_ARGS_OFFSET:
13802 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13803 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13804 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
13805 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
13806 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
13807 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
13808 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
13809 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
13810 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
13811 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13812 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
13813 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
13816 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
13822 case ISD::UMULO: return LowerXALUO(Op, DAG);
13823 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13824 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
13828 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13829 case ISD::ADD: return LowerADD(Op, DAG);
13830 case ISD::SUB: return LowerSUB(Op, DAG);
13831 case ISD::SDIV: return LowerSDIV(Op, DAG);
13832 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
13836 static void ReplaceATOMIC_LOAD(SDNode *Node,
13837 SmallVectorImpl<SDValue> &Results,
13838 SelectionDAG &DAG) {
13840 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13842 // Convert wide load -> cmpxchg8b/cmpxchg16b
13843 // FIXME: On 32-bit, load -> fild or movq would be more efficient
13844 // (The only way to get a 16-byte load is cmpxchg16b)
13845 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13846 SDValue Zero = DAG.getConstant(0, VT);
13847 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13848 Node->getOperand(0),
13849 Node->getOperand(1), Zero, Zero,
13850 cast<AtomicSDNode>(Node)->getMemOperand(),
13851 cast<AtomicSDNode>(Node)->getOrdering(),
13852 cast<AtomicSDNode>(Node)->getOrdering(),
13853 cast<AtomicSDNode>(Node)->getSynchScope());
13854 Results.push_back(Swap.getValue(0));
13855 Results.push_back(Swap.getValue(1));
13859 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13860 SelectionDAG &DAG, unsigned NewOp) {
13862 assert (Node->getValueType(0) == MVT::i64 &&
13863 "Only know how to expand i64 atomics");
13865 SDValue Chain = Node->getOperand(0);
13866 SDValue In1 = Node->getOperand(1);
13867 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13868 Node->getOperand(2), DAG.getIntPtrConstant(0));
13869 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13870 Node->getOperand(2), DAG.getIntPtrConstant(1));
13871 SDValue Ops[] = { Chain, In1, In2L, In2H };
13872 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13874 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13875 cast<MemSDNode>(Node)->getMemOperand());
13876 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13877 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13878 Results.push_back(Result.getValue(2));
13881 /// ReplaceNodeResults - Replace a node with an illegal result type
13882 /// with a new node built out of custom code.
13883 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13884 SmallVectorImpl<SDValue>&Results,
13885 SelectionDAG &DAG) const {
13887 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13888 switch (N->getOpcode()) {
13890 llvm_unreachable("Do not know how to custom type legalize this operation!");
13891 case ISD::SIGN_EXTEND_INREG:
13896 // We don't want to expand or promote these.
13898 case ISD::FP_TO_SINT:
13899 case ISD::FP_TO_UINT: {
13900 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13902 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13905 std::pair<SDValue,SDValue> Vals =
13906 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13907 SDValue FIST = Vals.first, StackSlot = Vals.second;
13908 if (FIST.getNode() != 0) {
13909 EVT VT = N->getValueType(0);
13910 // Return a load from the stack slot.
13911 if (StackSlot.getNode() != 0)
13912 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13913 MachinePointerInfo(),
13914 false, false, false, 0));
13916 Results.push_back(FIST);
13920 case ISD::UINT_TO_FP: {
13921 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13922 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13923 N->getValueType(0) != MVT::v2f32)
13925 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13927 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13929 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13930 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13931 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13932 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13933 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13934 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13937 case ISD::FP_ROUND: {
13938 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13940 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13941 Results.push_back(V);
13944 case ISD::READCYCLECOUNTER: {
13945 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13946 SDValue TheChain = N->getOperand(0);
13947 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13948 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13950 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13952 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13953 SDValue Ops[] = { eax, edx };
13954 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13955 array_lengthof(Ops)));
13956 Results.push_back(edx.getValue(1));
13959 case ISD::ATOMIC_CMP_SWAP: {
13960 EVT T = N->getValueType(0);
13961 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13962 bool Regs64bit = T == MVT::i128;
13963 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13964 SDValue cpInL, cpInH;
13965 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13966 DAG.getConstant(0, HalfT));
13967 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13968 DAG.getConstant(1, HalfT));
13969 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13970 Regs64bit ? X86::RAX : X86::EAX,
13972 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13973 Regs64bit ? X86::RDX : X86::EDX,
13974 cpInH, cpInL.getValue(1));
13975 SDValue swapInL, swapInH;
13976 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13977 DAG.getConstant(0, HalfT));
13978 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13979 DAG.getConstant(1, HalfT));
13980 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13981 Regs64bit ? X86::RBX : X86::EBX,
13982 swapInL, cpInH.getValue(1));
13983 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13984 Regs64bit ? X86::RCX : X86::ECX,
13985 swapInH, swapInL.getValue(1));
13986 SDValue Ops[] = { swapInH.getValue(0),
13988 swapInH.getValue(1) };
13989 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13990 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13991 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13992 X86ISD::LCMPXCHG8_DAG;
13993 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13994 Ops, array_lengthof(Ops), T, MMO);
13995 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13996 Regs64bit ? X86::RAX : X86::EAX,
13997 HalfT, Result.getValue(1));
13998 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13999 Regs64bit ? X86::RDX : X86::EDX,
14000 HalfT, cpOutL.getValue(2));
14001 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14002 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14003 Results.push_back(cpOutH.getValue(1));
14006 case ISD::ATOMIC_LOAD_ADD:
14007 case ISD::ATOMIC_LOAD_AND:
14008 case ISD::ATOMIC_LOAD_NAND:
14009 case ISD::ATOMIC_LOAD_OR:
14010 case ISD::ATOMIC_LOAD_SUB:
14011 case ISD::ATOMIC_LOAD_XOR:
14012 case ISD::ATOMIC_LOAD_MAX:
14013 case ISD::ATOMIC_LOAD_MIN:
14014 case ISD::ATOMIC_LOAD_UMAX:
14015 case ISD::ATOMIC_LOAD_UMIN:
14016 case ISD::ATOMIC_SWAP: {
14018 switch (N->getOpcode()) {
14019 default: llvm_unreachable("Unexpected opcode");
14020 case ISD::ATOMIC_LOAD_ADD:
14021 Opc = X86ISD::ATOMADD64_DAG;
14023 case ISD::ATOMIC_LOAD_AND:
14024 Opc = X86ISD::ATOMAND64_DAG;
14026 case ISD::ATOMIC_LOAD_NAND:
14027 Opc = X86ISD::ATOMNAND64_DAG;
14029 case ISD::ATOMIC_LOAD_OR:
14030 Opc = X86ISD::ATOMOR64_DAG;
14032 case ISD::ATOMIC_LOAD_SUB:
14033 Opc = X86ISD::ATOMSUB64_DAG;
14035 case ISD::ATOMIC_LOAD_XOR:
14036 Opc = X86ISD::ATOMXOR64_DAG;
14038 case ISD::ATOMIC_LOAD_MAX:
14039 Opc = X86ISD::ATOMMAX64_DAG;
14041 case ISD::ATOMIC_LOAD_MIN:
14042 Opc = X86ISD::ATOMMIN64_DAG;
14044 case ISD::ATOMIC_LOAD_UMAX:
14045 Opc = X86ISD::ATOMUMAX64_DAG;
14047 case ISD::ATOMIC_LOAD_UMIN:
14048 Opc = X86ISD::ATOMUMIN64_DAG;
14050 case ISD::ATOMIC_SWAP:
14051 Opc = X86ISD::ATOMSWAP64_DAG;
14054 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14057 case ISD::ATOMIC_LOAD:
14058 ReplaceATOMIC_LOAD(N, Results, DAG);
14062 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14064 default: return NULL;
14065 case X86ISD::BSF: return "X86ISD::BSF";
14066 case X86ISD::BSR: return "X86ISD::BSR";
14067 case X86ISD::SHLD: return "X86ISD::SHLD";
14068 case X86ISD::SHRD: return "X86ISD::SHRD";
14069 case X86ISD::FAND: return "X86ISD::FAND";
14070 case X86ISD::FANDN: return "X86ISD::FANDN";
14071 case X86ISD::FOR: return "X86ISD::FOR";
14072 case X86ISD::FXOR: return "X86ISD::FXOR";
14073 case X86ISD::FSRL: return "X86ISD::FSRL";
14074 case X86ISD::FILD: return "X86ISD::FILD";
14075 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14076 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14077 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14078 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14079 case X86ISD::FLD: return "X86ISD::FLD";
14080 case X86ISD::FST: return "X86ISD::FST";
14081 case X86ISD::CALL: return "X86ISD::CALL";
14082 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14083 case X86ISD::BT: return "X86ISD::BT";
14084 case X86ISD::CMP: return "X86ISD::CMP";
14085 case X86ISD::COMI: return "X86ISD::COMI";
14086 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14087 case X86ISD::CMPM: return "X86ISD::CMPM";
14088 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14089 case X86ISD::SETCC: return "X86ISD::SETCC";
14090 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14091 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14092 case X86ISD::CMOV: return "X86ISD::CMOV";
14093 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14094 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14095 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14096 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14097 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14098 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14099 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14100 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14101 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14102 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14103 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14104 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14105 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14106 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14107 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14108 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14109 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14110 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14111 case X86ISD::HADD: return "X86ISD::HADD";
14112 case X86ISD::HSUB: return "X86ISD::HSUB";
14113 case X86ISD::FHADD: return "X86ISD::FHADD";
14114 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14115 case X86ISD::UMAX: return "X86ISD::UMAX";
14116 case X86ISD::UMIN: return "X86ISD::UMIN";
14117 case X86ISD::SMAX: return "X86ISD::SMAX";
14118 case X86ISD::SMIN: return "X86ISD::SMIN";
14119 case X86ISD::FMAX: return "X86ISD::FMAX";
14120 case X86ISD::FMIN: return "X86ISD::FMIN";
14121 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14122 case X86ISD::FMINC: return "X86ISD::FMINC";
14123 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14124 case X86ISD::FRCP: return "X86ISD::FRCP";
14125 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14126 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14127 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14128 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14129 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14130 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14131 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14132 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14133 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14134 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14135 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14136 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14137 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14138 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14139 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14140 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14141 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14142 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14143 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14144 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14145 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14146 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14147 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14148 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14149 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14150 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14151 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14152 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14153 case X86ISD::VSHL: return "X86ISD::VSHL";
14154 case X86ISD::VSRL: return "X86ISD::VSRL";
14155 case X86ISD::VSRA: return "X86ISD::VSRA";
14156 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14157 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14158 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14159 case X86ISD::CMPP: return "X86ISD::CMPP";
14160 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14161 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14162 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14163 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14164 case X86ISD::ADD: return "X86ISD::ADD";
14165 case X86ISD::SUB: return "X86ISD::SUB";
14166 case X86ISD::ADC: return "X86ISD::ADC";
14167 case X86ISD::SBB: return "X86ISD::SBB";
14168 case X86ISD::SMUL: return "X86ISD::SMUL";
14169 case X86ISD::UMUL: return "X86ISD::UMUL";
14170 case X86ISD::INC: return "X86ISD::INC";
14171 case X86ISD::DEC: return "X86ISD::DEC";
14172 case X86ISD::OR: return "X86ISD::OR";
14173 case X86ISD::XOR: return "X86ISD::XOR";
14174 case X86ISD::AND: return "X86ISD::AND";
14175 case X86ISD::BZHI: return "X86ISD::BZHI";
14176 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14177 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14178 case X86ISD::PTEST: return "X86ISD::PTEST";
14179 case X86ISD::TESTP: return "X86ISD::TESTP";
14180 case X86ISD::TESTM: return "X86ISD::TESTM";
14181 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14182 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14183 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14184 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14185 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14186 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14187 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14188 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14189 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14190 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14191 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14192 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14193 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14194 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14195 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14196 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14197 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14198 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14199 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14200 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14201 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14202 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14203 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14204 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14205 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14206 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14207 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14208 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14209 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14210 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14211 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14212 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14213 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14214 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14215 case X86ISD::SAHF: return "X86ISD::SAHF";
14216 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14217 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14218 case X86ISD::FMADD: return "X86ISD::FMADD";
14219 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14220 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14221 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14222 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14223 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14224 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14225 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14226 case X86ISD::XTEST: return "X86ISD::XTEST";
14230 // isLegalAddressingMode - Return true if the addressing mode represented
14231 // by AM is legal for this target, for a load/store of the specified type.
14232 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14234 // X86 supports extremely general addressing modes.
14235 CodeModel::Model M = getTargetMachine().getCodeModel();
14236 Reloc::Model R = getTargetMachine().getRelocationModel();
14238 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14239 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14244 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14246 // If a reference to this global requires an extra load, we can't fold it.
14247 if (isGlobalStubReference(GVFlags))
14250 // If BaseGV requires a register for the PIC base, we cannot also have a
14251 // BaseReg specified.
14252 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14255 // If lower 4G is not available, then we must use rip-relative addressing.
14256 if ((M != CodeModel::Small || R != Reloc::Static) &&
14257 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14261 switch (AM.Scale) {
14267 // These scales always work.
14272 // These scales are formed with basereg+scalereg. Only accept if there is
14277 default: // Other stuff never works.
14284 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14285 unsigned Bits = Ty->getScalarSizeInBits();
14287 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14288 // particularly cheaper than those without.
14292 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14293 // variable shifts just as cheap as scalar ones.
14294 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14297 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14298 // fully general vector.
14302 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14303 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14305 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14306 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14307 return NumBits1 > NumBits2;
14310 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14311 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14314 if (!isTypeLegal(EVT::getEVT(Ty1)))
14317 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14319 // Assuming the caller doesn't have a zeroext or signext return parameter,
14320 // truncation all the way down to i1 is valid.
14324 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14325 return isInt<32>(Imm);
14328 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14329 // Can also use sub to handle negated immediates.
14330 return isInt<32>(Imm);
14333 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14334 if (!VT1.isInteger() || !VT2.isInteger())
14336 unsigned NumBits1 = VT1.getSizeInBits();
14337 unsigned NumBits2 = VT2.getSizeInBits();
14338 return NumBits1 > NumBits2;
14341 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14342 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14343 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14346 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14347 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14348 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14351 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14352 EVT VT1 = Val.getValueType();
14353 if (isZExtFree(VT1, VT2))
14356 if (Val.getOpcode() != ISD::LOAD)
14359 if (!VT1.isSimple() || !VT1.isInteger() ||
14360 !VT2.isSimple() || !VT2.isInteger())
14363 switch (VT1.getSimpleVT().SimpleTy) {
14368 // X86 has 8, 16, and 32-bit zero-extending loads.
14376 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14377 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14380 VT = VT.getScalarType();
14382 if (!VT.isSimple())
14385 switch (VT.getSimpleVT().SimpleTy) {
14396 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14397 // i16 instructions are longer (0x66 prefix) and potentially slower.
14398 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14401 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14402 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14403 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14404 /// are assumed to be legal.
14406 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14408 if (!VT.isSimple())
14411 MVT SVT = VT.getSimpleVT();
14413 // Very little shuffling can be done for 64-bit vectors right now.
14414 if (VT.getSizeInBits() == 64)
14417 // FIXME: pshufb, blends, shifts.
14418 return (SVT.getVectorNumElements() == 2 ||
14419 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14420 isMOVLMask(M, SVT) ||
14421 isSHUFPMask(M, SVT) ||
14422 isPSHUFDMask(M, SVT) ||
14423 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14424 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14425 isPALIGNRMask(M, SVT, Subtarget) ||
14426 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14427 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14428 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14429 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14433 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14435 if (!VT.isSimple())
14438 MVT SVT = VT.getSimpleVT();
14439 unsigned NumElts = SVT.getVectorNumElements();
14440 // FIXME: This collection of masks seems suspect.
14443 if (NumElts == 4 && SVT.is128BitVector()) {
14444 return (isMOVLMask(Mask, SVT) ||
14445 isCommutedMOVLMask(Mask, SVT, true) ||
14446 isSHUFPMask(Mask, SVT) ||
14447 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14452 //===----------------------------------------------------------------------===//
14453 // X86 Scheduler Hooks
14454 //===----------------------------------------------------------------------===//
14456 /// Utility function to emit xbegin specifying the start of an RTM region.
14457 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14458 const TargetInstrInfo *TII) {
14459 DebugLoc DL = MI->getDebugLoc();
14461 const BasicBlock *BB = MBB->getBasicBlock();
14462 MachineFunction::iterator I = MBB;
14465 // For the v = xbegin(), we generate
14476 MachineBasicBlock *thisMBB = MBB;
14477 MachineFunction *MF = MBB->getParent();
14478 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14479 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14480 MF->insert(I, mainMBB);
14481 MF->insert(I, sinkMBB);
14483 // Transfer the remainder of BB and its successor edges to sinkMBB.
14484 sinkMBB->splice(sinkMBB->begin(), MBB,
14485 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14486 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14490 // # fallthrough to mainMBB
14491 // # abortion to sinkMBB
14492 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14493 thisMBB->addSuccessor(mainMBB);
14494 thisMBB->addSuccessor(sinkMBB);
14498 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14499 mainMBB->addSuccessor(sinkMBB);
14502 // EAX is live into the sinkMBB
14503 sinkMBB->addLiveIn(X86::EAX);
14504 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14505 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14508 MI->eraseFromParent();
14512 // Get CMPXCHG opcode for the specified data type.
14513 static unsigned getCmpXChgOpcode(EVT VT) {
14514 switch (VT.getSimpleVT().SimpleTy) {
14515 case MVT::i8: return X86::LCMPXCHG8;
14516 case MVT::i16: return X86::LCMPXCHG16;
14517 case MVT::i32: return X86::LCMPXCHG32;
14518 case MVT::i64: return X86::LCMPXCHG64;
14522 llvm_unreachable("Invalid operand size!");
14525 // Get LOAD opcode for the specified data type.
14526 static unsigned getLoadOpcode(EVT VT) {
14527 switch (VT.getSimpleVT().SimpleTy) {
14528 case MVT::i8: return X86::MOV8rm;
14529 case MVT::i16: return X86::MOV16rm;
14530 case MVT::i32: return X86::MOV32rm;
14531 case MVT::i64: return X86::MOV64rm;
14535 llvm_unreachable("Invalid operand size!");
14538 // Get opcode of the non-atomic one from the specified atomic instruction.
14539 static unsigned getNonAtomicOpcode(unsigned Opc) {
14541 case X86::ATOMAND8: return X86::AND8rr;
14542 case X86::ATOMAND16: return X86::AND16rr;
14543 case X86::ATOMAND32: return X86::AND32rr;
14544 case X86::ATOMAND64: return X86::AND64rr;
14545 case X86::ATOMOR8: return X86::OR8rr;
14546 case X86::ATOMOR16: return X86::OR16rr;
14547 case X86::ATOMOR32: return X86::OR32rr;
14548 case X86::ATOMOR64: return X86::OR64rr;
14549 case X86::ATOMXOR8: return X86::XOR8rr;
14550 case X86::ATOMXOR16: return X86::XOR16rr;
14551 case X86::ATOMXOR32: return X86::XOR32rr;
14552 case X86::ATOMXOR64: return X86::XOR64rr;
14554 llvm_unreachable("Unhandled atomic-load-op opcode!");
14557 // Get opcode of the non-atomic one from the specified atomic instruction with
14559 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14560 unsigned &ExtraOpc) {
14562 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14563 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14564 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14565 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14566 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14567 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14568 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14569 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14570 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14571 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14572 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14573 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14574 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14575 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14576 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14577 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14578 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14579 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14580 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14581 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14583 llvm_unreachable("Unhandled atomic-load-op opcode!");
14586 // Get opcode of the non-atomic one from the specified atomic instruction for
14587 // 64-bit data type on 32-bit target.
14588 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14590 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14591 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14592 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14593 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14594 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14595 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14596 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14597 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14598 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14599 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14601 llvm_unreachable("Unhandled atomic-load-op opcode!");
14604 // Get opcode of the non-atomic one from the specified atomic instruction for
14605 // 64-bit data type on 32-bit target with extra opcode.
14606 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14608 unsigned &ExtraOpc) {
14610 case X86::ATOMNAND6432:
14611 ExtraOpc = X86::NOT32r;
14612 HiOpc = X86::AND32rr;
14613 return X86::AND32rr;
14615 llvm_unreachable("Unhandled atomic-load-op opcode!");
14618 // Get pseudo CMOV opcode from the specified data type.
14619 static unsigned getPseudoCMOVOpc(EVT VT) {
14620 switch (VT.getSimpleVT().SimpleTy) {
14621 case MVT::i8: return X86::CMOV_GR8;
14622 case MVT::i16: return X86::CMOV_GR16;
14623 case MVT::i32: return X86::CMOV_GR32;
14627 llvm_unreachable("Unknown CMOV opcode!");
14630 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14631 // They will be translated into a spin-loop or compare-exchange loop from
14634 // dst = atomic-fetch-op MI.addr, MI.val
14640 // t1 = LOAD MI.addr
14642 // t4 = phi(t1, t3 / loop)
14643 // t2 = OP MI.val, t4
14645 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14651 MachineBasicBlock *
14652 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14653 MachineBasicBlock *MBB) const {
14654 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14655 DebugLoc DL = MI->getDebugLoc();
14657 MachineFunction *MF = MBB->getParent();
14658 MachineRegisterInfo &MRI = MF->getRegInfo();
14660 const BasicBlock *BB = MBB->getBasicBlock();
14661 MachineFunction::iterator I = MBB;
14664 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14665 "Unexpected number of operands");
14667 assert(MI->hasOneMemOperand() &&
14668 "Expected atomic-load-op to have one memoperand");
14670 // Memory Reference
14671 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14672 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14674 unsigned DstReg, SrcReg;
14675 unsigned MemOpndSlot;
14677 unsigned CurOp = 0;
14679 DstReg = MI->getOperand(CurOp++).getReg();
14680 MemOpndSlot = CurOp;
14681 CurOp += X86::AddrNumOperands;
14682 SrcReg = MI->getOperand(CurOp++).getReg();
14684 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14685 MVT::SimpleValueType VT = *RC->vt_begin();
14686 unsigned t1 = MRI.createVirtualRegister(RC);
14687 unsigned t2 = MRI.createVirtualRegister(RC);
14688 unsigned t3 = MRI.createVirtualRegister(RC);
14689 unsigned t4 = MRI.createVirtualRegister(RC);
14690 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14692 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14693 unsigned LOADOpc = getLoadOpcode(VT);
14695 // For the atomic load-arith operator, we generate
14698 // t1 = LOAD [MI.addr]
14700 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
14701 // t1 = OP MI.val, EAX
14703 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14709 MachineBasicBlock *thisMBB = MBB;
14710 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14711 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14712 MF->insert(I, mainMBB);
14713 MF->insert(I, sinkMBB);
14715 MachineInstrBuilder MIB;
14717 // Transfer the remainder of BB and its successor edges to sinkMBB.
14718 sinkMBB->splice(sinkMBB->begin(), MBB,
14719 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14720 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14723 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14724 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14725 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14727 NewMO.setIsKill(false);
14728 MIB.addOperand(NewMO);
14730 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14731 unsigned flags = (*MMOI)->getFlags();
14732 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14733 MachineMemOperand *MMO =
14734 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14735 (*MMOI)->getSize(),
14736 (*MMOI)->getBaseAlignment(),
14737 (*MMOI)->getTBAAInfo(),
14738 (*MMOI)->getRanges());
14739 MIB.addMemOperand(MMO);
14742 thisMBB->addSuccessor(mainMBB);
14745 MachineBasicBlock *origMainMBB = mainMBB;
14748 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14749 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14751 unsigned Opc = MI->getOpcode();
14754 llvm_unreachable("Unhandled atomic-load-op opcode!");
14755 case X86::ATOMAND8:
14756 case X86::ATOMAND16:
14757 case X86::ATOMAND32:
14758 case X86::ATOMAND64:
14760 case X86::ATOMOR16:
14761 case X86::ATOMOR32:
14762 case X86::ATOMOR64:
14763 case X86::ATOMXOR8:
14764 case X86::ATOMXOR16:
14765 case X86::ATOMXOR32:
14766 case X86::ATOMXOR64: {
14767 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14768 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14772 case X86::ATOMNAND8:
14773 case X86::ATOMNAND16:
14774 case X86::ATOMNAND32:
14775 case X86::ATOMNAND64: {
14776 unsigned Tmp = MRI.createVirtualRegister(RC);
14778 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14779 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14781 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14784 case X86::ATOMMAX8:
14785 case X86::ATOMMAX16:
14786 case X86::ATOMMAX32:
14787 case X86::ATOMMAX64:
14788 case X86::ATOMMIN8:
14789 case X86::ATOMMIN16:
14790 case X86::ATOMMIN32:
14791 case X86::ATOMMIN64:
14792 case X86::ATOMUMAX8:
14793 case X86::ATOMUMAX16:
14794 case X86::ATOMUMAX32:
14795 case X86::ATOMUMAX64:
14796 case X86::ATOMUMIN8:
14797 case X86::ATOMUMIN16:
14798 case X86::ATOMUMIN32:
14799 case X86::ATOMUMIN64: {
14801 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14803 BuildMI(mainMBB, DL, TII->get(CMPOpc))
14807 if (Subtarget->hasCMov()) {
14808 if (VT != MVT::i8) {
14810 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14814 // Promote i8 to i32 to use CMOV32
14815 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14816 const TargetRegisterClass *RC32 =
14817 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14818 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14819 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14820 unsigned Tmp = MRI.createVirtualRegister(RC32);
14822 unsigned Undef = MRI.createVirtualRegister(RC32);
14823 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14825 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14828 .addImm(X86::sub_8bit);
14829 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14832 .addImm(X86::sub_8bit);
14834 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14838 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14839 .addReg(Tmp, 0, X86::sub_8bit);
14842 // Use pseudo select and lower them.
14843 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14844 "Invalid atomic-load-op transformation!");
14845 unsigned SelOpc = getPseudoCMOVOpc(VT);
14846 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14847 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14848 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14849 .addReg(SrcReg).addReg(t4)
14851 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14852 // Replace the original PHI node as mainMBB is changed after CMOV
14854 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14855 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14856 Phi->eraseFromParent();
14862 // Copy PhyReg back from virtual register.
14863 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14866 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14867 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14868 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14870 NewMO.setIsKill(false);
14871 MIB.addOperand(NewMO);
14874 MIB.setMemRefs(MMOBegin, MMOEnd);
14876 // Copy PhyReg back to virtual register.
14877 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14880 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14882 mainMBB->addSuccessor(origMainMBB);
14883 mainMBB->addSuccessor(sinkMBB);
14886 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14887 TII->get(TargetOpcode::COPY), DstReg)
14890 MI->eraseFromParent();
14894 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14895 // instructions. They will be translated into a spin-loop or compare-exchange
14899 // dst = atomic-fetch-op MI.addr, MI.val
14905 // t1L = LOAD [MI.addr + 0]
14906 // t1H = LOAD [MI.addr + 4]
14908 // t4L = phi(t1L, t3L / loop)
14909 // t4H = phi(t1H, t3H / loop)
14910 // t2L = OP MI.val.lo, t4L
14911 // t2H = OP MI.val.hi, t4H
14916 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14924 MachineBasicBlock *
14925 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14926 MachineBasicBlock *MBB) const {
14927 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14928 DebugLoc DL = MI->getDebugLoc();
14930 MachineFunction *MF = MBB->getParent();
14931 MachineRegisterInfo &MRI = MF->getRegInfo();
14933 const BasicBlock *BB = MBB->getBasicBlock();
14934 MachineFunction::iterator I = MBB;
14937 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14938 "Unexpected number of operands");
14940 assert(MI->hasOneMemOperand() &&
14941 "Expected atomic-load-op32 to have one memoperand");
14943 // Memory Reference
14944 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14945 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14947 unsigned DstLoReg, DstHiReg;
14948 unsigned SrcLoReg, SrcHiReg;
14949 unsigned MemOpndSlot;
14951 unsigned CurOp = 0;
14953 DstLoReg = MI->getOperand(CurOp++).getReg();
14954 DstHiReg = MI->getOperand(CurOp++).getReg();
14955 MemOpndSlot = CurOp;
14956 CurOp += X86::AddrNumOperands;
14957 SrcLoReg = MI->getOperand(CurOp++).getReg();
14958 SrcHiReg = MI->getOperand(CurOp++).getReg();
14960 const TargetRegisterClass *RC = &X86::GR32RegClass;
14961 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14963 unsigned t1L = MRI.createVirtualRegister(RC);
14964 unsigned t1H = MRI.createVirtualRegister(RC);
14965 unsigned t2L = MRI.createVirtualRegister(RC);
14966 unsigned t2H = MRI.createVirtualRegister(RC);
14967 unsigned t3L = MRI.createVirtualRegister(RC);
14968 unsigned t3H = MRI.createVirtualRegister(RC);
14969 unsigned t4L = MRI.createVirtualRegister(RC);
14970 unsigned t4H = MRI.createVirtualRegister(RC);
14972 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14973 unsigned LOADOpc = X86::MOV32rm;
14975 // For the atomic load-arith operator, we generate
14978 // t1L = LOAD [MI.addr + 0]
14979 // t1H = LOAD [MI.addr + 4]
14981 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
14982 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
14983 // t2L = OP MI.val.lo, t4L
14984 // t2H = OP MI.val.hi, t4H
14987 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14995 MachineBasicBlock *thisMBB = MBB;
14996 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14997 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14998 MF->insert(I, mainMBB);
14999 MF->insert(I, sinkMBB);
15001 MachineInstrBuilder MIB;
15003 // Transfer the remainder of BB and its successor edges to sinkMBB.
15004 sinkMBB->splice(sinkMBB->begin(), MBB,
15005 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15006 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15010 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15011 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15012 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15014 NewMO.setIsKill(false);
15015 MIB.addOperand(NewMO);
15017 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15018 unsigned flags = (*MMOI)->getFlags();
15019 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15020 MachineMemOperand *MMO =
15021 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15022 (*MMOI)->getSize(),
15023 (*MMOI)->getBaseAlignment(),
15024 (*MMOI)->getTBAAInfo(),
15025 (*MMOI)->getRanges());
15026 MIB.addMemOperand(MMO);
15028 MachineInstr *LowMI = MIB;
15031 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15032 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15033 if (i == X86::AddrDisp) {
15034 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15036 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15038 NewMO.setIsKill(false);
15039 MIB.addOperand(NewMO);
15042 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15044 thisMBB->addSuccessor(mainMBB);
15047 MachineBasicBlock *origMainMBB = mainMBB;
15050 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15051 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15052 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15053 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15055 unsigned Opc = MI->getOpcode();
15058 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15059 case X86::ATOMAND6432:
15060 case X86::ATOMOR6432:
15061 case X86::ATOMXOR6432:
15062 case X86::ATOMADD6432:
15063 case X86::ATOMSUB6432: {
15065 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15066 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15068 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15072 case X86::ATOMNAND6432: {
15073 unsigned HiOpc, NOTOpc;
15074 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15075 unsigned TmpL = MRI.createVirtualRegister(RC);
15076 unsigned TmpH = MRI.createVirtualRegister(RC);
15077 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15079 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15081 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15082 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15085 case X86::ATOMMAX6432:
15086 case X86::ATOMMIN6432:
15087 case X86::ATOMUMAX6432:
15088 case X86::ATOMUMIN6432: {
15090 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15091 unsigned cL = MRI.createVirtualRegister(RC8);
15092 unsigned cH = MRI.createVirtualRegister(RC8);
15093 unsigned cL32 = MRI.createVirtualRegister(RC);
15094 unsigned cH32 = MRI.createVirtualRegister(RC);
15095 unsigned cc = MRI.createVirtualRegister(RC);
15096 // cl := cmp src_lo, lo
15097 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15098 .addReg(SrcLoReg).addReg(t4L);
15099 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15100 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15101 // ch := cmp src_hi, hi
15102 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15103 .addReg(SrcHiReg).addReg(t4H);
15104 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15105 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15106 // cc := if (src_hi == hi) ? cl : ch;
15107 if (Subtarget->hasCMov()) {
15108 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15109 .addReg(cH32).addReg(cL32);
15111 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15112 .addReg(cH32).addReg(cL32)
15113 .addImm(X86::COND_E);
15114 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15116 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15117 if (Subtarget->hasCMov()) {
15118 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15119 .addReg(SrcLoReg).addReg(t4L);
15120 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15121 .addReg(SrcHiReg).addReg(t4H);
15123 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15124 .addReg(SrcLoReg).addReg(t4L)
15125 .addImm(X86::COND_NE);
15126 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15127 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15128 // 2nd CMOV lowering.
15129 mainMBB->addLiveIn(X86::EFLAGS);
15130 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15131 .addReg(SrcHiReg).addReg(t4H)
15132 .addImm(X86::COND_NE);
15133 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15134 // Replace the original PHI node as mainMBB is changed after CMOV
15136 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15137 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15138 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15139 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15140 PhiL->eraseFromParent();
15141 PhiH->eraseFromParent();
15145 case X86::ATOMSWAP6432: {
15147 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15148 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15149 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15154 // Copy EDX:EAX back from HiReg:LoReg
15155 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15156 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15157 // Copy ECX:EBX from t1H:t1L
15158 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15159 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15161 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15162 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15163 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15165 NewMO.setIsKill(false);
15166 MIB.addOperand(NewMO);
15168 MIB.setMemRefs(MMOBegin, MMOEnd);
15170 // Copy EDX:EAX back to t3H:t3L
15171 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15172 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15174 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15176 mainMBB->addSuccessor(origMainMBB);
15177 mainMBB->addSuccessor(sinkMBB);
15180 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15181 TII->get(TargetOpcode::COPY), DstLoReg)
15183 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15184 TII->get(TargetOpcode::COPY), DstHiReg)
15187 MI->eraseFromParent();
15191 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15192 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15193 // in the .td file.
15194 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15195 const TargetInstrInfo *TII) {
15197 switch (MI->getOpcode()) {
15198 default: llvm_unreachable("illegal opcode!");
15199 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15200 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15201 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15202 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15203 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15204 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15205 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15206 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15209 DebugLoc dl = MI->getDebugLoc();
15210 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15212 unsigned NumArgs = MI->getNumOperands();
15213 for (unsigned i = 1; i < NumArgs; ++i) {
15214 MachineOperand &Op = MI->getOperand(i);
15215 if (!(Op.isReg() && Op.isImplicit()))
15216 MIB.addOperand(Op);
15218 if (MI->hasOneMemOperand())
15219 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15221 BuildMI(*BB, MI, dl,
15222 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15223 .addReg(X86::XMM0);
15225 MI->eraseFromParent();
15229 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15230 // defs in an instruction pattern
15231 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15232 const TargetInstrInfo *TII) {
15234 switch (MI->getOpcode()) {
15235 default: llvm_unreachable("illegal opcode!");
15236 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15237 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15238 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15239 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15240 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15241 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15242 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15243 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15246 DebugLoc dl = MI->getDebugLoc();
15247 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15249 unsigned NumArgs = MI->getNumOperands(); // remove the results
15250 for (unsigned i = 1; i < NumArgs; ++i) {
15251 MachineOperand &Op = MI->getOperand(i);
15252 if (!(Op.isReg() && Op.isImplicit()))
15253 MIB.addOperand(Op);
15255 if (MI->hasOneMemOperand())
15256 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15258 BuildMI(*BB, MI, dl,
15259 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15262 MI->eraseFromParent();
15266 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15267 const TargetInstrInfo *TII,
15268 const X86Subtarget* Subtarget) {
15269 DebugLoc dl = MI->getDebugLoc();
15271 // Address into RAX/EAX, other two args into ECX, EDX.
15272 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15273 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15274 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15275 for (int i = 0; i < X86::AddrNumOperands; ++i)
15276 MIB.addOperand(MI->getOperand(i));
15278 unsigned ValOps = X86::AddrNumOperands;
15279 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15280 .addReg(MI->getOperand(ValOps).getReg());
15281 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15282 .addReg(MI->getOperand(ValOps+1).getReg());
15284 // The instruction doesn't actually take any operands though.
15285 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15287 MI->eraseFromParent(); // The pseudo is gone now.
15291 MachineBasicBlock *
15292 X86TargetLowering::EmitVAARG64WithCustomInserter(
15294 MachineBasicBlock *MBB) const {
15295 // Emit va_arg instruction on X86-64.
15297 // Operands to this pseudo-instruction:
15298 // 0 ) Output : destination address (reg)
15299 // 1-5) Input : va_list address (addr, i64mem)
15300 // 6 ) ArgSize : Size (in bytes) of vararg type
15301 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15302 // 8 ) Align : Alignment of type
15303 // 9 ) EFLAGS (implicit-def)
15305 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15306 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15308 unsigned DestReg = MI->getOperand(0).getReg();
15309 MachineOperand &Base = MI->getOperand(1);
15310 MachineOperand &Scale = MI->getOperand(2);
15311 MachineOperand &Index = MI->getOperand(3);
15312 MachineOperand &Disp = MI->getOperand(4);
15313 MachineOperand &Segment = MI->getOperand(5);
15314 unsigned ArgSize = MI->getOperand(6).getImm();
15315 unsigned ArgMode = MI->getOperand(7).getImm();
15316 unsigned Align = MI->getOperand(8).getImm();
15318 // Memory Reference
15319 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15320 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15321 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15323 // Machine Information
15324 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15325 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15326 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15327 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15328 DebugLoc DL = MI->getDebugLoc();
15330 // struct va_list {
15333 // i64 overflow_area (address)
15334 // i64 reg_save_area (address)
15336 // sizeof(va_list) = 24
15337 // alignment(va_list) = 8
15339 unsigned TotalNumIntRegs = 6;
15340 unsigned TotalNumXMMRegs = 8;
15341 bool UseGPOffset = (ArgMode == 1);
15342 bool UseFPOffset = (ArgMode == 2);
15343 unsigned MaxOffset = TotalNumIntRegs * 8 +
15344 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15346 /* Align ArgSize to a multiple of 8 */
15347 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15348 bool NeedsAlign = (Align > 8);
15350 MachineBasicBlock *thisMBB = MBB;
15351 MachineBasicBlock *overflowMBB;
15352 MachineBasicBlock *offsetMBB;
15353 MachineBasicBlock *endMBB;
15355 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15356 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15357 unsigned OffsetReg = 0;
15359 if (!UseGPOffset && !UseFPOffset) {
15360 // If we only pull from the overflow region, we don't create a branch.
15361 // We don't need to alter control flow.
15362 OffsetDestReg = 0; // unused
15363 OverflowDestReg = DestReg;
15366 overflowMBB = thisMBB;
15369 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15370 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15371 // If not, pull from overflow_area. (branch to overflowMBB)
15376 // offsetMBB overflowMBB
15381 // Registers for the PHI in endMBB
15382 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15383 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15385 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15386 MachineFunction *MF = MBB->getParent();
15387 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15388 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15389 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15391 MachineFunction::iterator MBBIter = MBB;
15394 // Insert the new basic blocks
15395 MF->insert(MBBIter, offsetMBB);
15396 MF->insert(MBBIter, overflowMBB);
15397 MF->insert(MBBIter, endMBB);
15399 // Transfer the remainder of MBB and its successor edges to endMBB.
15400 endMBB->splice(endMBB->begin(), thisMBB,
15401 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15402 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15404 // Make offsetMBB and overflowMBB successors of thisMBB
15405 thisMBB->addSuccessor(offsetMBB);
15406 thisMBB->addSuccessor(overflowMBB);
15408 // endMBB is a successor of both offsetMBB and overflowMBB
15409 offsetMBB->addSuccessor(endMBB);
15410 overflowMBB->addSuccessor(endMBB);
15412 // Load the offset value into a register
15413 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15414 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15418 .addDisp(Disp, UseFPOffset ? 4 : 0)
15419 .addOperand(Segment)
15420 .setMemRefs(MMOBegin, MMOEnd);
15422 // Check if there is enough room left to pull this argument.
15423 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15425 .addImm(MaxOffset + 8 - ArgSizeA8);
15427 // Branch to "overflowMBB" if offset >= max
15428 // Fall through to "offsetMBB" otherwise
15429 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15430 .addMBB(overflowMBB);
15433 // In offsetMBB, emit code to use the reg_save_area.
15435 assert(OffsetReg != 0);
15437 // Read the reg_save_area address.
15438 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15439 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15444 .addOperand(Segment)
15445 .setMemRefs(MMOBegin, MMOEnd);
15447 // Zero-extend the offset
15448 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15449 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15452 .addImm(X86::sub_32bit);
15454 // Add the offset to the reg_save_area to get the final address.
15455 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15456 .addReg(OffsetReg64)
15457 .addReg(RegSaveReg);
15459 // Compute the offset for the next argument
15460 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15461 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15463 .addImm(UseFPOffset ? 16 : 8);
15465 // Store it back into the va_list.
15466 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15470 .addDisp(Disp, UseFPOffset ? 4 : 0)
15471 .addOperand(Segment)
15472 .addReg(NextOffsetReg)
15473 .setMemRefs(MMOBegin, MMOEnd);
15476 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15481 // Emit code to use overflow area
15484 // Load the overflow_area address into a register.
15485 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15486 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15491 .addOperand(Segment)
15492 .setMemRefs(MMOBegin, MMOEnd);
15494 // If we need to align it, do so. Otherwise, just copy the address
15495 // to OverflowDestReg.
15497 // Align the overflow address
15498 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15499 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15501 // aligned_addr = (addr + (align-1)) & ~(align-1)
15502 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15503 .addReg(OverflowAddrReg)
15506 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15508 .addImm(~(uint64_t)(Align-1));
15510 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15511 .addReg(OverflowAddrReg);
15514 // Compute the next overflow address after this argument.
15515 // (the overflow address should be kept 8-byte aligned)
15516 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15517 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15518 .addReg(OverflowDestReg)
15519 .addImm(ArgSizeA8);
15521 // Store the new overflow address.
15522 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15527 .addOperand(Segment)
15528 .addReg(NextAddrReg)
15529 .setMemRefs(MMOBegin, MMOEnd);
15531 // If we branched, emit the PHI to the front of endMBB.
15533 BuildMI(*endMBB, endMBB->begin(), DL,
15534 TII->get(X86::PHI), DestReg)
15535 .addReg(OffsetDestReg).addMBB(offsetMBB)
15536 .addReg(OverflowDestReg).addMBB(overflowMBB);
15539 // Erase the pseudo instruction
15540 MI->eraseFromParent();
15545 MachineBasicBlock *
15546 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15548 MachineBasicBlock *MBB) const {
15549 // Emit code to save XMM registers to the stack. The ABI says that the
15550 // number of registers to save is given in %al, so it's theoretically
15551 // possible to do an indirect jump trick to avoid saving all of them,
15552 // however this code takes a simpler approach and just executes all
15553 // of the stores if %al is non-zero. It's less code, and it's probably
15554 // easier on the hardware branch predictor, and stores aren't all that
15555 // expensive anyway.
15557 // Create the new basic blocks. One block contains all the XMM stores,
15558 // and one block is the final destination regardless of whether any
15559 // stores were performed.
15560 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15561 MachineFunction *F = MBB->getParent();
15562 MachineFunction::iterator MBBIter = MBB;
15564 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15565 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15566 F->insert(MBBIter, XMMSaveMBB);
15567 F->insert(MBBIter, EndMBB);
15569 // Transfer the remainder of MBB and its successor edges to EndMBB.
15570 EndMBB->splice(EndMBB->begin(), MBB,
15571 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15572 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15574 // The original block will now fall through to the XMM save block.
15575 MBB->addSuccessor(XMMSaveMBB);
15576 // The XMMSaveMBB will fall through to the end block.
15577 XMMSaveMBB->addSuccessor(EndMBB);
15579 // Now add the instructions.
15580 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15581 DebugLoc DL = MI->getDebugLoc();
15583 unsigned CountReg = MI->getOperand(0).getReg();
15584 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15585 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15587 if (!Subtarget->isTargetWin64()) {
15588 // If %al is 0, branch around the XMM save block.
15589 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15590 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15591 MBB->addSuccessor(EndMBB);
15594 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15595 // that was just emitted, but clearly shouldn't be "saved".
15596 assert((MI->getNumOperands() <= 3 ||
15597 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15598 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15599 && "Expected last argument to be EFLAGS");
15600 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15601 // In the XMM save block, save all the XMM argument registers.
15602 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15603 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15604 MachineMemOperand *MMO =
15605 F->getMachineMemOperand(
15606 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15607 MachineMemOperand::MOStore,
15608 /*Size=*/16, /*Align=*/16);
15609 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15610 .addFrameIndex(RegSaveFrameIndex)
15611 .addImm(/*Scale=*/1)
15612 .addReg(/*IndexReg=*/0)
15613 .addImm(/*Disp=*/Offset)
15614 .addReg(/*Segment=*/0)
15615 .addReg(MI->getOperand(i).getReg())
15616 .addMemOperand(MMO);
15619 MI->eraseFromParent(); // The pseudo instruction is gone now.
15624 // The EFLAGS operand of SelectItr might be missing a kill marker
15625 // because there were multiple uses of EFLAGS, and ISel didn't know
15626 // which to mark. Figure out whether SelectItr should have had a
15627 // kill marker, and set it if it should. Returns the correct kill
15629 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15630 MachineBasicBlock* BB,
15631 const TargetRegisterInfo* TRI) {
15632 // Scan forward through BB for a use/def of EFLAGS.
15633 MachineBasicBlock::iterator miI(std::next(SelectItr));
15634 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15635 const MachineInstr& mi = *miI;
15636 if (mi.readsRegister(X86::EFLAGS))
15638 if (mi.definesRegister(X86::EFLAGS))
15639 break; // Should have kill-flag - update below.
15642 // If we hit the end of the block, check whether EFLAGS is live into a
15644 if (miI == BB->end()) {
15645 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15646 sEnd = BB->succ_end();
15647 sItr != sEnd; ++sItr) {
15648 MachineBasicBlock* succ = *sItr;
15649 if (succ->isLiveIn(X86::EFLAGS))
15654 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15655 // out. SelectMI should have a kill flag on EFLAGS.
15656 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15660 MachineBasicBlock *
15661 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15662 MachineBasicBlock *BB) const {
15663 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15664 DebugLoc DL = MI->getDebugLoc();
15666 // To "insert" a SELECT_CC instruction, we actually have to insert the
15667 // diamond control-flow pattern. The incoming instruction knows the
15668 // destination vreg to set, the condition code register to branch on, the
15669 // true/false values to select between, and a branch opcode to use.
15670 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15671 MachineFunction::iterator It = BB;
15677 // cmpTY ccX, r1, r2
15679 // fallthrough --> copy0MBB
15680 MachineBasicBlock *thisMBB = BB;
15681 MachineFunction *F = BB->getParent();
15682 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15683 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15684 F->insert(It, copy0MBB);
15685 F->insert(It, sinkMBB);
15687 // If the EFLAGS register isn't dead in the terminator, then claim that it's
15688 // live into the sink and copy blocks.
15689 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15690 if (!MI->killsRegister(X86::EFLAGS) &&
15691 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15692 copy0MBB->addLiveIn(X86::EFLAGS);
15693 sinkMBB->addLiveIn(X86::EFLAGS);
15696 // Transfer the remainder of BB and its successor edges to sinkMBB.
15697 sinkMBB->splice(sinkMBB->begin(), BB,
15698 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15699 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15701 // Add the true and fallthrough blocks as its successors.
15702 BB->addSuccessor(copy0MBB);
15703 BB->addSuccessor(sinkMBB);
15705 // Create the conditional branch instruction.
15707 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15708 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15711 // %FalseValue = ...
15712 // # fallthrough to sinkMBB
15713 copy0MBB->addSuccessor(sinkMBB);
15716 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15718 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15719 TII->get(X86::PHI), MI->getOperand(0).getReg())
15720 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15721 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15723 MI->eraseFromParent(); // The pseudo instruction is gone now.
15727 MachineBasicBlock *
15728 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15729 bool Is64Bit) const {
15730 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15731 DebugLoc DL = MI->getDebugLoc();
15732 MachineFunction *MF = BB->getParent();
15733 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15735 assert(getTargetMachine().Options.EnableSegmentedStacks);
15737 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15738 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15741 // ... [Till the alloca]
15742 // If stacklet is not large enough, jump to mallocMBB
15745 // Allocate by subtracting from RSP
15746 // Jump to continueMBB
15749 // Allocate by call to runtime
15753 // [rest of original BB]
15756 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15757 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15758 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15760 MachineRegisterInfo &MRI = MF->getRegInfo();
15761 const TargetRegisterClass *AddrRegClass =
15762 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15764 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15765 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15766 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15767 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15768 sizeVReg = MI->getOperand(1).getReg(),
15769 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15771 MachineFunction::iterator MBBIter = BB;
15774 MF->insert(MBBIter, bumpMBB);
15775 MF->insert(MBBIter, mallocMBB);
15776 MF->insert(MBBIter, continueMBB);
15778 continueMBB->splice(continueMBB->begin(), BB,
15779 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15780 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15782 // Add code to the main basic block to check if the stack limit has been hit,
15783 // and if so, jump to mallocMBB otherwise to bumpMBB.
15784 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15785 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15786 .addReg(tmpSPVReg).addReg(sizeVReg);
15787 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15788 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15789 .addReg(SPLimitVReg);
15790 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15792 // bumpMBB simply decreases the stack pointer, since we know the current
15793 // stacklet has enough space.
15794 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15795 .addReg(SPLimitVReg);
15796 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15797 .addReg(SPLimitVReg);
15798 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15800 // Calls into a routine in libgcc to allocate more space from the heap.
15801 const uint32_t *RegMask =
15802 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15804 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15806 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15807 .addExternalSymbol("__morestack_allocate_stack_space")
15808 .addRegMask(RegMask)
15809 .addReg(X86::RDI, RegState::Implicit)
15810 .addReg(X86::RAX, RegState::ImplicitDefine);
15812 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15814 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15815 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15816 .addExternalSymbol("__morestack_allocate_stack_space")
15817 .addRegMask(RegMask)
15818 .addReg(X86::EAX, RegState::ImplicitDefine);
15822 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15825 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15826 .addReg(Is64Bit ? X86::RAX : X86::EAX);
15827 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15829 // Set up the CFG correctly.
15830 BB->addSuccessor(bumpMBB);
15831 BB->addSuccessor(mallocMBB);
15832 mallocMBB->addSuccessor(continueMBB);
15833 bumpMBB->addSuccessor(continueMBB);
15835 // Take care of the PHI nodes.
15836 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15837 MI->getOperand(0).getReg())
15838 .addReg(mallocPtrVReg).addMBB(mallocMBB)
15839 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15841 // Delete the original pseudo instruction.
15842 MI->eraseFromParent();
15845 return continueMBB;
15848 MachineBasicBlock *
15849 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15850 MachineBasicBlock *BB) const {
15851 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15852 DebugLoc DL = MI->getDebugLoc();
15854 assert(!Subtarget->isTargetMacho());
15856 // The lowering is pretty easy: we're just emitting the call to _alloca. The
15857 // non-trivial part is impdef of ESP.
15859 if (Subtarget->isTargetWin64()) {
15860 if (Subtarget->isTargetCygMing()) {
15861 // ___chkstk(Mingw64):
15862 // Clobbers R10, R11, RAX and EFLAGS.
15864 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15865 .addExternalSymbol("___chkstk")
15866 .addReg(X86::RAX, RegState::Implicit)
15867 .addReg(X86::RSP, RegState::Implicit)
15868 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15869 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15870 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15872 // __chkstk(MSVCRT): does not update stack pointer.
15873 // Clobbers R10, R11 and EFLAGS.
15874 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15875 .addExternalSymbol("__chkstk")
15876 .addReg(X86::RAX, RegState::Implicit)
15877 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15878 // RAX has the offset to be subtracted from RSP.
15879 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15884 const char *StackProbeSymbol =
15885 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
15887 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15888 .addExternalSymbol(StackProbeSymbol)
15889 .addReg(X86::EAX, RegState::Implicit)
15890 .addReg(X86::ESP, RegState::Implicit)
15891 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15892 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15893 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15896 MI->eraseFromParent(); // The pseudo instruction is gone now.
15900 MachineBasicBlock *
15901 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15902 MachineBasicBlock *BB) const {
15903 // This is pretty easy. We're taking the value that we received from
15904 // our load from the relocation, sticking it in either RDI (x86-64)
15905 // or EAX and doing an indirect call. The return value will then
15906 // be in the normal return register.
15907 const X86InstrInfo *TII
15908 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15909 DebugLoc DL = MI->getDebugLoc();
15910 MachineFunction *F = BB->getParent();
15912 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15913 assert(MI->getOperand(3).isGlobal() && "This should be a global");
15915 // Get a register mask for the lowered call.
15916 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15917 // proper register mask.
15918 const uint32_t *RegMask =
15919 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15920 if (Subtarget->is64Bit()) {
15921 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15922 TII->get(X86::MOV64rm), X86::RDI)
15924 .addImm(0).addReg(0)
15925 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15926 MI->getOperand(3).getTargetFlags())
15928 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15929 addDirectMem(MIB, X86::RDI);
15930 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15931 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15932 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15933 TII->get(X86::MOV32rm), X86::EAX)
15935 .addImm(0).addReg(0)
15936 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15937 MI->getOperand(3).getTargetFlags())
15939 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15940 addDirectMem(MIB, X86::EAX);
15941 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15943 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15944 TII->get(X86::MOV32rm), X86::EAX)
15945 .addReg(TII->getGlobalBaseReg(F))
15946 .addImm(0).addReg(0)
15947 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15948 MI->getOperand(3).getTargetFlags())
15950 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15951 addDirectMem(MIB, X86::EAX);
15952 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15955 MI->eraseFromParent(); // The pseudo instruction is gone now.
15959 MachineBasicBlock *
15960 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15961 MachineBasicBlock *MBB) const {
15962 DebugLoc DL = MI->getDebugLoc();
15963 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15965 MachineFunction *MF = MBB->getParent();
15966 MachineRegisterInfo &MRI = MF->getRegInfo();
15968 const BasicBlock *BB = MBB->getBasicBlock();
15969 MachineFunction::iterator I = MBB;
15972 // Memory Reference
15973 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15974 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15977 unsigned MemOpndSlot = 0;
15979 unsigned CurOp = 0;
15981 DstReg = MI->getOperand(CurOp++).getReg();
15982 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15983 assert(RC->hasType(MVT::i32) && "Invalid destination!");
15984 unsigned mainDstReg = MRI.createVirtualRegister(RC);
15985 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15987 MemOpndSlot = CurOp;
15989 MVT PVT = getPointerTy();
15990 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15991 "Invalid Pointer Size!");
15993 // For v = setjmp(buf), we generate
15996 // buf[LabelOffset] = restoreMBB
15997 // SjLjSetup restoreMBB
16003 // v = phi(main, restore)
16008 MachineBasicBlock *thisMBB = MBB;
16009 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16010 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16011 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16012 MF->insert(I, mainMBB);
16013 MF->insert(I, sinkMBB);
16014 MF->push_back(restoreMBB);
16016 MachineInstrBuilder MIB;
16018 // Transfer the remainder of BB and its successor edges to sinkMBB.
16019 sinkMBB->splice(sinkMBB->begin(), MBB,
16020 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16021 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16024 unsigned PtrStoreOpc = 0;
16025 unsigned LabelReg = 0;
16026 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16027 Reloc::Model RM = getTargetMachine().getRelocationModel();
16028 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16029 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16031 // Prepare IP either in reg or imm.
16032 if (!UseImmLabel) {
16033 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16034 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16035 LabelReg = MRI.createVirtualRegister(PtrRC);
16036 if (Subtarget->is64Bit()) {
16037 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16041 .addMBB(restoreMBB)
16044 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16045 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16046 .addReg(XII->getGlobalBaseReg(MF))
16049 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16053 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16055 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16056 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16057 if (i == X86::AddrDisp)
16058 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16060 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16063 MIB.addReg(LabelReg);
16065 MIB.addMBB(restoreMBB);
16066 MIB.setMemRefs(MMOBegin, MMOEnd);
16068 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16069 .addMBB(restoreMBB);
16071 const X86RegisterInfo *RegInfo =
16072 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16073 MIB.addRegMask(RegInfo->getNoPreservedMask());
16074 thisMBB->addSuccessor(mainMBB);
16075 thisMBB->addSuccessor(restoreMBB);
16079 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16080 mainMBB->addSuccessor(sinkMBB);
16083 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16084 TII->get(X86::PHI), DstReg)
16085 .addReg(mainDstReg).addMBB(mainMBB)
16086 .addReg(restoreDstReg).addMBB(restoreMBB);
16089 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16090 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16091 restoreMBB->addSuccessor(sinkMBB);
16093 MI->eraseFromParent();
16097 MachineBasicBlock *
16098 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16099 MachineBasicBlock *MBB) const {
16100 DebugLoc DL = MI->getDebugLoc();
16101 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16103 MachineFunction *MF = MBB->getParent();
16104 MachineRegisterInfo &MRI = MF->getRegInfo();
16106 // Memory Reference
16107 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16108 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16110 MVT PVT = getPointerTy();
16111 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16112 "Invalid Pointer Size!");
16114 const TargetRegisterClass *RC =
16115 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16116 unsigned Tmp = MRI.createVirtualRegister(RC);
16117 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16118 const X86RegisterInfo *RegInfo =
16119 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16120 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16121 unsigned SP = RegInfo->getStackRegister();
16123 MachineInstrBuilder MIB;
16125 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16126 const int64_t SPOffset = 2 * PVT.getStoreSize();
16128 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16129 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16132 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16133 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16134 MIB.addOperand(MI->getOperand(i));
16135 MIB.setMemRefs(MMOBegin, MMOEnd);
16137 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16138 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16139 if (i == X86::AddrDisp)
16140 MIB.addDisp(MI->getOperand(i), LabelOffset);
16142 MIB.addOperand(MI->getOperand(i));
16144 MIB.setMemRefs(MMOBegin, MMOEnd);
16146 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16147 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16148 if (i == X86::AddrDisp)
16149 MIB.addDisp(MI->getOperand(i), SPOffset);
16151 MIB.addOperand(MI->getOperand(i));
16153 MIB.setMemRefs(MMOBegin, MMOEnd);
16155 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16157 MI->eraseFromParent();
16161 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16162 // accumulator loops. Writing back to the accumulator allows the coalescer
16163 // to remove extra copies in the loop.
16164 MachineBasicBlock *
16165 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16166 MachineBasicBlock *MBB) const {
16167 MachineOperand &AddendOp = MI->getOperand(3);
16169 // Bail out early if the addend isn't a register - we can't switch these.
16170 if (!AddendOp.isReg())
16173 MachineFunction &MF = *MBB->getParent();
16174 MachineRegisterInfo &MRI = MF.getRegInfo();
16176 // Check whether the addend is defined by a PHI:
16177 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16178 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16179 if (!AddendDef.isPHI())
16182 // Look for the following pattern:
16184 // %addend = phi [%entry, 0], [%loop, %result]
16186 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16190 // %addend = phi [%entry, 0], [%loop, %result]
16192 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16194 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16195 assert(AddendDef.getOperand(i).isReg());
16196 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16197 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16198 if (&PHISrcInst == MI) {
16199 // Found a matching instruction.
16200 unsigned NewFMAOpc = 0;
16201 switch (MI->getOpcode()) {
16202 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16203 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16204 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16205 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16206 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16207 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16208 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16209 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16210 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16211 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16212 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16213 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16214 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16215 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16216 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16217 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16218 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16219 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16220 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16221 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16222 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16223 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16224 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16225 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16226 default: llvm_unreachable("Unrecognized FMA variant.");
16229 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16230 MachineInstrBuilder MIB =
16231 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16232 .addOperand(MI->getOperand(0))
16233 .addOperand(MI->getOperand(3))
16234 .addOperand(MI->getOperand(2))
16235 .addOperand(MI->getOperand(1));
16236 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16237 MI->eraseFromParent();
16244 MachineBasicBlock *
16245 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16246 MachineBasicBlock *BB) const {
16247 switch (MI->getOpcode()) {
16248 default: llvm_unreachable("Unexpected instr type to insert");
16249 case X86::TAILJMPd64:
16250 case X86::TAILJMPr64:
16251 case X86::TAILJMPm64:
16252 llvm_unreachable("TAILJMP64 would not be touched here.");
16253 case X86::TCRETURNdi64:
16254 case X86::TCRETURNri64:
16255 case X86::TCRETURNmi64:
16257 case X86::WIN_ALLOCA:
16258 return EmitLoweredWinAlloca(MI, BB);
16259 case X86::SEG_ALLOCA_32:
16260 return EmitLoweredSegAlloca(MI, BB, false);
16261 case X86::SEG_ALLOCA_64:
16262 return EmitLoweredSegAlloca(MI, BB, true);
16263 case X86::TLSCall_32:
16264 case X86::TLSCall_64:
16265 return EmitLoweredTLSCall(MI, BB);
16266 case X86::CMOV_GR8:
16267 case X86::CMOV_FR32:
16268 case X86::CMOV_FR64:
16269 case X86::CMOV_V4F32:
16270 case X86::CMOV_V2F64:
16271 case X86::CMOV_V2I64:
16272 case X86::CMOV_V8F32:
16273 case X86::CMOV_V4F64:
16274 case X86::CMOV_V4I64:
16275 case X86::CMOV_V16F32:
16276 case X86::CMOV_V8F64:
16277 case X86::CMOV_V8I64:
16278 case X86::CMOV_GR16:
16279 case X86::CMOV_GR32:
16280 case X86::CMOV_RFP32:
16281 case X86::CMOV_RFP64:
16282 case X86::CMOV_RFP80:
16283 return EmitLoweredSelect(MI, BB);
16285 case X86::FP32_TO_INT16_IN_MEM:
16286 case X86::FP32_TO_INT32_IN_MEM:
16287 case X86::FP32_TO_INT64_IN_MEM:
16288 case X86::FP64_TO_INT16_IN_MEM:
16289 case X86::FP64_TO_INT32_IN_MEM:
16290 case X86::FP64_TO_INT64_IN_MEM:
16291 case X86::FP80_TO_INT16_IN_MEM:
16292 case X86::FP80_TO_INT32_IN_MEM:
16293 case X86::FP80_TO_INT64_IN_MEM: {
16294 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16295 DebugLoc DL = MI->getDebugLoc();
16297 // Change the floating point control register to use "round towards zero"
16298 // mode when truncating to an integer value.
16299 MachineFunction *F = BB->getParent();
16300 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16301 addFrameReference(BuildMI(*BB, MI, DL,
16302 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16304 // Load the old value of the high byte of the control word...
16306 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16307 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16310 // Set the high part to be round to zero...
16311 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16314 // Reload the modified control word now...
16315 addFrameReference(BuildMI(*BB, MI, DL,
16316 TII->get(X86::FLDCW16m)), CWFrameIdx);
16318 // Restore the memory image of control word to original value
16319 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16322 // Get the X86 opcode to use.
16324 switch (MI->getOpcode()) {
16325 default: llvm_unreachable("illegal opcode!");
16326 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16327 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16328 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16329 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16330 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16331 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16332 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16333 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16334 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16338 MachineOperand &Op = MI->getOperand(0);
16340 AM.BaseType = X86AddressMode::RegBase;
16341 AM.Base.Reg = Op.getReg();
16343 AM.BaseType = X86AddressMode::FrameIndexBase;
16344 AM.Base.FrameIndex = Op.getIndex();
16346 Op = MI->getOperand(1);
16348 AM.Scale = Op.getImm();
16349 Op = MI->getOperand(2);
16351 AM.IndexReg = Op.getImm();
16352 Op = MI->getOperand(3);
16353 if (Op.isGlobal()) {
16354 AM.GV = Op.getGlobal();
16356 AM.Disp = Op.getImm();
16358 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16359 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16361 // Reload the original control word now.
16362 addFrameReference(BuildMI(*BB, MI, DL,
16363 TII->get(X86::FLDCW16m)), CWFrameIdx);
16365 MI->eraseFromParent(); // The pseudo instruction is gone now.
16368 // String/text processing lowering.
16369 case X86::PCMPISTRM128REG:
16370 case X86::VPCMPISTRM128REG:
16371 case X86::PCMPISTRM128MEM:
16372 case X86::VPCMPISTRM128MEM:
16373 case X86::PCMPESTRM128REG:
16374 case X86::VPCMPESTRM128REG:
16375 case X86::PCMPESTRM128MEM:
16376 case X86::VPCMPESTRM128MEM:
16377 assert(Subtarget->hasSSE42() &&
16378 "Target must have SSE4.2 or AVX features enabled");
16379 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16381 // String/text processing lowering.
16382 case X86::PCMPISTRIREG:
16383 case X86::VPCMPISTRIREG:
16384 case X86::PCMPISTRIMEM:
16385 case X86::VPCMPISTRIMEM:
16386 case X86::PCMPESTRIREG:
16387 case X86::VPCMPESTRIREG:
16388 case X86::PCMPESTRIMEM:
16389 case X86::VPCMPESTRIMEM:
16390 assert(Subtarget->hasSSE42() &&
16391 "Target must have SSE4.2 or AVX features enabled");
16392 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16394 // Thread synchronization.
16396 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16400 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16402 // Atomic Lowering.
16403 case X86::ATOMAND8:
16404 case X86::ATOMAND16:
16405 case X86::ATOMAND32:
16406 case X86::ATOMAND64:
16409 case X86::ATOMOR16:
16410 case X86::ATOMOR32:
16411 case X86::ATOMOR64:
16413 case X86::ATOMXOR16:
16414 case X86::ATOMXOR8:
16415 case X86::ATOMXOR32:
16416 case X86::ATOMXOR64:
16418 case X86::ATOMNAND8:
16419 case X86::ATOMNAND16:
16420 case X86::ATOMNAND32:
16421 case X86::ATOMNAND64:
16423 case X86::ATOMMAX8:
16424 case X86::ATOMMAX16:
16425 case X86::ATOMMAX32:
16426 case X86::ATOMMAX64:
16428 case X86::ATOMMIN8:
16429 case X86::ATOMMIN16:
16430 case X86::ATOMMIN32:
16431 case X86::ATOMMIN64:
16433 case X86::ATOMUMAX8:
16434 case X86::ATOMUMAX16:
16435 case X86::ATOMUMAX32:
16436 case X86::ATOMUMAX64:
16438 case X86::ATOMUMIN8:
16439 case X86::ATOMUMIN16:
16440 case X86::ATOMUMIN32:
16441 case X86::ATOMUMIN64:
16442 return EmitAtomicLoadArith(MI, BB);
16444 // This group does 64-bit operations on a 32-bit host.
16445 case X86::ATOMAND6432:
16446 case X86::ATOMOR6432:
16447 case X86::ATOMXOR6432:
16448 case X86::ATOMNAND6432:
16449 case X86::ATOMADD6432:
16450 case X86::ATOMSUB6432:
16451 case X86::ATOMMAX6432:
16452 case X86::ATOMMIN6432:
16453 case X86::ATOMUMAX6432:
16454 case X86::ATOMUMIN6432:
16455 case X86::ATOMSWAP6432:
16456 return EmitAtomicLoadArith6432(MI, BB);
16458 case X86::VASTART_SAVE_XMM_REGS:
16459 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16461 case X86::VAARG_64:
16462 return EmitVAARG64WithCustomInserter(MI, BB);
16464 case X86::EH_SjLj_SetJmp32:
16465 case X86::EH_SjLj_SetJmp64:
16466 return emitEHSjLjSetJmp(MI, BB);
16468 case X86::EH_SjLj_LongJmp32:
16469 case X86::EH_SjLj_LongJmp64:
16470 return emitEHSjLjLongJmp(MI, BB);
16472 case TargetOpcode::STACKMAP:
16473 case TargetOpcode::PATCHPOINT:
16474 return emitPatchPoint(MI, BB);
16476 case X86::VFMADDPDr213r:
16477 case X86::VFMADDPSr213r:
16478 case X86::VFMADDSDr213r:
16479 case X86::VFMADDSSr213r:
16480 case X86::VFMSUBPDr213r:
16481 case X86::VFMSUBPSr213r:
16482 case X86::VFMSUBSDr213r:
16483 case X86::VFMSUBSSr213r:
16484 case X86::VFNMADDPDr213r:
16485 case X86::VFNMADDPSr213r:
16486 case X86::VFNMADDSDr213r:
16487 case X86::VFNMADDSSr213r:
16488 case X86::VFNMSUBPDr213r:
16489 case X86::VFNMSUBPSr213r:
16490 case X86::VFNMSUBSDr213r:
16491 case X86::VFNMSUBSSr213r:
16492 case X86::VFMADDPDr213rY:
16493 case X86::VFMADDPSr213rY:
16494 case X86::VFMSUBPDr213rY:
16495 case X86::VFMSUBPSr213rY:
16496 case X86::VFNMADDPDr213rY:
16497 case X86::VFNMADDPSr213rY:
16498 case X86::VFNMSUBPDr213rY:
16499 case X86::VFNMSUBPSr213rY:
16500 return emitFMA3Instr(MI, BB);
16504 //===----------------------------------------------------------------------===//
16505 // X86 Optimization Hooks
16506 //===----------------------------------------------------------------------===//
16508 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16511 const SelectionDAG &DAG,
16512 unsigned Depth) const {
16513 unsigned BitWidth = KnownZero.getBitWidth();
16514 unsigned Opc = Op.getOpcode();
16515 assert((Opc >= ISD::BUILTIN_OP_END ||
16516 Opc == ISD::INTRINSIC_WO_CHAIN ||
16517 Opc == ISD::INTRINSIC_W_CHAIN ||
16518 Opc == ISD::INTRINSIC_VOID) &&
16519 "Should use MaskedValueIsZero if you don't know whether Op"
16520 " is a target node!");
16522 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16536 // These nodes' second result is a boolean.
16537 if (Op.getResNo() == 0)
16540 case X86ISD::SETCC:
16541 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16543 case ISD::INTRINSIC_WO_CHAIN: {
16544 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16545 unsigned NumLoBits = 0;
16548 case Intrinsic::x86_sse_movmsk_ps:
16549 case Intrinsic::x86_avx_movmsk_ps_256:
16550 case Intrinsic::x86_sse2_movmsk_pd:
16551 case Intrinsic::x86_avx_movmsk_pd_256:
16552 case Intrinsic::x86_mmx_pmovmskb:
16553 case Intrinsic::x86_sse2_pmovmskb_128:
16554 case Intrinsic::x86_avx2_pmovmskb: {
16555 // High bits of movmskp{s|d}, pmovmskb are known zero.
16557 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16558 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16559 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16560 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16561 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16562 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16563 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16564 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16566 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16575 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16576 unsigned Depth) const {
16577 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16578 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16579 return Op.getValueType().getScalarType().getSizeInBits();
16585 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16586 /// node is a GlobalAddress + offset.
16587 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16588 const GlobalValue* &GA,
16589 int64_t &Offset) const {
16590 if (N->getOpcode() == X86ISD::Wrapper) {
16591 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16592 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16593 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16597 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16600 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16601 /// same as extracting the high 128-bit part of 256-bit vector and then
16602 /// inserting the result into the low part of a new 256-bit vector
16603 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16604 EVT VT = SVOp->getValueType(0);
16605 unsigned NumElems = VT.getVectorNumElements();
16607 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16608 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16609 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16610 SVOp->getMaskElt(j) >= 0)
16616 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16617 /// same as extracting the low 128-bit part of 256-bit vector and then
16618 /// inserting the result into the high part of a new 256-bit vector
16619 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16620 EVT VT = SVOp->getValueType(0);
16621 unsigned NumElems = VT.getVectorNumElements();
16623 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16624 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16625 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16626 SVOp->getMaskElt(j) >= 0)
16632 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16633 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16634 TargetLowering::DAGCombinerInfo &DCI,
16635 const X86Subtarget* Subtarget) {
16637 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16638 SDValue V1 = SVOp->getOperand(0);
16639 SDValue V2 = SVOp->getOperand(1);
16640 EVT VT = SVOp->getValueType(0);
16641 unsigned NumElems = VT.getVectorNumElements();
16643 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16644 V2.getOpcode() == ISD::CONCAT_VECTORS) {
16648 // V UNDEF BUILD_VECTOR UNDEF
16650 // CONCAT_VECTOR CONCAT_VECTOR
16653 // RESULT: V + zero extended
16655 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16656 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16657 V1.getOperand(1).getOpcode() != ISD::UNDEF)
16660 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16663 // To match the shuffle mask, the first half of the mask should
16664 // be exactly the first vector, and all the rest a splat with the
16665 // first element of the second one.
16666 for (unsigned i = 0; i != NumElems/2; ++i)
16667 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16668 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16671 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16672 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16673 if (Ld->hasNUsesOfValue(1, 0)) {
16674 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16675 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16677 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16678 array_lengthof(Ops),
16680 Ld->getPointerInfo(),
16681 Ld->getAlignment(),
16682 false/*isVolatile*/, true/*ReadMem*/,
16683 false/*WriteMem*/);
16685 // Make sure the newly-created LOAD is in the same position as Ld in
16686 // terms of dependency. We create a TokenFactor for Ld and ResNode,
16687 // and update uses of Ld's output chain to use the TokenFactor.
16688 if (Ld->hasAnyUseOfValue(1)) {
16689 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16690 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16691 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16692 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16693 SDValue(ResNode.getNode(), 1));
16696 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16700 // Emit a zeroed vector and insert the desired subvector on its
16702 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16703 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16704 return DCI.CombineTo(N, InsV);
16707 //===--------------------------------------------------------------------===//
16708 // Combine some shuffles into subvector extracts and inserts:
16711 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16712 if (isShuffleHigh128VectorInsertLow(SVOp)) {
16713 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16714 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16715 return DCI.CombineTo(N, InsV);
16718 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16719 if (isShuffleLow128VectorInsertHigh(SVOp)) {
16720 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16721 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16722 return DCI.CombineTo(N, InsV);
16728 /// PerformShuffleCombine - Performs several different shuffle combines.
16729 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16730 TargetLowering::DAGCombinerInfo &DCI,
16731 const X86Subtarget *Subtarget) {
16733 EVT VT = N->getValueType(0);
16735 // Don't create instructions with illegal types after legalize types has run.
16736 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16737 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16740 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16741 if (Subtarget->hasFp256() && VT.is256BitVector() &&
16742 N->getOpcode() == ISD::VECTOR_SHUFFLE)
16743 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16745 // Only handle 128 wide vector from here on.
16746 if (!VT.is128BitVector())
16749 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16750 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16751 // consecutive, non-overlapping, and in the right order.
16752 SmallVector<SDValue, 16> Elts;
16753 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16754 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16756 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16759 /// PerformTruncateCombine - Converts truncate operation to
16760 /// a sequence of vector shuffle operations.
16761 /// It is possible when we truncate 256-bit vector to 128-bit vector
16762 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16763 TargetLowering::DAGCombinerInfo &DCI,
16764 const X86Subtarget *Subtarget) {
16768 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16769 /// specific shuffle of a load can be folded into a single element load.
16770 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16771 /// shuffles have been customed lowered so we need to handle those here.
16772 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16773 TargetLowering::DAGCombinerInfo &DCI) {
16774 if (DCI.isBeforeLegalizeOps())
16777 SDValue InVec = N->getOperand(0);
16778 SDValue EltNo = N->getOperand(1);
16780 if (!isa<ConstantSDNode>(EltNo))
16783 EVT VT = InVec.getValueType();
16785 bool HasShuffleIntoBitcast = false;
16786 if (InVec.getOpcode() == ISD::BITCAST) {
16787 // Don't duplicate a load with other uses.
16788 if (!InVec.hasOneUse())
16790 EVT BCVT = InVec.getOperand(0).getValueType();
16791 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16793 InVec = InVec.getOperand(0);
16794 HasShuffleIntoBitcast = true;
16797 if (!isTargetShuffle(InVec.getOpcode()))
16800 // Don't duplicate a load with other uses.
16801 if (!InVec.hasOneUse())
16804 SmallVector<int, 16> ShuffleMask;
16806 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16810 // Select the input vector, guarding against out of range extract vector.
16811 unsigned NumElems = VT.getVectorNumElements();
16812 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16813 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16814 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16815 : InVec.getOperand(1);
16817 // If inputs to shuffle are the same for both ops, then allow 2 uses
16818 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16820 if (LdNode.getOpcode() == ISD::BITCAST) {
16821 // Don't duplicate a load with other uses.
16822 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16825 AllowedUses = 1; // only allow 1 load use if we have a bitcast
16826 LdNode = LdNode.getOperand(0);
16829 if (!ISD::isNormalLoad(LdNode.getNode()))
16832 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16834 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16837 if (HasShuffleIntoBitcast) {
16838 // If there's a bitcast before the shuffle, check if the load type and
16839 // alignment is valid.
16840 unsigned Align = LN0->getAlignment();
16841 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16842 unsigned NewAlign = TLI.getDataLayout()->
16843 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16845 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16849 // All checks match so transform back to vector_shuffle so that DAG combiner
16850 // can finish the job
16853 // Create shuffle node taking into account the case that its a unary shuffle
16854 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16855 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16856 InVec.getOperand(0), Shuffle,
16858 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16859 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16863 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16864 /// generation and convert it from being a bunch of shuffles and extracts
16865 /// to a simple store and scalar loads to extract the elements.
16866 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16867 TargetLowering::DAGCombinerInfo &DCI) {
16868 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16869 if (NewOp.getNode())
16872 SDValue InputVector = N->getOperand(0);
16874 // Detect whether we are trying to convert from mmx to i32 and the bitcast
16875 // from mmx to v2i32 has a single usage.
16876 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16877 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16878 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16879 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16880 N->getValueType(0),
16881 InputVector.getNode()->getOperand(0));
16883 // Only operate on vectors of 4 elements, where the alternative shuffling
16884 // gets to be more expensive.
16885 if (InputVector.getValueType() != MVT::v4i32)
16888 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16889 // single use which is a sign-extend or zero-extend, and all elements are
16891 SmallVector<SDNode *, 4> Uses;
16892 unsigned ExtractedElements = 0;
16893 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16894 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16895 if (UI.getUse().getResNo() != InputVector.getResNo())
16898 SDNode *Extract = *UI;
16899 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16902 if (Extract->getValueType(0) != MVT::i32)
16904 if (!Extract->hasOneUse())
16906 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16907 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16909 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16912 // Record which element was extracted.
16913 ExtractedElements |=
16914 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16916 Uses.push_back(Extract);
16919 // If not all the elements were used, this may not be worthwhile.
16920 if (ExtractedElements != 15)
16923 // Ok, we've now decided to do the transformation.
16924 SDLoc dl(InputVector);
16926 // Store the value to a temporary stack slot.
16927 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16928 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16929 MachinePointerInfo(), false, false, 0);
16931 // Replace each use (extract) with a load of the appropriate element.
16932 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16933 UE = Uses.end(); UI != UE; ++UI) {
16934 SDNode *Extract = *UI;
16936 // cOMpute the element's address.
16937 SDValue Idx = Extract->getOperand(1);
16939 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16940 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16941 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16942 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16944 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16945 StackPtr, OffsetVal);
16947 // Load the scalar.
16948 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16949 ScalarAddr, MachinePointerInfo(),
16950 false, false, false, 0);
16952 // Replace the exact with the load.
16953 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16956 // The replacement was made in place; don't return anything.
16960 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16961 static std::pair<unsigned, bool>
16962 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16963 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16964 if (!VT.isVector())
16965 return std::make_pair(0, false);
16967 bool NeedSplit = false;
16968 switch (VT.getSimpleVT().SimpleTy) {
16969 default: return std::make_pair(0, false);
16973 if (!Subtarget->hasAVX2())
16975 if (!Subtarget->hasAVX())
16976 return std::make_pair(0, false);
16981 if (!Subtarget->hasSSE2())
16982 return std::make_pair(0, false);
16985 // SSE2 has only a small subset of the operations.
16986 bool hasUnsigned = Subtarget->hasSSE41() ||
16987 (Subtarget->hasSSE2() && VT == MVT::v16i8);
16988 bool hasSigned = Subtarget->hasSSE41() ||
16989 (Subtarget->hasSSE2() && VT == MVT::v8i16);
16991 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16994 // Check for x CC y ? x : y.
16995 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16996 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17001 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17004 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17007 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17010 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17012 // Check for x CC y ? y : x -- a min/max with reversed arms.
17013 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17014 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17019 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17022 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17025 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17028 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17032 return std::make_pair(Opc, NeedSplit);
17035 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17037 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17038 TargetLowering::DAGCombinerInfo &DCI,
17039 const X86Subtarget *Subtarget) {
17041 SDValue Cond = N->getOperand(0);
17042 // Get the LHS/RHS of the select.
17043 SDValue LHS = N->getOperand(1);
17044 SDValue RHS = N->getOperand(2);
17045 EVT VT = LHS.getValueType();
17046 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17048 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17049 // instructions match the semantics of the common C idiom x<y?x:y but not
17050 // x<=y?x:y, because of how they handle negative zero (which can be
17051 // ignored in unsafe-math mode).
17052 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17053 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17054 (Subtarget->hasSSE2() ||
17055 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17056 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17058 unsigned Opcode = 0;
17059 // Check for x CC y ? x : y.
17060 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17061 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17065 // Converting this to a min would handle NaNs incorrectly, and swapping
17066 // the operands would cause it to handle comparisons between positive
17067 // and negative zero incorrectly.
17068 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17069 if (!DAG.getTarget().Options.UnsafeFPMath &&
17070 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17072 std::swap(LHS, RHS);
17074 Opcode = X86ISD::FMIN;
17077 // Converting this to a min would handle comparisons between positive
17078 // and negative zero incorrectly.
17079 if (!DAG.getTarget().Options.UnsafeFPMath &&
17080 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17082 Opcode = X86ISD::FMIN;
17085 // Converting this to a min would handle both negative zeros and NaNs
17086 // incorrectly, but we can swap the operands to fix both.
17087 std::swap(LHS, RHS);
17091 Opcode = X86ISD::FMIN;
17095 // Converting this to a max would handle comparisons between positive
17096 // and negative zero incorrectly.
17097 if (!DAG.getTarget().Options.UnsafeFPMath &&
17098 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17100 Opcode = X86ISD::FMAX;
17103 // Converting this to a max would handle NaNs incorrectly, and swapping
17104 // the operands would cause it to handle comparisons between positive
17105 // and negative zero incorrectly.
17106 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17107 if (!DAG.getTarget().Options.UnsafeFPMath &&
17108 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17110 std::swap(LHS, RHS);
17112 Opcode = X86ISD::FMAX;
17115 // Converting this to a max would handle both negative zeros and NaNs
17116 // incorrectly, but we can swap the operands to fix both.
17117 std::swap(LHS, RHS);
17121 Opcode = X86ISD::FMAX;
17124 // Check for x CC y ? y : x -- a min/max with reversed arms.
17125 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17126 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17130 // Converting this to a min would handle comparisons between positive
17131 // and negative zero incorrectly, and swapping the operands would
17132 // cause it to handle NaNs incorrectly.
17133 if (!DAG.getTarget().Options.UnsafeFPMath &&
17134 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17135 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17137 std::swap(LHS, RHS);
17139 Opcode = X86ISD::FMIN;
17142 // Converting this to a min would handle NaNs incorrectly.
17143 if (!DAG.getTarget().Options.UnsafeFPMath &&
17144 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17146 Opcode = X86ISD::FMIN;
17149 // Converting this to a min would handle both negative zeros and NaNs
17150 // incorrectly, but we can swap the operands to fix both.
17151 std::swap(LHS, RHS);
17155 Opcode = X86ISD::FMIN;
17159 // Converting this to a max would handle NaNs incorrectly.
17160 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17162 Opcode = X86ISD::FMAX;
17165 // Converting this to a max would handle comparisons between positive
17166 // and negative zero incorrectly, and swapping the operands would
17167 // cause it to handle NaNs incorrectly.
17168 if (!DAG.getTarget().Options.UnsafeFPMath &&
17169 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17170 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17172 std::swap(LHS, RHS);
17174 Opcode = X86ISD::FMAX;
17177 // Converting this to a max would handle both negative zeros and NaNs
17178 // incorrectly, but we can swap the operands to fix both.
17179 std::swap(LHS, RHS);
17183 Opcode = X86ISD::FMAX;
17189 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17192 EVT CondVT = Cond.getValueType();
17193 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17194 CondVT.getVectorElementType() == MVT::i1) {
17195 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17196 // lowering on AVX-512. In this case we convert it to
17197 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17198 // The same situation for all 128 and 256-bit vectors of i8 and i16
17199 EVT OpVT = LHS.getValueType();
17200 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17201 (OpVT.getVectorElementType() == MVT::i8 ||
17202 OpVT.getVectorElementType() == MVT::i16)) {
17203 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17204 DCI.AddToWorklist(Cond.getNode());
17205 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17208 // If this is a select between two integer constants, try to do some
17210 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17211 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17212 // Don't do this for crazy integer types.
17213 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17214 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17215 // so that TrueC (the true value) is larger than FalseC.
17216 bool NeedsCondInvert = false;
17218 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17219 // Efficiently invertible.
17220 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17221 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17222 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17223 NeedsCondInvert = true;
17224 std::swap(TrueC, FalseC);
17227 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17228 if (FalseC->getAPIntValue() == 0 &&
17229 TrueC->getAPIntValue().isPowerOf2()) {
17230 if (NeedsCondInvert) // Invert the condition if needed.
17231 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17232 DAG.getConstant(1, Cond.getValueType()));
17234 // Zero extend the condition if needed.
17235 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17237 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17238 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17239 DAG.getConstant(ShAmt, MVT::i8));
17242 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17243 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17244 if (NeedsCondInvert) // Invert the condition if needed.
17245 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17246 DAG.getConstant(1, Cond.getValueType()));
17248 // Zero extend the condition if needed.
17249 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17250 FalseC->getValueType(0), Cond);
17251 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17252 SDValue(FalseC, 0));
17255 // Optimize cases that will turn into an LEA instruction. This requires
17256 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17257 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17258 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17259 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17261 bool isFastMultiplier = false;
17263 switch ((unsigned char)Diff) {
17265 case 1: // result = add base, cond
17266 case 2: // result = lea base( , cond*2)
17267 case 3: // result = lea base(cond, cond*2)
17268 case 4: // result = lea base( , cond*4)
17269 case 5: // result = lea base(cond, cond*4)
17270 case 8: // result = lea base( , cond*8)
17271 case 9: // result = lea base(cond, cond*8)
17272 isFastMultiplier = true;
17277 if (isFastMultiplier) {
17278 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17279 if (NeedsCondInvert) // Invert the condition if needed.
17280 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17281 DAG.getConstant(1, Cond.getValueType()));
17283 // Zero extend the condition if needed.
17284 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17286 // Scale the condition by the difference.
17288 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17289 DAG.getConstant(Diff, Cond.getValueType()));
17291 // Add the base if non-zero.
17292 if (FalseC->getAPIntValue() != 0)
17293 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17294 SDValue(FalseC, 0));
17301 // Canonicalize max and min:
17302 // (x > y) ? x : y -> (x >= y) ? x : y
17303 // (x < y) ? x : y -> (x <= y) ? x : y
17304 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17305 // the need for an extra compare
17306 // against zero. e.g.
17307 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17309 // testl %edi, %edi
17311 // cmovgl %edi, %eax
17315 // cmovsl %eax, %edi
17316 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17317 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17318 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17319 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17324 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17325 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17326 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17327 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17332 // Early exit check
17333 if (!TLI.isTypeLegal(VT))
17336 // Match VSELECTs into subs with unsigned saturation.
17337 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17338 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17339 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17340 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17341 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17343 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17344 // left side invert the predicate to simplify logic below.
17346 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17348 CC = ISD::getSetCCInverse(CC, true);
17349 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17353 if (Other.getNode() && Other->getNumOperands() == 2 &&
17354 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17355 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17356 SDValue CondRHS = Cond->getOperand(1);
17358 // Look for a general sub with unsigned saturation first.
17359 // x >= y ? x-y : 0 --> subus x, y
17360 // x > y ? x-y : 0 --> subus x, y
17361 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17362 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17363 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17365 // If the RHS is a constant we have to reverse the const canonicalization.
17366 // x > C-1 ? x+-C : 0 --> subus x, C
17367 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17368 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17369 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17370 if (CondRHS.getConstantOperandVal(0) == -A-1)
17371 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17372 DAG.getConstant(-A, VT));
17375 // Another special case: If C was a sign bit, the sub has been
17376 // canonicalized into a xor.
17377 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17378 // it's safe to decanonicalize the xor?
17379 // x s< 0 ? x^C : 0 --> subus x, C
17380 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17381 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17382 isSplatVector(OpRHS.getNode())) {
17383 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17385 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17390 // Try to match a min/max vector operation.
17391 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17392 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17393 unsigned Opc = ret.first;
17394 bool NeedSplit = ret.second;
17396 if (Opc && NeedSplit) {
17397 unsigned NumElems = VT.getVectorNumElements();
17398 // Extract the LHS vectors
17399 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17400 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17402 // Extract the RHS vectors
17403 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17404 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17406 // Create min/max for each subvector
17407 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17408 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17410 // Merge the result
17411 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17413 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17416 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17417 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17418 // Check if SETCC has already been promoted
17419 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17420 // Check that condition value type matches vselect operand type
17423 assert(Cond.getValueType().isVector() &&
17424 "vector select expects a vector selector!");
17426 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17427 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17429 if (!TValIsAllOnes && !FValIsAllZeros) {
17430 // Try invert the condition if true value is not all 1s and false value
17432 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17433 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17435 if (TValIsAllZeros || FValIsAllOnes) {
17436 SDValue CC = Cond.getOperand(2);
17437 ISD::CondCode NewCC =
17438 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17439 Cond.getOperand(0).getValueType().isInteger());
17440 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17441 std::swap(LHS, RHS);
17442 TValIsAllOnes = FValIsAllOnes;
17443 FValIsAllZeros = TValIsAllZeros;
17447 if (TValIsAllOnes || FValIsAllZeros) {
17450 if (TValIsAllOnes && FValIsAllZeros)
17452 else if (TValIsAllOnes)
17453 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17454 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17455 else if (FValIsAllZeros)
17456 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17457 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17459 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17463 // Try to fold this VSELECT into a MOVSS/MOVSD
17464 if (N->getOpcode() == ISD::VSELECT &&
17465 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17466 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17467 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17468 bool CanFold = false;
17469 unsigned NumElems = Cond.getNumOperands();
17473 if (isZero(Cond.getOperand(0))) {
17476 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17477 // fold (vselect <0,-1> -> (movsd A, B)
17478 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17479 CanFold = isAllOnes(Cond.getOperand(i));
17480 } else if (isAllOnes(Cond.getOperand(0))) {
17484 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17485 // fold (vselect <-1,0> -> (movsd B, A)
17486 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17487 CanFold = isZero(Cond.getOperand(i));
17491 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17492 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17493 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17496 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17497 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17498 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17499 // (v2i64 (bitcast B)))))
17501 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17502 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17503 // (v2f64 (bitcast B)))))
17505 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17506 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17507 // (v2i64 (bitcast A)))))
17509 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17510 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17511 // (v2f64 (bitcast A)))))
17513 CanFold = (isZero(Cond.getOperand(0)) &&
17514 isZero(Cond.getOperand(1)) &&
17515 isAllOnes(Cond.getOperand(2)) &&
17516 isAllOnes(Cond.getOperand(3)));
17518 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17519 isAllOnes(Cond.getOperand(1)) &&
17520 isZero(Cond.getOperand(2)) &&
17521 isZero(Cond.getOperand(3))) {
17523 std::swap(LHS, RHS);
17527 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17528 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17529 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17530 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17532 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17538 // If we know that this node is legal then we know that it is going to be
17539 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17540 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17541 // to simplify previous instructions.
17542 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17543 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17544 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17546 // Don't optimize vector selects that map to mask-registers.
17550 // Check all uses of that condition operand to check whether it will be
17551 // consumed by non-BLEND instructions, which may depend on all bits are set
17553 for (SDNode::use_iterator I = Cond->use_begin(),
17554 E = Cond->use_end(); I != E; ++I)
17555 if (I->getOpcode() != ISD::VSELECT)
17556 // TODO: Add other opcodes eventually lowered into BLEND.
17559 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17560 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17562 APInt KnownZero, KnownOne;
17563 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17564 DCI.isBeforeLegalizeOps());
17565 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17566 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17567 DCI.CommitTargetLoweringOpt(TLO);
17573 // Check whether a boolean test is testing a boolean value generated by
17574 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17577 // Simplify the following patterns:
17578 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17579 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17580 // to (Op EFLAGS Cond)
17582 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17583 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17584 // to (Op EFLAGS !Cond)
17586 // where Op could be BRCOND or CMOV.
17588 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17589 // Quit if not CMP and SUB with its value result used.
17590 if (Cmp.getOpcode() != X86ISD::CMP &&
17591 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17594 // Quit if not used as a boolean value.
17595 if (CC != X86::COND_E && CC != X86::COND_NE)
17598 // Check CMP operands. One of them should be 0 or 1 and the other should be
17599 // an SetCC or extended from it.
17600 SDValue Op1 = Cmp.getOperand(0);
17601 SDValue Op2 = Cmp.getOperand(1);
17604 const ConstantSDNode* C = 0;
17605 bool needOppositeCond = (CC == X86::COND_E);
17606 bool checkAgainstTrue = false; // Is it a comparison against 1?
17608 if ((C = dyn_cast<ConstantSDNode>(Op1)))
17610 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17612 else // Quit if all operands are not constants.
17615 if (C->getZExtValue() == 1) {
17616 needOppositeCond = !needOppositeCond;
17617 checkAgainstTrue = true;
17618 } else if (C->getZExtValue() != 0)
17619 // Quit if the constant is neither 0 or 1.
17622 bool truncatedToBoolWithAnd = false;
17623 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17624 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17625 SetCC.getOpcode() == ISD::TRUNCATE ||
17626 SetCC.getOpcode() == ISD::AND) {
17627 if (SetCC.getOpcode() == ISD::AND) {
17629 ConstantSDNode *CS;
17630 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17631 CS->getZExtValue() == 1)
17633 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17634 CS->getZExtValue() == 1)
17638 SetCC = SetCC.getOperand(OpIdx);
17639 truncatedToBoolWithAnd = true;
17641 SetCC = SetCC.getOperand(0);
17644 switch (SetCC.getOpcode()) {
17645 case X86ISD::SETCC_CARRY:
17646 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17647 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17648 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17649 // truncated to i1 using 'and'.
17650 if (checkAgainstTrue && !truncatedToBoolWithAnd)
17652 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17653 "Invalid use of SETCC_CARRY!");
17655 case X86ISD::SETCC:
17656 // Set the condition code or opposite one if necessary.
17657 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17658 if (needOppositeCond)
17659 CC = X86::GetOppositeBranchCondition(CC);
17660 return SetCC.getOperand(1);
17661 case X86ISD::CMOV: {
17662 // Check whether false/true value has canonical one, i.e. 0 or 1.
17663 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17664 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17665 // Quit if true value is not a constant.
17668 // Quit if false value is not a constant.
17670 SDValue Op = SetCC.getOperand(0);
17671 // Skip 'zext' or 'trunc' node.
17672 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17673 Op.getOpcode() == ISD::TRUNCATE)
17674 Op = Op.getOperand(0);
17675 // A special case for rdrand/rdseed, where 0 is set if false cond is
17677 if ((Op.getOpcode() != X86ISD::RDRAND &&
17678 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17681 // Quit if false value is not the constant 0 or 1.
17682 bool FValIsFalse = true;
17683 if (FVal && FVal->getZExtValue() != 0) {
17684 if (FVal->getZExtValue() != 1)
17686 // If FVal is 1, opposite cond is needed.
17687 needOppositeCond = !needOppositeCond;
17688 FValIsFalse = false;
17690 // Quit if TVal is not the constant opposite of FVal.
17691 if (FValIsFalse && TVal->getZExtValue() != 1)
17693 if (!FValIsFalse && TVal->getZExtValue() != 0)
17695 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17696 if (needOppositeCond)
17697 CC = X86::GetOppositeBranchCondition(CC);
17698 return SetCC.getOperand(3);
17705 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17706 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17707 TargetLowering::DAGCombinerInfo &DCI,
17708 const X86Subtarget *Subtarget) {
17711 // If the flag operand isn't dead, don't touch this CMOV.
17712 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17715 SDValue FalseOp = N->getOperand(0);
17716 SDValue TrueOp = N->getOperand(1);
17717 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17718 SDValue Cond = N->getOperand(3);
17720 if (CC == X86::COND_E || CC == X86::COND_NE) {
17721 switch (Cond.getOpcode()) {
17725 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17726 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17727 return (CC == X86::COND_E) ? FalseOp : TrueOp;
17733 Flags = checkBoolTestSetCCCombine(Cond, CC);
17734 if (Flags.getNode() &&
17735 // Extra check as FCMOV only supports a subset of X86 cond.
17736 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17737 SDValue Ops[] = { FalseOp, TrueOp,
17738 DAG.getConstant(CC, MVT::i8), Flags };
17739 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17740 Ops, array_lengthof(Ops));
17743 // If this is a select between two integer constants, try to do some
17744 // optimizations. Note that the operands are ordered the opposite of SELECT
17746 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17747 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17748 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17749 // larger than FalseC (the false value).
17750 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17751 CC = X86::GetOppositeBranchCondition(CC);
17752 std::swap(TrueC, FalseC);
17753 std::swap(TrueOp, FalseOp);
17756 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
17757 // This is efficient for any integer data type (including i8/i16) and
17759 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17760 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17761 DAG.getConstant(CC, MVT::i8), Cond);
17763 // Zero extend the condition if needed.
17764 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17766 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17767 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17768 DAG.getConstant(ShAmt, MVT::i8));
17769 if (N->getNumValues() == 2) // Dead flag value?
17770 return DCI.CombineTo(N, Cond, SDValue());
17774 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
17775 // for any integer data type, including i8/i16.
17776 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17777 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17778 DAG.getConstant(CC, MVT::i8), Cond);
17780 // Zero extend the condition if needed.
17781 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17782 FalseC->getValueType(0), Cond);
17783 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17784 SDValue(FalseC, 0));
17786 if (N->getNumValues() == 2) // Dead flag value?
17787 return DCI.CombineTo(N, Cond, SDValue());
17791 // Optimize cases that will turn into an LEA instruction. This requires
17792 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17793 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17794 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17795 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17797 bool isFastMultiplier = false;
17799 switch ((unsigned char)Diff) {
17801 case 1: // result = add base, cond
17802 case 2: // result = lea base( , cond*2)
17803 case 3: // result = lea base(cond, cond*2)
17804 case 4: // result = lea base( , cond*4)
17805 case 5: // result = lea base(cond, cond*4)
17806 case 8: // result = lea base( , cond*8)
17807 case 9: // result = lea base(cond, cond*8)
17808 isFastMultiplier = true;
17813 if (isFastMultiplier) {
17814 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17815 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17816 DAG.getConstant(CC, MVT::i8), Cond);
17817 // Zero extend the condition if needed.
17818 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17820 // Scale the condition by the difference.
17822 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17823 DAG.getConstant(Diff, Cond.getValueType()));
17825 // Add the base if non-zero.
17826 if (FalseC->getAPIntValue() != 0)
17827 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17828 SDValue(FalseC, 0));
17829 if (N->getNumValues() == 2) // Dead flag value?
17830 return DCI.CombineTo(N, Cond, SDValue());
17837 // Handle these cases:
17838 // (select (x != c), e, c) -> select (x != c), e, x),
17839 // (select (x == c), c, e) -> select (x == c), x, e)
17840 // where the c is an integer constant, and the "select" is the combination
17841 // of CMOV and CMP.
17843 // The rationale for this change is that the conditional-move from a constant
17844 // needs two instructions, however, conditional-move from a register needs
17845 // only one instruction.
17847 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17848 // some instruction-combining opportunities. This opt needs to be
17849 // postponed as late as possible.
17851 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17852 // the DCI.xxxx conditions are provided to postpone the optimization as
17853 // late as possible.
17855 ConstantSDNode *CmpAgainst = 0;
17856 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17857 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17858 !isa<ConstantSDNode>(Cond.getOperand(0))) {
17860 if (CC == X86::COND_NE &&
17861 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17862 CC = X86::GetOppositeBranchCondition(CC);
17863 std::swap(TrueOp, FalseOp);
17866 if (CC == X86::COND_E &&
17867 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17868 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17869 DAG.getConstant(CC, MVT::i8), Cond };
17870 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17871 array_lengthof(Ops));
17879 /// PerformMulCombine - Optimize a single multiply with constant into two
17880 /// in order to implement it with two cheaper instructions, e.g.
17881 /// LEA + SHL, LEA + LEA.
17882 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17883 TargetLowering::DAGCombinerInfo &DCI) {
17884 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17887 EVT VT = N->getValueType(0);
17888 if (VT != MVT::i64)
17891 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17894 uint64_t MulAmt = C->getZExtValue();
17895 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17898 uint64_t MulAmt1 = 0;
17899 uint64_t MulAmt2 = 0;
17900 if ((MulAmt % 9) == 0) {
17902 MulAmt2 = MulAmt / 9;
17903 } else if ((MulAmt % 5) == 0) {
17905 MulAmt2 = MulAmt / 5;
17906 } else if ((MulAmt % 3) == 0) {
17908 MulAmt2 = MulAmt / 3;
17911 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17914 if (isPowerOf2_64(MulAmt2) &&
17915 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17916 // If second multiplifer is pow2, issue it first. We want the multiply by
17917 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17919 std::swap(MulAmt1, MulAmt2);
17922 if (isPowerOf2_64(MulAmt1))
17923 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17924 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17926 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17927 DAG.getConstant(MulAmt1, VT));
17929 if (isPowerOf2_64(MulAmt2))
17930 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17931 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17933 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17934 DAG.getConstant(MulAmt2, VT));
17936 // Do not add new nodes to DAG combiner worklist.
17937 DCI.CombineTo(N, NewMul, false);
17942 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17943 SDValue N0 = N->getOperand(0);
17944 SDValue N1 = N->getOperand(1);
17945 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17946 EVT VT = N0.getValueType();
17948 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17949 // since the result of setcc_c is all zero's or all ones.
17950 if (VT.isInteger() && !VT.isVector() &&
17951 N1C && N0.getOpcode() == ISD::AND &&
17952 N0.getOperand(1).getOpcode() == ISD::Constant) {
17953 SDValue N00 = N0.getOperand(0);
17954 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17955 ((N00.getOpcode() == ISD::ANY_EXTEND ||
17956 N00.getOpcode() == ISD::ZERO_EXTEND) &&
17957 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17958 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17959 APInt ShAmt = N1C->getAPIntValue();
17960 Mask = Mask.shl(ShAmt);
17962 return DAG.getNode(ISD::AND, SDLoc(N), VT,
17963 N00, DAG.getConstant(Mask, VT));
17967 // Hardware support for vector shifts is sparse which makes us scalarize the
17968 // vector operations in many cases. Also, on sandybridge ADD is faster than
17970 // (shl V, 1) -> add V,V
17971 if (isSplatVector(N1.getNode())) {
17972 assert(N0.getValueType().isVector() && "Invalid vector shift type");
17973 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17974 // We shift all of the values by one. In many cases we do not have
17975 // hardware support for this operation. This is better expressed as an ADD
17977 if (N1C && (1 == N1C->getZExtValue())) {
17978 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17985 /// \brief Returns a vector of 0s if the node in input is a vector logical
17986 /// shift by a constant amount which is known to be bigger than or equal
17987 /// to the vector element size in bits.
17988 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17989 const X86Subtarget *Subtarget) {
17990 EVT VT = N->getValueType(0);
17992 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17993 (!Subtarget->hasInt256() ||
17994 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17997 SDValue Amt = N->getOperand(1);
17999 if (isSplatVector(Amt.getNode())) {
18000 SDValue SclrAmt = Amt->getOperand(0);
18001 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18002 APInt ShiftAmt = C->getAPIntValue();
18003 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18005 // SSE2/AVX2 logical shifts always return a vector of 0s
18006 // if the shift amount is bigger than or equal to
18007 // the element size. The constant shift amount will be
18008 // encoded as a 8-bit immediate.
18009 if (ShiftAmt.trunc(8).uge(MaxAmount))
18010 return getZeroVector(VT, Subtarget, DAG, DL);
18017 /// PerformShiftCombine - Combine shifts.
18018 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18019 TargetLowering::DAGCombinerInfo &DCI,
18020 const X86Subtarget *Subtarget) {
18021 if (N->getOpcode() == ISD::SHL) {
18022 SDValue V = PerformSHLCombine(N, DAG);
18023 if (V.getNode()) return V;
18026 if (N->getOpcode() != ISD::SRA) {
18027 // Try to fold this logical shift into a zero vector.
18028 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18029 if (V.getNode()) return V;
18035 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18036 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18037 // and friends. Likewise for OR -> CMPNEQSS.
18038 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18039 TargetLowering::DAGCombinerInfo &DCI,
18040 const X86Subtarget *Subtarget) {
18043 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18044 // we're requiring SSE2 for both.
18045 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18046 SDValue N0 = N->getOperand(0);
18047 SDValue N1 = N->getOperand(1);
18048 SDValue CMP0 = N0->getOperand(1);
18049 SDValue CMP1 = N1->getOperand(1);
18052 // The SETCCs should both refer to the same CMP.
18053 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18056 SDValue CMP00 = CMP0->getOperand(0);
18057 SDValue CMP01 = CMP0->getOperand(1);
18058 EVT VT = CMP00.getValueType();
18060 if (VT == MVT::f32 || VT == MVT::f64) {
18061 bool ExpectingFlags = false;
18062 // Check for any users that want flags:
18063 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18064 !ExpectingFlags && UI != UE; ++UI)
18065 switch (UI->getOpcode()) {
18070 ExpectingFlags = true;
18072 case ISD::CopyToReg:
18073 case ISD::SIGN_EXTEND:
18074 case ISD::ZERO_EXTEND:
18075 case ISD::ANY_EXTEND:
18079 if (!ExpectingFlags) {
18080 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18081 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18083 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18084 X86::CondCode tmp = cc0;
18089 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18090 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18091 // FIXME: need symbolic constants for these magic numbers.
18092 // See X86ATTInstPrinter.cpp:printSSECC().
18093 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18094 if (Subtarget->hasAVX512()) {
18095 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18096 CMP01, DAG.getConstant(x86cc, MVT::i8));
18097 if (N->getValueType(0) != MVT::i1)
18098 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18102 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18103 CMP00.getValueType(), CMP00, CMP01,
18104 DAG.getConstant(x86cc, MVT::i8));
18106 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18107 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18109 if (is64BitFP && !Subtarget->is64Bit()) {
18110 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18111 // 64-bit integer, since that's not a legal type. Since
18112 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18113 // bits, but can do this little dance to extract the lowest 32 bits
18114 // and work with those going forward.
18115 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18117 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18119 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18120 Vector32, DAG.getIntPtrConstant(0));
18124 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18125 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18126 DAG.getConstant(1, IntVT));
18127 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18128 return OneBitOfTruth;
18136 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18137 /// so it can be folded inside ANDNP.
18138 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18139 EVT VT = N->getValueType(0);
18141 // Match direct AllOnes for 128 and 256-bit vectors
18142 if (ISD::isBuildVectorAllOnes(N))
18145 // Look through a bit convert.
18146 if (N->getOpcode() == ISD::BITCAST)
18147 N = N->getOperand(0).getNode();
18149 // Sometimes the operand may come from a insert_subvector building a 256-bit
18151 if (VT.is256BitVector() &&
18152 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18153 SDValue V1 = N->getOperand(0);
18154 SDValue V2 = N->getOperand(1);
18156 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18157 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18158 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18159 ISD::isBuildVectorAllOnes(V2.getNode()))
18166 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18167 // register. In most cases we actually compare or select YMM-sized registers
18168 // and mixing the two types creates horrible code. This method optimizes
18169 // some of the transition sequences.
18170 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18171 TargetLowering::DAGCombinerInfo &DCI,
18172 const X86Subtarget *Subtarget) {
18173 EVT VT = N->getValueType(0);
18174 if (!VT.is256BitVector())
18177 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18178 N->getOpcode() == ISD::ZERO_EXTEND ||
18179 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18181 SDValue Narrow = N->getOperand(0);
18182 EVT NarrowVT = Narrow->getValueType(0);
18183 if (!NarrowVT.is128BitVector())
18186 if (Narrow->getOpcode() != ISD::XOR &&
18187 Narrow->getOpcode() != ISD::AND &&
18188 Narrow->getOpcode() != ISD::OR)
18191 SDValue N0 = Narrow->getOperand(0);
18192 SDValue N1 = Narrow->getOperand(1);
18195 // The Left side has to be a trunc.
18196 if (N0.getOpcode() != ISD::TRUNCATE)
18199 // The type of the truncated inputs.
18200 EVT WideVT = N0->getOperand(0)->getValueType(0);
18204 // The right side has to be a 'trunc' or a constant vector.
18205 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18206 bool RHSConst = (isSplatVector(N1.getNode()) &&
18207 isa<ConstantSDNode>(N1->getOperand(0)));
18208 if (!RHSTrunc && !RHSConst)
18211 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18213 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18216 // Set N0 and N1 to hold the inputs to the new wide operation.
18217 N0 = N0->getOperand(0);
18219 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18220 N1->getOperand(0));
18221 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18222 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18223 } else if (RHSTrunc) {
18224 N1 = N1->getOperand(0);
18227 // Generate the wide operation.
18228 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18229 unsigned Opcode = N->getOpcode();
18231 case ISD::ANY_EXTEND:
18233 case ISD::ZERO_EXTEND: {
18234 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18235 APInt Mask = APInt::getAllOnesValue(InBits);
18236 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18237 return DAG.getNode(ISD::AND, DL, VT,
18238 Op, DAG.getConstant(Mask, VT));
18240 case ISD::SIGN_EXTEND:
18241 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18242 Op, DAG.getValueType(NarrowVT));
18244 llvm_unreachable("Unexpected opcode");
18248 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18249 TargetLowering::DAGCombinerInfo &DCI,
18250 const X86Subtarget *Subtarget) {
18251 EVT VT = N->getValueType(0);
18252 if (DCI.isBeforeLegalizeOps())
18255 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18259 // Create BEXTR and BZHI instructions
18260 // BZHI is X & ((1 << Y) - 1)
18261 // BEXTR is ((X >> imm) & (2**size-1))
18262 if (VT == MVT::i32 || VT == MVT::i64) {
18263 SDValue N0 = N->getOperand(0);
18264 SDValue N1 = N->getOperand(1);
18267 if (Subtarget->hasBMI2()) {
18268 // Check for (and (add (shl 1, Y), -1), X)
18269 if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
18270 SDValue N00 = N0.getOperand(0);
18271 if (N00.getOpcode() == ISD::SHL) {
18272 SDValue N001 = N00.getOperand(1);
18273 assert(N001.getValueType() == MVT::i8 && "unexpected type");
18274 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
18275 if (C && C->getZExtValue() == 1)
18276 return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
18280 // Check for (and X, (add (shl 1, Y), -1))
18281 if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
18282 SDValue N10 = N1.getOperand(0);
18283 if (N10.getOpcode() == ISD::SHL) {
18284 SDValue N101 = N10.getOperand(1);
18285 assert(N101.getValueType() == MVT::i8 && "unexpected type");
18286 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
18287 if (C && C->getZExtValue() == 1)
18288 return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
18293 // Check for BEXTR.
18294 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18295 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18296 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18297 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18298 if (MaskNode && ShiftNode) {
18299 uint64_t Mask = MaskNode->getZExtValue();
18300 uint64_t Shift = ShiftNode->getZExtValue();
18301 if (isMask_64(Mask)) {
18302 uint64_t MaskSize = CountPopulation_64(Mask);
18303 if (Shift + MaskSize <= VT.getSizeInBits())
18304 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18305 DAG.getConstant(Shift | (MaskSize << 8), VT));
18313 // Want to form ANDNP nodes:
18314 // 1) In the hopes of then easily combining them with OR and AND nodes
18315 // to form PBLEND/PSIGN.
18316 // 2) To match ANDN packed intrinsics
18317 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18320 SDValue N0 = N->getOperand(0);
18321 SDValue N1 = N->getOperand(1);
18324 // Check LHS for vnot
18325 if (N0.getOpcode() == ISD::XOR &&
18326 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18327 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18328 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18330 // Check RHS for vnot
18331 if (N1.getOpcode() == ISD::XOR &&
18332 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18333 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18334 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18339 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18340 TargetLowering::DAGCombinerInfo &DCI,
18341 const X86Subtarget *Subtarget) {
18342 if (DCI.isBeforeLegalizeOps())
18345 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18349 SDValue N0 = N->getOperand(0);
18350 SDValue N1 = N->getOperand(1);
18351 EVT VT = N->getValueType(0);
18353 // look for psign/blend
18354 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18355 if (!Subtarget->hasSSSE3() ||
18356 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18359 // Canonicalize pandn to RHS
18360 if (N0.getOpcode() == X86ISD::ANDNP)
18362 // or (and (m, y), (pandn m, x))
18363 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18364 SDValue Mask = N1.getOperand(0);
18365 SDValue X = N1.getOperand(1);
18367 if (N0.getOperand(0) == Mask)
18368 Y = N0.getOperand(1);
18369 if (N0.getOperand(1) == Mask)
18370 Y = N0.getOperand(0);
18372 // Check to see if the mask appeared in both the AND and ANDNP and
18376 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18377 // Look through mask bitcast.
18378 if (Mask.getOpcode() == ISD::BITCAST)
18379 Mask = Mask.getOperand(0);
18380 if (X.getOpcode() == ISD::BITCAST)
18381 X = X.getOperand(0);
18382 if (Y.getOpcode() == ISD::BITCAST)
18383 Y = Y.getOperand(0);
18385 EVT MaskVT = Mask.getValueType();
18387 // Validate that the Mask operand is a vector sra node.
18388 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18389 // there is no psrai.b
18390 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18391 unsigned SraAmt = ~0;
18392 if (Mask.getOpcode() == ISD::SRA) {
18393 SDValue Amt = Mask.getOperand(1);
18394 if (isSplatVector(Amt.getNode())) {
18395 SDValue SclrAmt = Amt->getOperand(0);
18396 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18397 SraAmt = C->getZExtValue();
18399 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18400 SDValue SraC = Mask.getOperand(1);
18401 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18403 if ((SraAmt + 1) != EltBits)
18408 // Now we know we at least have a plendvb with the mask val. See if
18409 // we can form a psignb/w/d.
18410 // psign = x.type == y.type == mask.type && y = sub(0, x);
18411 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18412 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18413 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18414 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18415 "Unsupported VT for PSIGN");
18416 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18417 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18419 // PBLENDVB only available on SSE 4.1
18420 if (!Subtarget->hasSSE41())
18423 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18425 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18426 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18427 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18428 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18429 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18433 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18436 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18437 MachineFunction &MF = DAG.getMachineFunction();
18438 bool OptForSize = MF.getFunction()->getAttributes().
18439 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18441 // SHLD/SHRD instructions have lower register pressure, but on some
18442 // platforms they have higher latency than the equivalent
18443 // series of shifts/or that would otherwise be generated.
18444 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18445 // have higher latencies and we are not optimizing for size.
18446 if (!OptForSize && Subtarget->isSHLDSlow())
18449 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18451 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18453 if (!N0.hasOneUse() || !N1.hasOneUse())
18456 SDValue ShAmt0 = N0.getOperand(1);
18457 if (ShAmt0.getValueType() != MVT::i8)
18459 SDValue ShAmt1 = N1.getOperand(1);
18460 if (ShAmt1.getValueType() != MVT::i8)
18462 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18463 ShAmt0 = ShAmt0.getOperand(0);
18464 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18465 ShAmt1 = ShAmt1.getOperand(0);
18468 unsigned Opc = X86ISD::SHLD;
18469 SDValue Op0 = N0.getOperand(0);
18470 SDValue Op1 = N1.getOperand(0);
18471 if (ShAmt0.getOpcode() == ISD::SUB) {
18472 Opc = X86ISD::SHRD;
18473 std::swap(Op0, Op1);
18474 std::swap(ShAmt0, ShAmt1);
18477 unsigned Bits = VT.getSizeInBits();
18478 if (ShAmt1.getOpcode() == ISD::SUB) {
18479 SDValue Sum = ShAmt1.getOperand(0);
18480 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18481 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18482 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18483 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18484 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18485 return DAG.getNode(Opc, DL, VT,
18487 DAG.getNode(ISD::TRUNCATE, DL,
18490 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18491 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18493 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18494 return DAG.getNode(Opc, DL, VT,
18495 N0.getOperand(0), N1.getOperand(0),
18496 DAG.getNode(ISD::TRUNCATE, DL,
18503 // Generate NEG and CMOV for integer abs.
18504 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18505 EVT VT = N->getValueType(0);
18507 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18508 // 8-bit integer abs to NEG and CMOV.
18509 if (VT.isInteger() && VT.getSizeInBits() == 8)
18512 SDValue N0 = N->getOperand(0);
18513 SDValue N1 = N->getOperand(1);
18516 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18517 // and change it to SUB and CMOV.
18518 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18519 N0.getOpcode() == ISD::ADD &&
18520 N0.getOperand(1) == N1 &&
18521 N1.getOpcode() == ISD::SRA &&
18522 N1.getOperand(0) == N0.getOperand(0))
18523 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18524 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18525 // Generate SUB & CMOV.
18526 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18527 DAG.getConstant(0, VT), N0.getOperand(0));
18529 SDValue Ops[] = { N0.getOperand(0), Neg,
18530 DAG.getConstant(X86::COND_GE, MVT::i8),
18531 SDValue(Neg.getNode(), 1) };
18532 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18533 Ops, array_lengthof(Ops));
18538 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18539 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18540 TargetLowering::DAGCombinerInfo &DCI,
18541 const X86Subtarget *Subtarget) {
18542 if (DCI.isBeforeLegalizeOps())
18545 if (Subtarget->hasCMov()) {
18546 SDValue RV = performIntegerAbsCombine(N, DAG);
18554 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18555 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18556 TargetLowering::DAGCombinerInfo &DCI,
18557 const X86Subtarget *Subtarget) {
18558 LoadSDNode *Ld = cast<LoadSDNode>(N);
18559 EVT RegVT = Ld->getValueType(0);
18560 EVT MemVT = Ld->getMemoryVT();
18562 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18563 unsigned RegSz = RegVT.getSizeInBits();
18565 // On Sandybridge unaligned 256bit loads are inefficient.
18566 ISD::LoadExtType Ext = Ld->getExtensionType();
18567 unsigned Alignment = Ld->getAlignment();
18568 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18569 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18570 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18571 unsigned NumElems = RegVT.getVectorNumElements();
18575 SDValue Ptr = Ld->getBasePtr();
18576 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18578 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18580 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18581 Ld->getPointerInfo(), Ld->isVolatile(),
18582 Ld->isNonTemporal(), Ld->isInvariant(),
18584 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18585 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18586 Ld->getPointerInfo(), Ld->isVolatile(),
18587 Ld->isNonTemporal(), Ld->isInvariant(),
18588 std::min(16U, Alignment));
18589 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18591 Load2.getValue(1));
18593 SDValue NewVec = DAG.getUNDEF(RegVT);
18594 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18595 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18596 return DCI.CombineTo(N, NewVec, TF, true);
18599 // If this is a vector EXT Load then attempt to optimize it using a
18600 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18601 // expansion is still better than scalar code.
18602 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18603 // emit a shuffle and a arithmetic shift.
18604 // TODO: It is possible to support ZExt by zeroing the undef values
18605 // during the shuffle phase or after the shuffle.
18606 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18607 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18608 assert(MemVT != RegVT && "Cannot extend to the same type");
18609 assert(MemVT.isVector() && "Must load a vector from memory");
18611 unsigned NumElems = RegVT.getVectorNumElements();
18612 unsigned MemSz = MemVT.getSizeInBits();
18613 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18615 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18618 // All sizes must be a power of two.
18619 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18622 // Attempt to load the original value using scalar loads.
18623 // Find the largest scalar type that divides the total loaded size.
18624 MVT SclrLoadTy = MVT::i8;
18625 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18626 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18627 MVT Tp = (MVT::SimpleValueType)tp;
18628 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18633 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18634 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18636 SclrLoadTy = MVT::f64;
18638 // Calculate the number of scalar loads that we need to perform
18639 // in order to load our vector from memory.
18640 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18641 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18644 unsigned loadRegZize = RegSz;
18645 if (Ext == ISD::SEXTLOAD && RegSz == 256)
18648 // Represent our vector as a sequence of elements which are the
18649 // largest scalar that we can load.
18650 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18651 loadRegZize/SclrLoadTy.getSizeInBits());
18653 // Represent the data using the same element type that is stored in
18654 // memory. In practice, we ''widen'' MemVT.
18656 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18657 loadRegZize/MemVT.getScalarType().getSizeInBits());
18659 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18660 "Invalid vector type");
18662 // We can't shuffle using an illegal type.
18663 if (!TLI.isTypeLegal(WideVecVT))
18666 SmallVector<SDValue, 8> Chains;
18667 SDValue Ptr = Ld->getBasePtr();
18668 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18669 TLI.getPointerTy());
18670 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18672 for (unsigned i = 0; i < NumLoads; ++i) {
18673 // Perform a single load.
18674 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18675 Ptr, Ld->getPointerInfo(),
18676 Ld->isVolatile(), Ld->isNonTemporal(),
18677 Ld->isInvariant(), Ld->getAlignment());
18678 Chains.push_back(ScalarLoad.getValue(1));
18679 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18680 // another round of DAGCombining.
18682 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18684 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18685 ScalarLoad, DAG.getIntPtrConstant(i));
18687 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18690 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18693 // Bitcast the loaded value to a vector of the original element type, in
18694 // the size of the target vector type.
18695 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18696 unsigned SizeRatio = RegSz/MemSz;
18698 if (Ext == ISD::SEXTLOAD) {
18699 // If we have SSE4.1 we can directly emit a VSEXT node.
18700 if (Subtarget->hasSSE41()) {
18701 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18702 return DCI.CombineTo(N, Sext, TF, true);
18705 // Otherwise we'll shuffle the small elements in the high bits of the
18706 // larger type and perform an arithmetic shift. If the shift is not legal
18707 // it's better to scalarize.
18708 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18711 // Redistribute the loaded elements into the different locations.
18712 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18713 for (unsigned i = 0; i != NumElems; ++i)
18714 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18716 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18717 DAG.getUNDEF(WideVecVT),
18720 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18722 // Build the arithmetic shift.
18723 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18724 MemVT.getVectorElementType().getSizeInBits();
18725 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18726 DAG.getConstant(Amt, RegVT));
18728 return DCI.CombineTo(N, Shuff, TF, true);
18731 // Redistribute the loaded elements into the different locations.
18732 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18733 for (unsigned i = 0; i != NumElems; ++i)
18734 ShuffleVec[i*SizeRatio] = i;
18736 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18737 DAG.getUNDEF(WideVecVT),
18740 // Bitcast to the requested type.
18741 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18742 // Replace the original load with the new sequence
18743 // and return the new chain.
18744 return DCI.CombineTo(N, Shuff, TF, true);
18750 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18751 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18752 const X86Subtarget *Subtarget) {
18753 StoreSDNode *St = cast<StoreSDNode>(N);
18754 EVT VT = St->getValue().getValueType();
18755 EVT StVT = St->getMemoryVT();
18757 SDValue StoredVal = St->getOperand(1);
18758 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18760 // If we are saving a concatenation of two XMM registers, perform two stores.
18761 // On Sandy Bridge, 256-bit memory operations are executed by two
18762 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18763 // memory operation.
18764 unsigned Alignment = St->getAlignment();
18765 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18766 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18767 StVT == VT && !IsAligned) {
18768 unsigned NumElems = VT.getVectorNumElements();
18772 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18773 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18775 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18776 SDValue Ptr0 = St->getBasePtr();
18777 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18779 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18780 St->getPointerInfo(), St->isVolatile(),
18781 St->isNonTemporal(), Alignment);
18782 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18783 St->getPointerInfo(), St->isVolatile(),
18784 St->isNonTemporal(),
18785 std::min(16U, Alignment));
18786 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18789 // Optimize trunc store (of multiple scalars) to shuffle and store.
18790 // First, pack all of the elements in one place. Next, store to memory
18791 // in fewer chunks.
18792 if (St->isTruncatingStore() && VT.isVector()) {
18793 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18794 unsigned NumElems = VT.getVectorNumElements();
18795 assert(StVT != VT && "Cannot truncate to the same type");
18796 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18797 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18799 // From, To sizes and ElemCount must be pow of two
18800 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18801 // We are going to use the original vector elt for storing.
18802 // Accumulated smaller vector elements must be a multiple of the store size.
18803 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18805 unsigned SizeRatio = FromSz / ToSz;
18807 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18809 // Create a type on which we perform the shuffle
18810 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18811 StVT.getScalarType(), NumElems*SizeRatio);
18813 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18815 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18816 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18817 for (unsigned i = 0; i != NumElems; ++i)
18818 ShuffleVec[i] = i * SizeRatio;
18820 // Can't shuffle using an illegal type.
18821 if (!TLI.isTypeLegal(WideVecVT))
18824 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18825 DAG.getUNDEF(WideVecVT),
18827 // At this point all of the data is stored at the bottom of the
18828 // register. We now need to save it to mem.
18830 // Find the largest store unit
18831 MVT StoreType = MVT::i8;
18832 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18833 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18834 MVT Tp = (MVT::SimpleValueType)tp;
18835 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18839 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18840 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18841 (64 <= NumElems * ToSz))
18842 StoreType = MVT::f64;
18844 // Bitcast the original vector into a vector of store-size units
18845 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18846 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18847 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18848 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18849 SmallVector<SDValue, 8> Chains;
18850 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18851 TLI.getPointerTy());
18852 SDValue Ptr = St->getBasePtr();
18854 // Perform one or more big stores into memory.
18855 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18856 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18857 StoreType, ShuffWide,
18858 DAG.getIntPtrConstant(i));
18859 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18860 St->getPointerInfo(), St->isVolatile(),
18861 St->isNonTemporal(), St->getAlignment());
18862 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18863 Chains.push_back(Ch);
18866 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18870 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
18871 // the FP state in cases where an emms may be missing.
18872 // A preferable solution to the general problem is to figure out the right
18873 // places to insert EMMS. This qualifies as a quick hack.
18875 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18876 if (VT.getSizeInBits() != 64)
18879 const Function *F = DAG.getMachineFunction().getFunction();
18880 bool NoImplicitFloatOps = F->getAttributes().
18881 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18882 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18883 && Subtarget->hasSSE2();
18884 if ((VT.isVector() ||
18885 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18886 isa<LoadSDNode>(St->getValue()) &&
18887 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18888 St->getChain().hasOneUse() && !St->isVolatile()) {
18889 SDNode* LdVal = St->getValue().getNode();
18890 LoadSDNode *Ld = 0;
18891 int TokenFactorIndex = -1;
18892 SmallVector<SDValue, 8> Ops;
18893 SDNode* ChainVal = St->getChain().getNode();
18894 // Must be a store of a load. We currently handle two cases: the load
18895 // is a direct child, and it's under an intervening TokenFactor. It is
18896 // possible to dig deeper under nested TokenFactors.
18897 if (ChainVal == LdVal)
18898 Ld = cast<LoadSDNode>(St->getChain());
18899 else if (St->getValue().hasOneUse() &&
18900 ChainVal->getOpcode() == ISD::TokenFactor) {
18901 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18902 if (ChainVal->getOperand(i).getNode() == LdVal) {
18903 TokenFactorIndex = i;
18904 Ld = cast<LoadSDNode>(St->getValue());
18906 Ops.push_back(ChainVal->getOperand(i));
18910 if (!Ld || !ISD::isNormalLoad(Ld))
18913 // If this is not the MMX case, i.e. we are just turning i64 load/store
18914 // into f64 load/store, avoid the transformation if there are multiple
18915 // uses of the loaded value.
18916 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18921 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18922 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18924 if (Subtarget->is64Bit() || F64IsLegal) {
18925 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18926 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18927 Ld->getPointerInfo(), Ld->isVolatile(),
18928 Ld->isNonTemporal(), Ld->isInvariant(),
18929 Ld->getAlignment());
18930 SDValue NewChain = NewLd.getValue(1);
18931 if (TokenFactorIndex != -1) {
18932 Ops.push_back(NewChain);
18933 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18936 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18937 St->getPointerInfo(),
18938 St->isVolatile(), St->isNonTemporal(),
18939 St->getAlignment());
18942 // Otherwise, lower to two pairs of 32-bit loads / stores.
18943 SDValue LoAddr = Ld->getBasePtr();
18944 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18945 DAG.getConstant(4, MVT::i32));
18947 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18948 Ld->getPointerInfo(),
18949 Ld->isVolatile(), Ld->isNonTemporal(),
18950 Ld->isInvariant(), Ld->getAlignment());
18951 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18952 Ld->getPointerInfo().getWithOffset(4),
18953 Ld->isVolatile(), Ld->isNonTemporal(),
18955 MinAlign(Ld->getAlignment(), 4));
18957 SDValue NewChain = LoLd.getValue(1);
18958 if (TokenFactorIndex != -1) {
18959 Ops.push_back(LoLd);
18960 Ops.push_back(HiLd);
18961 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18965 LoAddr = St->getBasePtr();
18966 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18967 DAG.getConstant(4, MVT::i32));
18969 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18970 St->getPointerInfo(),
18971 St->isVolatile(), St->isNonTemporal(),
18972 St->getAlignment());
18973 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18974 St->getPointerInfo().getWithOffset(4),
18976 St->isNonTemporal(),
18977 MinAlign(St->getAlignment(), 4));
18978 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18983 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18984 /// and return the operands for the horizontal operation in LHS and RHS. A
18985 /// horizontal operation performs the binary operation on successive elements
18986 /// of its first operand, then on successive elements of its second operand,
18987 /// returning the resulting values in a vector. For example, if
18988 /// A = < float a0, float a1, float a2, float a3 >
18990 /// B = < float b0, float b1, float b2, float b3 >
18991 /// then the result of doing a horizontal operation on A and B is
18992 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18993 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18994 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18995 /// set to A, RHS to B, and the routine returns 'true'.
18996 /// Note that the binary operation should have the property that if one of the
18997 /// operands is UNDEF then the result is UNDEF.
18998 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18999 // Look for the following pattern: if
19000 // A = < float a0, float a1, float a2, float a3 >
19001 // B = < float b0, float b1, float b2, float b3 >
19003 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19004 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19005 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19006 // which is A horizontal-op B.
19008 // At least one of the operands should be a vector shuffle.
19009 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19010 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19013 MVT VT = LHS.getSimpleValueType();
19015 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19016 "Unsupported vector type for horizontal add/sub");
19018 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19019 // operate independently on 128-bit lanes.
19020 unsigned NumElts = VT.getVectorNumElements();
19021 unsigned NumLanes = VT.getSizeInBits()/128;
19022 unsigned NumLaneElts = NumElts / NumLanes;
19023 assert((NumLaneElts % 2 == 0) &&
19024 "Vector type should have an even number of elements in each lane");
19025 unsigned HalfLaneElts = NumLaneElts/2;
19027 // View LHS in the form
19028 // LHS = VECTOR_SHUFFLE A, B, LMask
19029 // If LHS is not a shuffle then pretend it is the shuffle
19030 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19031 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19034 SmallVector<int, 16> LMask(NumElts);
19035 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19036 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19037 A = LHS.getOperand(0);
19038 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19039 B = LHS.getOperand(1);
19040 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19041 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19043 if (LHS.getOpcode() != ISD::UNDEF)
19045 for (unsigned i = 0; i != NumElts; ++i)
19049 // Likewise, view RHS in the form
19050 // RHS = VECTOR_SHUFFLE C, D, RMask
19052 SmallVector<int, 16> RMask(NumElts);
19053 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19054 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19055 C = RHS.getOperand(0);
19056 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19057 D = RHS.getOperand(1);
19058 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19059 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19061 if (RHS.getOpcode() != ISD::UNDEF)
19063 for (unsigned i = 0; i != NumElts; ++i)
19067 // Check that the shuffles are both shuffling the same vectors.
19068 if (!(A == C && B == D) && !(A == D && B == C))
19071 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19072 if (!A.getNode() && !B.getNode())
19075 // If A and B occur in reverse order in RHS, then "swap" them (which means
19076 // rewriting the mask).
19078 CommuteVectorShuffleMask(RMask, NumElts);
19080 // At this point LHS and RHS are equivalent to
19081 // LHS = VECTOR_SHUFFLE A, B, LMask
19082 // RHS = VECTOR_SHUFFLE A, B, RMask
19083 // Check that the masks correspond to performing a horizontal operation.
19084 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19085 for (unsigned i = 0; i != NumLaneElts; ++i) {
19086 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19088 // Ignore any UNDEF components.
19089 if (LIdx < 0 || RIdx < 0 ||
19090 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19091 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19094 // Check that successive elements are being operated on. If not, this is
19095 // not a horizontal operation.
19096 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19097 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19098 if (!(LIdx == Index && RIdx == Index + 1) &&
19099 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19104 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19105 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19109 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19110 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19111 const X86Subtarget *Subtarget) {
19112 EVT VT = N->getValueType(0);
19113 SDValue LHS = N->getOperand(0);
19114 SDValue RHS = N->getOperand(1);
19116 // Try to synthesize horizontal adds from adds of shuffles.
19117 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19118 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19119 isHorizontalBinOp(LHS, RHS, true))
19120 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19124 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19125 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19126 const X86Subtarget *Subtarget) {
19127 EVT VT = N->getValueType(0);
19128 SDValue LHS = N->getOperand(0);
19129 SDValue RHS = N->getOperand(1);
19131 // Try to synthesize horizontal subs from subs of shuffles.
19132 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19133 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19134 isHorizontalBinOp(LHS, RHS, false))
19135 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19139 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19140 /// X86ISD::FXOR nodes.
19141 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19142 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19143 // F[X]OR(0.0, x) -> x
19144 // F[X]OR(x, 0.0) -> x
19145 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19146 if (C->getValueAPF().isPosZero())
19147 return N->getOperand(1);
19148 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19149 if (C->getValueAPF().isPosZero())
19150 return N->getOperand(0);
19154 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19155 /// X86ISD::FMAX nodes.
19156 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19157 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19159 // Only perform optimizations if UnsafeMath is used.
19160 if (!DAG.getTarget().Options.UnsafeFPMath)
19163 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19164 // into FMINC and FMAXC, which are Commutative operations.
19165 unsigned NewOp = 0;
19166 switch (N->getOpcode()) {
19167 default: llvm_unreachable("unknown opcode");
19168 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19169 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19172 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19173 N->getOperand(0), N->getOperand(1));
19176 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19177 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19178 // FAND(0.0, x) -> 0.0
19179 // FAND(x, 0.0) -> 0.0
19180 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19181 if (C->getValueAPF().isPosZero())
19182 return N->getOperand(0);
19183 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19184 if (C->getValueAPF().isPosZero())
19185 return N->getOperand(1);
19189 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19190 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19191 // FANDN(x, 0.0) -> 0.0
19192 // FANDN(0.0, x) -> x
19193 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19194 if (C->getValueAPF().isPosZero())
19195 return N->getOperand(1);
19196 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19197 if (C->getValueAPF().isPosZero())
19198 return N->getOperand(1);
19202 static SDValue PerformBTCombine(SDNode *N,
19204 TargetLowering::DAGCombinerInfo &DCI) {
19205 // BT ignores high bits in the bit index operand.
19206 SDValue Op1 = N->getOperand(1);
19207 if (Op1.hasOneUse()) {
19208 unsigned BitWidth = Op1.getValueSizeInBits();
19209 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19210 APInt KnownZero, KnownOne;
19211 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19212 !DCI.isBeforeLegalizeOps());
19213 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19214 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19215 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19216 DCI.CommitTargetLoweringOpt(TLO);
19221 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19222 SDValue Op = N->getOperand(0);
19223 if (Op.getOpcode() == ISD::BITCAST)
19224 Op = Op.getOperand(0);
19225 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19226 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19227 VT.getVectorElementType().getSizeInBits() ==
19228 OpVT.getVectorElementType().getSizeInBits()) {
19229 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19234 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19235 const X86Subtarget *Subtarget) {
19236 EVT VT = N->getValueType(0);
19237 if (!VT.isVector())
19240 SDValue N0 = N->getOperand(0);
19241 SDValue N1 = N->getOperand(1);
19242 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19245 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19246 // both SSE and AVX2 since there is no sign-extended shift right
19247 // operation on a vector with 64-bit elements.
19248 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19249 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19250 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19251 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19252 SDValue N00 = N0.getOperand(0);
19254 // EXTLOAD has a better solution on AVX2,
19255 // it may be replaced with X86ISD::VSEXT node.
19256 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19257 if (!ISD::isNormalLoad(N00.getNode()))
19260 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19261 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19263 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19269 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19270 TargetLowering::DAGCombinerInfo &DCI,
19271 const X86Subtarget *Subtarget) {
19272 if (!DCI.isBeforeLegalizeOps())
19275 if (!Subtarget->hasFp256())
19278 EVT VT = N->getValueType(0);
19279 if (VT.isVector() && VT.getSizeInBits() == 256) {
19280 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19288 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19289 const X86Subtarget* Subtarget) {
19291 EVT VT = N->getValueType(0);
19293 // Let legalize expand this if it isn't a legal type yet.
19294 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19297 EVT ScalarVT = VT.getScalarType();
19298 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19299 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19302 SDValue A = N->getOperand(0);
19303 SDValue B = N->getOperand(1);
19304 SDValue C = N->getOperand(2);
19306 bool NegA = (A.getOpcode() == ISD::FNEG);
19307 bool NegB = (B.getOpcode() == ISD::FNEG);
19308 bool NegC = (C.getOpcode() == ISD::FNEG);
19310 // Negative multiplication when NegA xor NegB
19311 bool NegMul = (NegA != NegB);
19313 A = A.getOperand(0);
19315 B = B.getOperand(0);
19317 C = C.getOperand(0);
19321 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19323 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19325 return DAG.getNode(Opcode, dl, VT, A, B, C);
19328 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19329 TargetLowering::DAGCombinerInfo &DCI,
19330 const X86Subtarget *Subtarget) {
19331 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19332 // (and (i32 x86isd::setcc_carry), 1)
19333 // This eliminates the zext. This transformation is necessary because
19334 // ISD::SETCC is always legalized to i8.
19336 SDValue N0 = N->getOperand(0);
19337 EVT VT = N->getValueType(0);
19339 if (N0.getOpcode() == ISD::AND &&
19341 N0.getOperand(0).hasOneUse()) {
19342 SDValue N00 = N0.getOperand(0);
19343 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19344 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19345 if (!C || C->getZExtValue() != 1)
19347 return DAG.getNode(ISD::AND, dl, VT,
19348 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19349 N00.getOperand(0), N00.getOperand(1)),
19350 DAG.getConstant(1, VT));
19354 if (N0.getOpcode() == ISD::TRUNCATE &&
19356 N0.getOperand(0).hasOneUse()) {
19357 SDValue N00 = N0.getOperand(0);
19358 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19359 return DAG.getNode(ISD::AND, dl, VT,
19360 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19361 N00.getOperand(0), N00.getOperand(1)),
19362 DAG.getConstant(1, VT));
19365 if (VT.is256BitVector()) {
19366 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19374 // Optimize x == -y --> x+y == 0
19375 // x != -y --> x+y != 0
19376 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19377 const X86Subtarget* Subtarget) {
19378 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19379 SDValue LHS = N->getOperand(0);
19380 SDValue RHS = N->getOperand(1);
19381 EVT VT = N->getValueType(0);
19384 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19385 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19386 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19387 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19388 LHS.getValueType(), RHS, LHS.getOperand(1));
19389 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19390 addV, DAG.getConstant(0, addV.getValueType()), CC);
19392 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19393 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19394 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19395 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19396 RHS.getValueType(), LHS, RHS.getOperand(1));
19397 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19398 addV, DAG.getConstant(0, addV.getValueType()), CC);
19401 if (VT.getScalarType() == MVT::i1) {
19402 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19403 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19404 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19405 if (!IsSEXT0 && !IsVZero0)
19407 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19408 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19409 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19411 if (!IsSEXT1 && !IsVZero1)
19414 if (IsSEXT0 && IsVZero1) {
19415 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19416 if (CC == ISD::SETEQ)
19417 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19418 return LHS.getOperand(0);
19420 if (IsSEXT1 && IsVZero0) {
19421 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19422 if (CC == ISD::SETEQ)
19423 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19424 return RHS.getOperand(0);
19431 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19432 // as "sbb reg,reg", since it can be extended without zext and produces
19433 // an all-ones bit which is more useful than 0/1 in some cases.
19434 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19437 return DAG.getNode(ISD::AND, DL, VT,
19438 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19439 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19440 DAG.getConstant(1, VT));
19441 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19442 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19443 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19444 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19447 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19448 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19449 TargetLowering::DAGCombinerInfo &DCI,
19450 const X86Subtarget *Subtarget) {
19452 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19453 SDValue EFLAGS = N->getOperand(1);
19455 if (CC == X86::COND_A) {
19456 // Try to convert COND_A into COND_B in an attempt to facilitate
19457 // materializing "setb reg".
19459 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19460 // cannot take an immediate as its first operand.
19462 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19463 EFLAGS.getValueType().isInteger() &&
19464 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19465 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19466 EFLAGS.getNode()->getVTList(),
19467 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19468 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19469 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19473 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19474 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19476 if (CC == X86::COND_B)
19477 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19481 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19482 if (Flags.getNode()) {
19483 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19484 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19490 // Optimize branch condition evaluation.
19492 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19493 TargetLowering::DAGCombinerInfo &DCI,
19494 const X86Subtarget *Subtarget) {
19496 SDValue Chain = N->getOperand(0);
19497 SDValue Dest = N->getOperand(1);
19498 SDValue EFLAGS = N->getOperand(3);
19499 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19503 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19504 if (Flags.getNode()) {
19505 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19506 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19513 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19514 const X86TargetLowering *XTLI) {
19515 SDValue Op0 = N->getOperand(0);
19516 EVT InVT = Op0->getValueType(0);
19518 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19519 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19521 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19522 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19523 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19526 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19527 // a 32-bit target where SSE doesn't support i64->FP operations.
19528 if (Op0.getOpcode() == ISD::LOAD) {
19529 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19530 EVT VT = Ld->getValueType(0);
19531 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19532 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19533 !XTLI->getSubtarget()->is64Bit() &&
19535 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19536 Ld->getChain(), Op0, DAG);
19537 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19544 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19545 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19546 X86TargetLowering::DAGCombinerInfo &DCI) {
19547 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19548 // the result is either zero or one (depending on the input carry bit).
19549 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19550 if (X86::isZeroNode(N->getOperand(0)) &&
19551 X86::isZeroNode(N->getOperand(1)) &&
19552 // We don't have a good way to replace an EFLAGS use, so only do this when
19554 SDValue(N, 1).use_empty()) {
19556 EVT VT = N->getValueType(0);
19557 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19558 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19559 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19560 DAG.getConstant(X86::COND_B,MVT::i8),
19562 DAG.getConstant(1, VT));
19563 return DCI.CombineTo(N, Res1, CarryOut);
19569 // fold (add Y, (sete X, 0)) -> adc 0, Y
19570 // (add Y, (setne X, 0)) -> sbb -1, Y
19571 // (sub (sete X, 0), Y) -> sbb 0, Y
19572 // (sub (setne X, 0), Y) -> adc -1, Y
19573 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19576 // Look through ZExts.
19577 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19578 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19581 SDValue SetCC = Ext.getOperand(0);
19582 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19585 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19586 if (CC != X86::COND_E && CC != X86::COND_NE)
19589 SDValue Cmp = SetCC.getOperand(1);
19590 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19591 !X86::isZeroNode(Cmp.getOperand(1)) ||
19592 !Cmp.getOperand(0).getValueType().isInteger())
19595 SDValue CmpOp0 = Cmp.getOperand(0);
19596 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19597 DAG.getConstant(1, CmpOp0.getValueType()));
19599 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19600 if (CC == X86::COND_NE)
19601 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19602 DL, OtherVal.getValueType(), OtherVal,
19603 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19604 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19605 DL, OtherVal.getValueType(), OtherVal,
19606 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19609 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19610 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19611 const X86Subtarget *Subtarget) {
19612 EVT VT = N->getValueType(0);
19613 SDValue Op0 = N->getOperand(0);
19614 SDValue Op1 = N->getOperand(1);
19616 // Try to synthesize horizontal adds from adds of shuffles.
19617 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19618 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19619 isHorizontalBinOp(Op0, Op1, true))
19620 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19622 return OptimizeConditionalInDecrement(N, DAG);
19625 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19626 const X86Subtarget *Subtarget) {
19627 SDValue Op0 = N->getOperand(0);
19628 SDValue Op1 = N->getOperand(1);
19630 // X86 can't encode an immediate LHS of a sub. See if we can push the
19631 // negation into a preceding instruction.
19632 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19633 // If the RHS of the sub is a XOR with one use and a constant, invert the
19634 // immediate. Then add one to the LHS of the sub so we can turn
19635 // X-Y -> X+~Y+1, saving one register.
19636 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19637 isa<ConstantSDNode>(Op1.getOperand(1))) {
19638 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19639 EVT VT = Op0.getValueType();
19640 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19642 DAG.getConstant(~XorC, VT));
19643 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19644 DAG.getConstant(C->getAPIntValue()+1, VT));
19648 // Try to synthesize horizontal adds from adds of shuffles.
19649 EVT VT = N->getValueType(0);
19650 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19651 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19652 isHorizontalBinOp(Op0, Op1, true))
19653 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19655 return OptimizeConditionalInDecrement(N, DAG);
19658 /// performVZEXTCombine - Performs build vector combines
19659 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19660 TargetLowering::DAGCombinerInfo &DCI,
19661 const X86Subtarget *Subtarget) {
19662 // (vzext (bitcast (vzext (x)) -> (vzext x)
19663 SDValue In = N->getOperand(0);
19664 while (In.getOpcode() == ISD::BITCAST)
19665 In = In.getOperand(0);
19667 if (In.getOpcode() != X86ISD::VZEXT)
19670 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19674 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19675 DAGCombinerInfo &DCI) const {
19676 SelectionDAG &DAG = DCI.DAG;
19677 switch (N->getOpcode()) {
19679 case ISD::EXTRACT_VECTOR_ELT:
19680 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19682 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19683 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19684 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
19685 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
19686 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
19687 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
19690 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
19691 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
19692 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
19693 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
19694 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
19695 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
19696 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
19697 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
19698 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
19700 case X86ISD::FOR: return PerformFORCombine(N, DAG);
19702 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
19703 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
19704 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
19705 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
19706 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
19707 case ISD::ANY_EXTEND:
19708 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
19709 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
19710 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19711 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19712 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
19713 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19714 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19715 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
19716 case X86ISD::SHUFP: // Handle all target specific shuffles
19717 case X86ISD::PALIGNR:
19718 case X86ISD::UNPCKH:
19719 case X86ISD::UNPCKL:
19720 case X86ISD::MOVHLPS:
19721 case X86ISD::MOVLHPS:
19722 case X86ISD::PSHUFD:
19723 case X86ISD::PSHUFHW:
19724 case X86ISD::PSHUFLW:
19725 case X86ISD::MOVSS:
19726 case X86ISD::MOVSD:
19727 case X86ISD::VPERMILP:
19728 case X86ISD::VPERM2X128:
19729 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19730 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
19736 /// isTypeDesirableForOp - Return true if the target has native support for
19737 /// the specified value type and it is 'desirable' to use the type for the
19738 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19739 /// instruction encodings are longer and some i16 instructions are slow.
19740 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19741 if (!isTypeLegal(VT))
19743 if (VT != MVT::i16)
19750 case ISD::SIGN_EXTEND:
19751 case ISD::ZERO_EXTEND:
19752 case ISD::ANY_EXTEND:
19765 /// IsDesirableToPromoteOp - This method query the target whether it is
19766 /// beneficial for dag combiner to promote the specified node. If true, it
19767 /// should return the desired promotion type by reference.
19768 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19769 EVT VT = Op.getValueType();
19770 if (VT != MVT::i16)
19773 bool Promote = false;
19774 bool Commute = false;
19775 switch (Op.getOpcode()) {
19778 LoadSDNode *LD = cast<LoadSDNode>(Op);
19779 // If the non-extending load has a single use and it's not live out, then it
19780 // might be folded.
19781 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19782 Op.hasOneUse()*/) {
19783 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19784 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19785 // The only case where we'd want to promote LOAD (rather then it being
19786 // promoted as an operand is when it's only use is liveout.
19787 if (UI->getOpcode() != ISD::CopyToReg)
19794 case ISD::SIGN_EXTEND:
19795 case ISD::ZERO_EXTEND:
19796 case ISD::ANY_EXTEND:
19801 SDValue N0 = Op.getOperand(0);
19802 // Look out for (store (shl (load), x)).
19803 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19816 SDValue N0 = Op.getOperand(0);
19817 SDValue N1 = Op.getOperand(1);
19818 if (!Commute && MayFoldLoad(N1))
19820 // Avoid disabling potential load folding opportunities.
19821 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19823 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19833 //===----------------------------------------------------------------------===//
19834 // X86 Inline Assembly Support
19835 //===----------------------------------------------------------------------===//
19838 // Helper to match a string separated by whitespace.
19839 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19840 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19842 for (unsigned i = 0, e = args.size(); i != e; ++i) {
19843 StringRef piece(*args[i]);
19844 if (!s.startswith(piece)) // Check if the piece matches.
19847 s = s.substr(piece.size());
19848 StringRef::size_type pos = s.find_first_not_of(" \t");
19849 if (pos == 0) // We matched a prefix.
19857 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19860 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19862 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19863 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19864 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19865 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19867 if (AsmPieces.size() == 3)
19869 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19876 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19877 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19879 std::string AsmStr = IA->getAsmString();
19881 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19882 if (!Ty || Ty->getBitWidth() % 16 != 0)
19885 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19886 SmallVector<StringRef, 4> AsmPieces;
19887 SplitString(AsmStr, AsmPieces, ";\n");
19889 switch (AsmPieces.size()) {
19890 default: return false;
19892 // FIXME: this should verify that we are targeting a 486 or better. If not,
19893 // we will turn this bswap into something that will be lowered to logical
19894 // ops instead of emitting the bswap asm. For now, we don't support 486 or
19895 // lower so don't worry about this.
19897 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19898 matchAsm(AsmPieces[0], "bswapl", "$0") ||
19899 matchAsm(AsmPieces[0], "bswapq", "$0") ||
19900 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19901 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19902 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19903 // No need to check constraints, nothing other than the equivalent of
19904 // "=r,0" would be valid here.
19905 return IntrinsicLowering::LowerToByteSwap(CI);
19908 // rorw $$8, ${0:w} --> llvm.bswap.i16
19909 if (CI->getType()->isIntegerTy(16) &&
19910 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19911 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19912 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19914 const std::string &ConstraintsStr = IA->getConstraintString();
19915 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19916 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19917 if (clobbersFlagRegisters(AsmPieces))
19918 return IntrinsicLowering::LowerToByteSwap(CI);
19922 if (CI->getType()->isIntegerTy(32) &&
19923 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19924 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19925 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19926 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19928 const std::string &ConstraintsStr = IA->getConstraintString();
19929 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19930 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19931 if (clobbersFlagRegisters(AsmPieces))
19932 return IntrinsicLowering::LowerToByteSwap(CI);
19935 if (CI->getType()->isIntegerTy(64)) {
19936 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19937 if (Constraints.size() >= 2 &&
19938 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19939 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19940 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
19941 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19942 matchAsm(AsmPieces[1], "bswap", "%edx") &&
19943 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19944 return IntrinsicLowering::LowerToByteSwap(CI);
19952 /// getConstraintType - Given a constraint letter, return the type of
19953 /// constraint it is for this target.
19954 X86TargetLowering::ConstraintType
19955 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19956 if (Constraint.size() == 1) {
19957 switch (Constraint[0]) {
19968 return C_RegisterClass;
19992 return TargetLowering::getConstraintType(Constraint);
19995 /// Examine constraint type and operand type and determine a weight value.
19996 /// This object must already have been set up with the operand type
19997 /// and the current alternative constraint selected.
19998 TargetLowering::ConstraintWeight
19999 X86TargetLowering::getSingleConstraintMatchWeight(
20000 AsmOperandInfo &info, const char *constraint) const {
20001 ConstraintWeight weight = CW_Invalid;
20002 Value *CallOperandVal = info.CallOperandVal;
20003 // If we don't have a value, we can't do a match,
20004 // but allow it at the lowest weight.
20005 if (CallOperandVal == NULL)
20007 Type *type = CallOperandVal->getType();
20008 // Look at the constraint type.
20009 switch (*constraint) {
20011 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20022 if (CallOperandVal->getType()->isIntegerTy())
20023 weight = CW_SpecificReg;
20028 if (type->isFloatingPointTy())
20029 weight = CW_SpecificReg;
20032 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20033 weight = CW_SpecificReg;
20037 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20038 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20039 weight = CW_Register;
20042 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20043 if (C->getZExtValue() <= 31)
20044 weight = CW_Constant;
20048 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20049 if (C->getZExtValue() <= 63)
20050 weight = CW_Constant;
20054 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20055 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20056 weight = CW_Constant;
20060 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20061 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20062 weight = CW_Constant;
20066 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20067 if (C->getZExtValue() <= 3)
20068 weight = CW_Constant;
20072 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20073 if (C->getZExtValue() <= 0xff)
20074 weight = CW_Constant;
20079 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20080 weight = CW_Constant;
20084 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20085 if ((C->getSExtValue() >= -0x80000000LL) &&
20086 (C->getSExtValue() <= 0x7fffffffLL))
20087 weight = CW_Constant;
20091 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20092 if (C->getZExtValue() <= 0xffffffff)
20093 weight = CW_Constant;
20100 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20101 /// with another that has more specific requirements based on the type of the
20102 /// corresponding operand.
20103 const char *X86TargetLowering::
20104 LowerXConstraint(EVT ConstraintVT) const {
20105 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20106 // 'f' like normal targets.
20107 if (ConstraintVT.isFloatingPoint()) {
20108 if (Subtarget->hasSSE2())
20110 if (Subtarget->hasSSE1())
20114 return TargetLowering::LowerXConstraint(ConstraintVT);
20117 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20118 /// vector. If it is invalid, don't add anything to Ops.
20119 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20120 std::string &Constraint,
20121 std::vector<SDValue>&Ops,
20122 SelectionDAG &DAG) const {
20123 SDValue Result(0, 0);
20125 // Only support length 1 constraints for now.
20126 if (Constraint.length() > 1) return;
20128 char ConstraintLetter = Constraint[0];
20129 switch (ConstraintLetter) {
20132 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20133 if (C->getZExtValue() <= 31) {
20134 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20141 if (C->getZExtValue() <= 63) {
20142 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20148 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20149 if (isInt<8>(C->getSExtValue())) {
20150 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20156 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20157 if (C->getZExtValue() <= 255) {
20158 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20164 // 32-bit signed value
20165 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20166 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20167 C->getSExtValue())) {
20168 // Widen to 64 bits here to get it sign extended.
20169 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20172 // FIXME gcc accepts some relocatable values here too, but only in certain
20173 // memory models; it's complicated.
20178 // 32-bit unsigned value
20179 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20180 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20181 C->getZExtValue())) {
20182 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20186 // FIXME gcc accepts some relocatable values here too, but only in certain
20187 // memory models; it's complicated.
20191 // Literal immediates are always ok.
20192 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20193 // Widen to 64 bits here to get it sign extended.
20194 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20198 // In any sort of PIC mode addresses need to be computed at runtime by
20199 // adding in a register or some sort of table lookup. These can't
20200 // be used as immediates.
20201 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20204 // If we are in non-pic codegen mode, we allow the address of a global (with
20205 // an optional displacement) to be used with 'i'.
20206 GlobalAddressSDNode *GA = 0;
20207 int64_t Offset = 0;
20209 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20211 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20212 Offset += GA->getOffset();
20214 } else if (Op.getOpcode() == ISD::ADD) {
20215 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20216 Offset += C->getZExtValue();
20217 Op = Op.getOperand(0);
20220 } else if (Op.getOpcode() == ISD::SUB) {
20221 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20222 Offset += -C->getZExtValue();
20223 Op = Op.getOperand(0);
20228 // Otherwise, this isn't something we can handle, reject it.
20232 const GlobalValue *GV = GA->getGlobal();
20233 // If we require an extra load to get this address, as in PIC mode, we
20234 // can't accept it.
20235 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20236 getTargetMachine())))
20239 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20240 GA->getValueType(0), Offset);
20245 if (Result.getNode()) {
20246 Ops.push_back(Result);
20249 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20252 std::pair<unsigned, const TargetRegisterClass*>
20253 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20255 // First, see if this is a constraint that directly corresponds to an LLVM
20257 if (Constraint.size() == 1) {
20258 // GCC Constraint Letters
20259 switch (Constraint[0]) {
20261 // TODO: Slight differences here in allocation order and leaving
20262 // RIP in the class. Do they matter any more here than they do
20263 // in the normal allocation?
20264 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20265 if (Subtarget->is64Bit()) {
20266 if (VT == MVT::i32 || VT == MVT::f32)
20267 return std::make_pair(0U, &X86::GR32RegClass);
20268 if (VT == MVT::i16)
20269 return std::make_pair(0U, &X86::GR16RegClass);
20270 if (VT == MVT::i8 || VT == MVT::i1)
20271 return std::make_pair(0U, &X86::GR8RegClass);
20272 if (VT == MVT::i64 || VT == MVT::f64)
20273 return std::make_pair(0U, &X86::GR64RegClass);
20276 // 32-bit fallthrough
20277 case 'Q': // Q_REGS
20278 if (VT == MVT::i32 || VT == MVT::f32)
20279 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20280 if (VT == MVT::i16)
20281 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20282 if (VT == MVT::i8 || VT == MVT::i1)
20283 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20284 if (VT == MVT::i64)
20285 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20287 case 'r': // GENERAL_REGS
20288 case 'l': // INDEX_REGS
20289 if (VT == MVT::i8 || VT == MVT::i1)
20290 return std::make_pair(0U, &X86::GR8RegClass);
20291 if (VT == MVT::i16)
20292 return std::make_pair(0U, &X86::GR16RegClass);
20293 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20294 return std::make_pair(0U, &X86::GR32RegClass);
20295 return std::make_pair(0U, &X86::GR64RegClass);
20296 case 'R': // LEGACY_REGS
20297 if (VT == MVT::i8 || VT == MVT::i1)
20298 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20299 if (VT == MVT::i16)
20300 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20301 if (VT == MVT::i32 || !Subtarget->is64Bit())
20302 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20303 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20304 case 'f': // FP Stack registers.
20305 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20306 // value to the correct fpstack register class.
20307 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20308 return std::make_pair(0U, &X86::RFP32RegClass);
20309 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20310 return std::make_pair(0U, &X86::RFP64RegClass);
20311 return std::make_pair(0U, &X86::RFP80RegClass);
20312 case 'y': // MMX_REGS if MMX allowed.
20313 if (!Subtarget->hasMMX()) break;
20314 return std::make_pair(0U, &X86::VR64RegClass);
20315 case 'Y': // SSE_REGS if SSE2 allowed
20316 if (!Subtarget->hasSSE2()) break;
20318 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20319 if (!Subtarget->hasSSE1()) break;
20321 switch (VT.SimpleTy) {
20323 // Scalar SSE types.
20326 return std::make_pair(0U, &X86::FR32RegClass);
20329 return std::make_pair(0U, &X86::FR64RegClass);
20337 return std::make_pair(0U, &X86::VR128RegClass);
20345 return std::make_pair(0U, &X86::VR256RegClass);
20350 return std::make_pair(0U, &X86::VR512RegClass);
20356 // Use the default implementation in TargetLowering to convert the register
20357 // constraint into a member of a register class.
20358 std::pair<unsigned, const TargetRegisterClass*> Res;
20359 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20361 // Not found as a standard register?
20362 if (Res.second == 0) {
20363 // Map st(0) -> st(7) -> ST0
20364 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20365 tolower(Constraint[1]) == 's' &&
20366 tolower(Constraint[2]) == 't' &&
20367 Constraint[3] == '(' &&
20368 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20369 Constraint[5] == ')' &&
20370 Constraint[6] == '}') {
20372 Res.first = X86::ST0+Constraint[4]-'0';
20373 Res.second = &X86::RFP80RegClass;
20377 // GCC allows "st(0)" to be called just plain "st".
20378 if (StringRef("{st}").equals_lower(Constraint)) {
20379 Res.first = X86::ST0;
20380 Res.second = &X86::RFP80RegClass;
20385 if (StringRef("{flags}").equals_lower(Constraint)) {
20386 Res.first = X86::EFLAGS;
20387 Res.second = &X86::CCRRegClass;
20391 // 'A' means EAX + EDX.
20392 if (Constraint == "A") {
20393 Res.first = X86::EAX;
20394 Res.second = &X86::GR32_ADRegClass;
20400 // Otherwise, check to see if this is a register class of the wrong value
20401 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20402 // turn into {ax},{dx}.
20403 if (Res.second->hasType(VT))
20404 return Res; // Correct type already, nothing to do.
20406 // All of the single-register GCC register classes map their values onto
20407 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20408 // really want an 8-bit or 32-bit register, map to the appropriate register
20409 // class and return the appropriate register.
20410 if (Res.second == &X86::GR16RegClass) {
20411 if (VT == MVT::i8 || VT == MVT::i1) {
20412 unsigned DestReg = 0;
20413 switch (Res.first) {
20415 case X86::AX: DestReg = X86::AL; break;
20416 case X86::DX: DestReg = X86::DL; break;
20417 case X86::CX: DestReg = X86::CL; break;
20418 case X86::BX: DestReg = X86::BL; break;
20421 Res.first = DestReg;
20422 Res.second = &X86::GR8RegClass;
20424 } else if (VT == MVT::i32 || VT == MVT::f32) {
20425 unsigned DestReg = 0;
20426 switch (Res.first) {
20428 case X86::AX: DestReg = X86::EAX; break;
20429 case X86::DX: DestReg = X86::EDX; break;
20430 case X86::CX: DestReg = X86::ECX; break;
20431 case X86::BX: DestReg = X86::EBX; break;
20432 case X86::SI: DestReg = X86::ESI; break;
20433 case X86::DI: DestReg = X86::EDI; break;
20434 case X86::BP: DestReg = X86::EBP; break;
20435 case X86::SP: DestReg = X86::ESP; break;
20438 Res.first = DestReg;
20439 Res.second = &X86::GR32RegClass;
20441 } else if (VT == MVT::i64 || VT == MVT::f64) {
20442 unsigned DestReg = 0;
20443 switch (Res.first) {
20445 case X86::AX: DestReg = X86::RAX; break;
20446 case X86::DX: DestReg = X86::RDX; break;
20447 case X86::CX: DestReg = X86::RCX; break;
20448 case X86::BX: DestReg = X86::RBX; break;
20449 case X86::SI: DestReg = X86::RSI; break;
20450 case X86::DI: DestReg = X86::RDI; break;
20451 case X86::BP: DestReg = X86::RBP; break;
20452 case X86::SP: DestReg = X86::RSP; break;
20455 Res.first = DestReg;
20456 Res.second = &X86::GR64RegClass;
20459 } else if (Res.second == &X86::FR32RegClass ||
20460 Res.second == &X86::FR64RegClass ||
20461 Res.second == &X86::VR128RegClass ||
20462 Res.second == &X86::VR256RegClass ||
20463 Res.second == &X86::FR32XRegClass ||
20464 Res.second == &X86::FR64XRegClass ||
20465 Res.second == &X86::VR128XRegClass ||
20466 Res.second == &X86::VR256XRegClass ||
20467 Res.second == &X86::VR512RegClass) {
20468 // Handle references to XMM physical registers that got mapped into the
20469 // wrong class. This can happen with constraints like {xmm0} where the
20470 // target independent register mapper will just pick the first match it can
20471 // find, ignoring the required type.
20473 if (VT == MVT::f32 || VT == MVT::i32)
20474 Res.second = &X86::FR32RegClass;
20475 else if (VT == MVT::f64 || VT == MVT::i64)
20476 Res.second = &X86::FR64RegClass;
20477 else if (X86::VR128RegClass.hasType(VT))
20478 Res.second = &X86::VR128RegClass;
20479 else if (X86::VR256RegClass.hasType(VT))
20480 Res.second = &X86::VR256RegClass;
20481 else if (X86::VR512RegClass.hasType(VT))
20482 Res.second = &X86::VR512RegClass;