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->isTargetWindows())
193 return new X86WindowsTargetObjectFile();
194 if (Subtarget->isTargetCOFF())
195 return new TargetLoweringObjectFileCOFF();
196 llvm_unreachable("unknown subtarget type");
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200 : TargetLowering(TM, createTLOF(TM)) {
201 Subtarget = &TM.getSubtarget<X86Subtarget>();
202 X86ScalarSSEf64 = Subtarget->hasSSE2();
203 X86ScalarSSEf32 = Subtarget->hasSSE1();
204 TD = getDataLayout();
206 resetOperationActions();
209 void X86TargetLowering::resetOperationActions() {
210 const TargetMachine &TM = getTargetMachine();
211 static bool FirstTimeThrough = true;
213 // If none of the target options have changed, then we don't need to reset the
214 // operation actions.
215 if (!FirstTimeThrough && TO == TM.Options) return;
217 if (!FirstTimeThrough) {
218 // Reinitialize the actions.
220 FirstTimeThrough = false;
225 // Set up the TargetLowering object.
226 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
228 // X86 is weird, it always uses i8 for shift amounts and setcc results.
229 setBooleanContents(ZeroOrOneBooleanContent);
230 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
233 // For 64-bit since we have so many registers use the ILP scheduler, for
234 // 32-bit code use the register pressure specific scheduling.
235 // For Atom, always use ILP scheduling.
236 if (Subtarget->isAtom())
237 setSchedulingPreference(Sched::ILP);
238 else if (Subtarget->is64Bit())
239 setSchedulingPreference(Sched::ILP);
241 setSchedulingPreference(Sched::RegPressure);
242 const X86RegisterInfo *RegInfo =
243 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
244 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
246 // Bypass expensive divides on Atom when compiling with O2
247 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
248 addBypassSlowDiv(32, 8);
249 if (Subtarget->is64Bit())
250 addBypassSlowDiv(64, 16);
253 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
254 // Setup Windows compiler runtime calls.
255 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
256 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
257 setLibcallName(RTLIB::SREM_I64, "_allrem");
258 setLibcallName(RTLIB::UREM_I64, "_aullrem");
259 setLibcallName(RTLIB::MUL_I64, "_allmul");
260 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
261 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266 // The _ftol2 runtime function has an unusual calling conv, which
267 // is modeled by a special pseudo-instruction.
268 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
269 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
270 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
271 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
274 if (Subtarget->isTargetDarwin()) {
275 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
276 setUseUnderscoreSetJmp(false);
277 setUseUnderscoreLongJmp(false);
278 } else if (Subtarget->isTargetMingw()) {
279 // MS runtime is weird: it exports _setjmp, but longjmp!
280 setUseUnderscoreSetJmp(true);
281 setUseUnderscoreLongJmp(false);
283 setUseUnderscoreSetJmp(true);
284 setUseUnderscoreLongJmp(true);
287 // Set up the register classes.
288 addRegisterClass(MVT::i8, &X86::GR8RegClass);
289 addRegisterClass(MVT::i16, &X86::GR16RegClass);
290 addRegisterClass(MVT::i32, &X86::GR32RegClass);
291 if (Subtarget->is64Bit())
292 addRegisterClass(MVT::i64, &X86::GR64RegClass);
294 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296 // We don't accept any truncstore of integer registers.
297 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
304 // SETOEQ and SETUNE require checking two conditions.
305 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
312 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
314 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
315 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
316 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
318 if (Subtarget->is64Bit()) {
319 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
320 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
321 } else if (!TM.Options.UseSoftFloat) {
322 // We have an algorithm for SSE2->double, and we turn this into a
323 // 64-bit FILD followed by conditional FADD for other targets.
324 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
325 // We have an algorithm for SSE2, and we turn this into a 64-bit
326 // FILD for other targets.
327 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
330 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
332 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
333 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
335 if (!TM.Options.UseSoftFloat) {
336 // SSE has no i16 to fp conversion, only i32
337 if (X86ScalarSSEf32) {
338 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
339 // f32 and f64 cases are Legal, f80 case is not
340 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
342 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
343 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
346 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
347 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
350 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
351 // are Legal, f80 is custom lowered.
352 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
353 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
355 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
357 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
358 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
360 if (X86ScalarSSEf32) {
361 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
362 // f32 and f64 cases are Legal, f80 case is not
363 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
365 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
366 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
369 // Handle FP_TO_UINT by promoting the destination to a larger signed
371 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
372 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
373 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
375 if (Subtarget->is64Bit()) {
376 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
377 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
378 } else if (!TM.Options.UseSoftFloat) {
379 // Since AVX is a superset of SSE3, only check for SSE here.
380 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381 // Expand FP_TO_UINT into a select.
382 // FIXME: We would like to use a Custom expander here eventually to do
383 // the optimal thing for SSE vs. the default expansion in the legalizer.
384 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
386 // With SSE3 we can use fisttpll to convert to a signed i64; without
387 // SSE, we're stuck with a fistpll.
388 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
391 if (isTargetFTOL()) {
392 // Use the _ftol2 runtime function, which has a pseudo-instruction
393 // to handle its weird calling convention.
394 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
397 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398 if (!X86ScalarSSEf64) {
399 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
400 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
401 if (Subtarget->is64Bit()) {
402 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
403 // Without SSE, i64->f64 goes through memory.
404 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
408 // Scalar integer divide and remainder are lowered to use operations that
409 // produce two results, to match the available instructions. This exposes
410 // the two-result form to trivial CSE, which is able to combine x/y and x%y
411 // into a single instruction.
413 // Scalar integer multiply-high is also lowered to use two-result
414 // operations, to match the available instructions. However, plain multiply
415 // (low) operations are left as Legal, as there are single-result
416 // instructions for this in x86. Using the two-result multiply instructions
417 // when both high and low results are needed must be arranged by dagcombine.
418 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
420 setOperationAction(ISD::MULHS, VT, Expand);
421 setOperationAction(ISD::MULHU, VT, Expand);
422 setOperationAction(ISD::SDIV, VT, Expand);
423 setOperationAction(ISD::UDIV, VT, Expand);
424 setOperationAction(ISD::SREM, VT, Expand);
425 setOperationAction(ISD::UREM, VT, Expand);
427 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428 setOperationAction(ISD::ADDC, VT, Custom);
429 setOperationAction(ISD::ADDE, VT, Custom);
430 setOperationAction(ISD::SUBC, VT, Custom);
431 setOperationAction(ISD::SUBE, VT, Custom);
434 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
435 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
436 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
437 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
438 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
439 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
443 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
444 if (Subtarget->is64Bit())
445 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
449 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
450 setOperationAction(ISD::FREM , MVT::f32 , Expand);
451 setOperationAction(ISD::FREM , MVT::f64 , Expand);
452 setOperationAction(ISD::FREM , MVT::f80 , Expand);
453 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
455 // Promote the i8 variants and force them on up to i32 which has a shorter
457 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
458 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
459 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
460 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
461 if (Subtarget->hasBMI()) {
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
464 if (Subtarget->is64Bit())
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
467 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
468 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
469 if (Subtarget->is64Bit())
470 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
473 if (Subtarget->hasLZCNT()) {
474 // When promoting the i8 variants, force them to i32 for a shorter
476 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
477 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
478 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
482 if (Subtarget->is64Bit())
483 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
485 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
486 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
487 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
491 if (Subtarget->is64Bit()) {
492 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
493 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
497 if (Subtarget->hasPOPCNT()) {
498 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
500 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
501 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
502 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
507 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
509 if (!Subtarget->hasMOVBE())
510 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
512 // These should be promoted to a larger select which is supported.
513 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
514 // X86 wants to expand cmov itself.
515 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
516 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
517 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
518 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
519 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
521 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
522 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
524 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
525 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
527 if (Subtarget->is64Bit()) {
528 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
529 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
531 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
532 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
533 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
534 // support continuation, user-level threading, and etc.. As a result, no
535 // other SjLj exception interfaces are implemented and please don't build
536 // your own exception handling based on them.
537 // LLVM/Clang supports zero-cost DWARF exception handling.
538 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
539 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
542 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
543 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
544 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
545 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
546 if (Subtarget->is64Bit())
547 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
548 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
549 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
550 if (Subtarget->is64Bit()) {
551 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
552 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
553 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
554 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
555 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
557 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
558 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
559 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
560 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
561 if (Subtarget->is64Bit()) {
562 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
563 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
564 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
567 if (Subtarget->hasSSE1())
568 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
570 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
572 // Expand certain atomics
573 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
575 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
576 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
577 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
580 if (!Subtarget->is64Bit()) {
581 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
582 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
595 if (Subtarget->hasCmpxchg16b()) {
596 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
599 // FIXME - use subtarget debug flags
600 if (!Subtarget->isTargetDarwin() &&
601 !Subtarget->isTargetELF() &&
602 !Subtarget->isTargetCygMing()) {
603 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
606 if (Subtarget->is64Bit()) {
607 setExceptionPointerRegister(X86::RAX);
608 setExceptionSelectorRegister(X86::RDX);
610 setExceptionPointerRegister(X86::EAX);
611 setExceptionSelectorRegister(X86::EDX);
613 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
614 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
616 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
617 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
619 setOperationAction(ISD::TRAP, MVT::Other, Legal);
620 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
622 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
623 setOperationAction(ISD::VASTART , MVT::Other, Custom);
624 setOperationAction(ISD::VAEND , MVT::Other, Expand);
625 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
626 // TargetInfo::X86_64ABIBuiltinVaList
627 setOperationAction(ISD::VAARG , MVT::Other, Custom);
628 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
630 // TargetInfo::CharPtrBuiltinVaList
631 setOperationAction(ISD::VAARG , MVT::Other, Expand);
632 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
635 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
636 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
638 if (Subtarget->isOSWindows() && !Subtarget->isTargetMacho())
639 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640 MVT::i64 : MVT::i32, Custom);
641 else if (TM.Options.EnableSegmentedStacks)
642 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
643 MVT::i64 : MVT::i32, Custom);
645 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
646 MVT::i64 : MVT::i32, Expand);
648 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
649 // f32 and f64 use SSE.
650 // Set up the FP register classes.
651 addRegisterClass(MVT::f32, &X86::FR32RegClass);
652 addRegisterClass(MVT::f64, &X86::FR64RegClass);
654 // Use ANDPD to simulate FABS.
655 setOperationAction(ISD::FABS , MVT::f64, Custom);
656 setOperationAction(ISD::FABS , MVT::f32, Custom);
658 // Use XORP to simulate FNEG.
659 setOperationAction(ISD::FNEG , MVT::f64, Custom);
660 setOperationAction(ISD::FNEG , MVT::f32, Custom);
662 // Use ANDPD and ORPD to simulate FCOPYSIGN.
663 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
664 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
666 // Lower this to FGETSIGNx86 plus an AND.
667 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
668 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
670 // We don't support sin/cos/fmod
671 setOperationAction(ISD::FSIN , MVT::f64, Expand);
672 setOperationAction(ISD::FCOS , MVT::f64, Expand);
673 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
674 setOperationAction(ISD::FSIN , MVT::f32, Expand);
675 setOperationAction(ISD::FCOS , MVT::f32, Expand);
676 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
678 // Expand FP immediates into loads from the stack, except for the special
680 addLegalFPImmediate(APFloat(+0.0)); // xorpd
681 addLegalFPImmediate(APFloat(+0.0f)); // xorps
682 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
683 // Use SSE for f32, x87 for f64.
684 // Set up the FP register classes.
685 addRegisterClass(MVT::f32, &X86::FR32RegClass);
686 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
688 // Use ANDPS to simulate FABS.
689 setOperationAction(ISD::FABS , MVT::f32, Custom);
691 // Use XORP to simulate FNEG.
692 setOperationAction(ISD::FNEG , MVT::f32, Custom);
694 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
696 // Use ANDPS and ORPS to simulate FCOPYSIGN.
697 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
698 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
700 // We don't support sin/cos/fmod
701 setOperationAction(ISD::FSIN , MVT::f32, Expand);
702 setOperationAction(ISD::FCOS , MVT::f32, Expand);
703 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
705 // Special cases we handle for FP constants.
706 addLegalFPImmediate(APFloat(+0.0f)); // xorps
707 addLegalFPImmediate(APFloat(+0.0)); // FLD0
708 addLegalFPImmediate(APFloat(+1.0)); // FLD1
709 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
710 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
712 if (!TM.Options.UnsafeFPMath) {
713 setOperationAction(ISD::FSIN , MVT::f64, Expand);
714 setOperationAction(ISD::FCOS , MVT::f64, Expand);
715 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
717 } else if (!TM.Options.UseSoftFloat) {
718 // f32 and f64 in x87.
719 // Set up the FP register classes.
720 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
721 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
723 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
724 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
725 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
726 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
728 if (!TM.Options.UnsafeFPMath) {
729 setOperationAction(ISD::FSIN , MVT::f64, Expand);
730 setOperationAction(ISD::FSIN , MVT::f32, Expand);
731 setOperationAction(ISD::FCOS , MVT::f64, Expand);
732 setOperationAction(ISD::FCOS , MVT::f32, Expand);
733 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
734 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
736 addLegalFPImmediate(APFloat(+0.0)); // FLD0
737 addLegalFPImmediate(APFloat(+1.0)); // FLD1
738 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
739 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
740 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
741 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
742 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
743 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
746 // We don't support FMA.
747 setOperationAction(ISD::FMA, MVT::f64, Expand);
748 setOperationAction(ISD::FMA, MVT::f32, Expand);
750 // Long double always uses X87.
751 if (!TM.Options.UseSoftFloat) {
752 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
753 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
754 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
756 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
757 addLegalFPImmediate(TmpFlt); // FLD0
759 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
762 APFloat TmpFlt2(+1.0);
763 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
765 addLegalFPImmediate(TmpFlt2); // FLD1
766 TmpFlt2.changeSign();
767 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
770 if (!TM.Options.UnsafeFPMath) {
771 setOperationAction(ISD::FSIN , MVT::f80, Expand);
772 setOperationAction(ISD::FCOS , MVT::f80, Expand);
773 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
776 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
777 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
778 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
779 setOperationAction(ISD::FRINT, MVT::f80, Expand);
780 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
781 setOperationAction(ISD::FMA, MVT::f80, Expand);
784 // Always use a library call for pow.
785 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
786 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
787 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
789 setOperationAction(ISD::FLOG, MVT::f80, Expand);
790 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
791 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
792 setOperationAction(ISD::FEXP, MVT::f80, Expand);
793 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
795 // First set operation action for all vector types to either promote
796 // (for widening) or expand (for scalarization). Then we will selectively
797 // turn on ones that can be effectively codegen'd.
798 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
799 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
800 MVT VT = (MVT::SimpleValueType)i;
801 setOperationAction(ISD::ADD , VT, Expand);
802 setOperationAction(ISD::SUB , VT, Expand);
803 setOperationAction(ISD::FADD, VT, Expand);
804 setOperationAction(ISD::FNEG, VT, Expand);
805 setOperationAction(ISD::FSUB, VT, Expand);
806 setOperationAction(ISD::MUL , VT, Expand);
807 setOperationAction(ISD::FMUL, VT, Expand);
808 setOperationAction(ISD::SDIV, VT, Expand);
809 setOperationAction(ISD::UDIV, VT, Expand);
810 setOperationAction(ISD::FDIV, VT, Expand);
811 setOperationAction(ISD::SREM, VT, Expand);
812 setOperationAction(ISD::UREM, VT, Expand);
813 setOperationAction(ISD::LOAD, VT, Expand);
814 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
816 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
817 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
818 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
819 setOperationAction(ISD::FABS, VT, Expand);
820 setOperationAction(ISD::FSIN, VT, Expand);
821 setOperationAction(ISD::FSINCOS, VT, Expand);
822 setOperationAction(ISD::FCOS, VT, Expand);
823 setOperationAction(ISD::FSINCOS, VT, Expand);
824 setOperationAction(ISD::FREM, VT, Expand);
825 setOperationAction(ISD::FMA, VT, Expand);
826 setOperationAction(ISD::FPOWI, VT, Expand);
827 setOperationAction(ISD::FSQRT, VT, Expand);
828 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
829 setOperationAction(ISD::FFLOOR, VT, Expand);
830 setOperationAction(ISD::FCEIL, VT, Expand);
831 setOperationAction(ISD::FTRUNC, VT, Expand);
832 setOperationAction(ISD::FRINT, VT, Expand);
833 setOperationAction(ISD::FNEARBYINT, VT, Expand);
834 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
835 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
836 setOperationAction(ISD::SDIVREM, VT, Expand);
837 setOperationAction(ISD::UDIVREM, VT, Expand);
838 setOperationAction(ISD::FPOW, VT, Expand);
839 setOperationAction(ISD::CTPOP, VT, Expand);
840 setOperationAction(ISD::CTTZ, VT, Expand);
841 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
842 setOperationAction(ISD::CTLZ, VT, Expand);
843 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
844 setOperationAction(ISD::SHL, VT, Expand);
845 setOperationAction(ISD::SRA, VT, Expand);
846 setOperationAction(ISD::SRL, VT, Expand);
847 setOperationAction(ISD::ROTL, VT, Expand);
848 setOperationAction(ISD::ROTR, VT, Expand);
849 setOperationAction(ISD::BSWAP, VT, Expand);
850 setOperationAction(ISD::SETCC, VT, Expand);
851 setOperationAction(ISD::FLOG, VT, Expand);
852 setOperationAction(ISD::FLOG2, VT, Expand);
853 setOperationAction(ISD::FLOG10, VT, Expand);
854 setOperationAction(ISD::FEXP, VT, Expand);
855 setOperationAction(ISD::FEXP2, VT, Expand);
856 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
857 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
858 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
859 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
860 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
861 setOperationAction(ISD::TRUNCATE, VT, Expand);
862 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
863 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
864 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
865 setOperationAction(ISD::VSELECT, VT, Expand);
866 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
867 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
868 setTruncStoreAction(VT,
869 (MVT::SimpleValueType)InnerVT, Expand);
870 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
871 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
872 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
875 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
876 // with -msoft-float, disable use of MMX as well.
877 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
878 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
879 // No operations on x86mmx supported, everything uses intrinsics.
882 // MMX-sized vectors (other than x86mmx) are expected to be expanded
883 // into smaller operations.
884 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
885 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
886 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
887 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
888 setOperationAction(ISD::AND, MVT::v8i8, Expand);
889 setOperationAction(ISD::AND, MVT::v4i16, Expand);
890 setOperationAction(ISD::AND, MVT::v2i32, Expand);
891 setOperationAction(ISD::AND, MVT::v1i64, Expand);
892 setOperationAction(ISD::OR, MVT::v8i8, Expand);
893 setOperationAction(ISD::OR, MVT::v4i16, Expand);
894 setOperationAction(ISD::OR, MVT::v2i32, Expand);
895 setOperationAction(ISD::OR, MVT::v1i64, Expand);
896 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
897 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
898 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
899 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
900 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
901 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
902 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
903 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
904 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
905 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
906 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
907 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
908 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
909 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
910 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
911 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
912 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
914 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
915 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
917 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
918 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
919 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
920 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
921 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
922 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
923 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
924 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
925 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
926 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
927 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
928 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
931 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
932 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
934 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
935 // registers cannot be used even for integer operations.
936 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
937 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
938 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
939 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
941 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
942 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
943 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
944 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
945 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
946 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
947 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
948 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
949 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
950 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
951 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
952 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
953 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
954 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
955 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
956 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
957 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
958 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
960 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
961 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
962 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
963 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
965 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
966 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
971 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
972 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
973 MVT VT = (MVT::SimpleValueType)i;
974 // Do not attempt to custom lower non-power-of-2 vectors
975 if (!isPowerOf2_32(VT.getVectorNumElements()))
977 // Do not attempt to custom lower non-128-bit vectors
978 if (!VT.is128BitVector())
980 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
981 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
982 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
985 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
986 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
987 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
988 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
989 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
992 if (Subtarget->is64Bit()) {
993 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
994 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
997 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
998 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
999 MVT VT = (MVT::SimpleValueType)i;
1001 // Do not attempt to promote non-128-bit vectors
1002 if (!VT.is128BitVector())
1005 setOperationAction(ISD::AND, VT, Promote);
1006 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1007 setOperationAction(ISD::OR, VT, Promote);
1008 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1009 setOperationAction(ISD::XOR, VT, Promote);
1010 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1011 setOperationAction(ISD::LOAD, VT, Promote);
1012 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1013 setOperationAction(ISD::SELECT, VT, Promote);
1014 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1017 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1019 // Custom lower v2i64 and v2f64 selects.
1020 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1021 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1022 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1023 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1025 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1026 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1028 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1029 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1030 // As there is no 64-bit GPR available, we need build a special custom
1031 // sequence to convert from v2i32 to v2f32.
1032 if (!Subtarget->is64Bit())
1033 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1035 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1036 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1038 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1041 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1042 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1043 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1044 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1045 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1046 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1047 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1048 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1049 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1050 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1051 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1053 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1054 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1055 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1056 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1057 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1058 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1059 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1060 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1061 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1062 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1064 // FIXME: Do we need to handle scalar-to-vector here?
1065 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1068 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1069 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1073 // i8 and i16 vectors are custom , because the source register and source
1074 // source memory operand types are not the same width. f32 vectors are
1075 // custom since the immediate controlling the insert encodes additional
1077 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1078 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1079 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1080 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1082 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1083 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1084 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1085 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1087 // FIXME: these should be Legal but thats only for the case where
1088 // the index is constant. For now custom expand to deal with that.
1089 if (Subtarget->is64Bit()) {
1090 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1091 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1095 if (Subtarget->hasSSE2()) {
1096 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1097 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1099 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1100 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1102 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1103 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1105 // In the customized shift lowering, the legal cases in AVX2 will be
1107 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1108 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1110 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1111 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1113 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1115 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1116 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1119 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1120 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1122 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1123 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1124 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1125 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1127 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1128 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1129 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1131 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1140 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1142 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1144 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1153 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1154 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1155 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1157 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1158 // even though v8i16 is a legal type.
1159 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1160 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1161 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1163 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1164 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1165 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1167 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1168 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1170 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1172 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1176 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1183 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1184 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1185 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1186 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1188 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1189 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1190 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1192 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1193 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1194 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1195 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1197 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1198 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1199 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1200 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1201 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1202 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1203 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1204 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1205 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1206 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1207 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1208 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1210 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1211 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1212 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1213 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1214 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1215 setOperationAction(ISD::FMA, MVT::f32, Legal);
1216 setOperationAction(ISD::FMA, MVT::f64, Legal);
1219 if (Subtarget->hasInt256()) {
1220 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1221 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1222 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1223 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1225 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1226 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1227 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1228 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1230 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1231 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1232 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1233 // Don't lower v32i8 because there is no 128-bit byte mul
1235 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1237 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1239 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1240 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1241 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1242 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1244 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1245 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1246 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1247 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1249 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1250 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1251 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1252 // Don't lower v32i8 because there is no 128-bit byte mul
1255 // In the customized shift lowering, the legal cases in AVX2 will be
1257 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1258 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1260 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1261 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1263 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1265 // Custom lower several nodes for 256-bit types.
1266 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1267 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1268 MVT VT = (MVT::SimpleValueType)i;
1270 // Extract subvector is special because the value type
1271 // (result) is 128-bit but the source is 256-bit wide.
1272 if (VT.is128BitVector())
1273 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1275 // Do not attempt to custom lower other non-256-bit vectors
1276 if (!VT.is256BitVector())
1279 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1280 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1281 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1282 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1283 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1284 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1285 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1288 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1289 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1290 MVT VT = (MVT::SimpleValueType)i;
1292 // Do not attempt to promote non-256-bit vectors
1293 if (!VT.is256BitVector())
1296 setOperationAction(ISD::AND, VT, Promote);
1297 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1298 setOperationAction(ISD::OR, VT, Promote);
1299 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1300 setOperationAction(ISD::XOR, VT, Promote);
1301 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1302 setOperationAction(ISD::LOAD, VT, Promote);
1303 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1304 setOperationAction(ISD::SELECT, VT, Promote);
1305 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1309 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1310 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1311 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1312 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1313 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1315 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1316 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1317 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1319 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1320 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1321 setOperationAction(ISD::XOR, MVT::i1, Legal);
1322 setOperationAction(ISD::OR, MVT::i1, Legal);
1323 setOperationAction(ISD::AND, MVT::i1, Legal);
1324 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1325 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1326 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1327 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1328 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1329 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1331 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1332 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1333 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1334 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1335 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1336 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1338 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1340 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1341 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1342 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1343 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1344 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1345 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1346 setOperationAction(ISD::SDIV, MVT::v16i32, Custom);
1348 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1349 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1350 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1351 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1352 if (Subtarget->is64Bit()) {
1353 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1354 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1355 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1356 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1358 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1359 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1360 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1361 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1362 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1363 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1364 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1365 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1367 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1368 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1369 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1372 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1373 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1374 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1375 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1376 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1377 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1378 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1379 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1381 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1383 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1384 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1386 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1388 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1389 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1391 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1393 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1395 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1396 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1397 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1398 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1399 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1401 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1402 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1404 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1405 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1407 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1409 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1410 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1412 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1413 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1415 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1416 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1418 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1419 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1420 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1421 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1422 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1423 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1425 // Custom lower several nodes.
1426 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1427 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1428 MVT VT = (MVT::SimpleValueType)i;
1430 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1431 // Extract subvector is special because the value type
1432 // (result) is 256/128-bit but the source is 512-bit wide.
1433 if (VT.is128BitVector() || VT.is256BitVector())
1434 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1436 if (VT.getVectorElementType() == MVT::i1)
1437 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1439 // Do not attempt to custom lower other non-512-bit vectors
1440 if (!VT.is512BitVector())
1443 if ( EltSize >= 32) {
1444 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1445 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1446 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1447 setOperationAction(ISD::VSELECT, VT, Legal);
1448 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1449 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1450 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1453 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1454 MVT VT = (MVT::SimpleValueType)i;
1456 // Do not attempt to promote non-256-bit vectors
1457 if (!VT.is512BitVector())
1460 setOperationAction(ISD::SELECT, VT, Promote);
1461 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1465 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1466 // of this type with custom code.
1467 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1468 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1469 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1473 // We want to custom lower some of our intrinsics.
1474 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1475 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1476 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1478 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1479 // handle type legalization for these operations here.
1481 // FIXME: We really should do custom legalization for addition and
1482 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1483 // than generic legalization for 64-bit multiplication-with-overflow, though.
1484 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1485 // Add/Sub/Mul with overflow operations are custom lowered.
1487 setOperationAction(ISD::SADDO, VT, Custom);
1488 setOperationAction(ISD::UADDO, VT, Custom);
1489 setOperationAction(ISD::SSUBO, VT, Custom);
1490 setOperationAction(ISD::USUBO, VT, Custom);
1491 setOperationAction(ISD::SMULO, VT, Custom);
1492 setOperationAction(ISD::UMULO, VT, Custom);
1495 // There are no 8-bit 3-address imul/mul instructions
1496 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1497 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1499 if (!Subtarget->is64Bit()) {
1500 // These libcalls are not available in 32-bit.
1501 setLibcallName(RTLIB::SHL_I128, 0);
1502 setLibcallName(RTLIB::SRL_I128, 0);
1503 setLibcallName(RTLIB::SRA_I128, 0);
1506 // Combine sin / cos into one node or libcall if possible.
1507 if (Subtarget->hasSinCos()) {
1508 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1509 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1510 if (Subtarget->isTargetDarwin()) {
1511 // For MacOSX, we don't want to the normal expansion of a libcall to
1512 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1514 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1515 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1519 // We have target-specific dag combine patterns for the following nodes:
1520 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1521 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1522 setTargetDAGCombine(ISD::VSELECT);
1523 setTargetDAGCombine(ISD::SELECT);
1524 setTargetDAGCombine(ISD::SHL);
1525 setTargetDAGCombine(ISD::SRA);
1526 setTargetDAGCombine(ISD::SRL);
1527 setTargetDAGCombine(ISD::OR);
1528 setTargetDAGCombine(ISD::AND);
1529 setTargetDAGCombine(ISD::ADD);
1530 setTargetDAGCombine(ISD::FADD);
1531 setTargetDAGCombine(ISD::FSUB);
1532 setTargetDAGCombine(ISD::FMA);
1533 setTargetDAGCombine(ISD::SUB);
1534 setTargetDAGCombine(ISD::LOAD);
1535 setTargetDAGCombine(ISD::STORE);
1536 setTargetDAGCombine(ISD::ZERO_EXTEND);
1537 setTargetDAGCombine(ISD::ANY_EXTEND);
1538 setTargetDAGCombine(ISD::SIGN_EXTEND);
1539 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1540 setTargetDAGCombine(ISD::TRUNCATE);
1541 setTargetDAGCombine(ISD::SINT_TO_FP);
1542 setTargetDAGCombine(ISD::SETCC);
1543 if (Subtarget->is64Bit())
1544 setTargetDAGCombine(ISD::MUL);
1545 setTargetDAGCombine(ISD::XOR);
1547 computeRegisterProperties();
1549 // On Darwin, -Os means optimize for size without hurting performance,
1550 // do not reduce the limit.
1551 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1552 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1553 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1554 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1555 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1556 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1557 setPrefLoopAlignment(4); // 2^4 bytes.
1559 // Predictable cmov don't hurt on atom because it's in-order.
1560 PredictableSelectIsExpensive = !Subtarget->isAtom();
1562 setPrefFunctionAlignment(4); // 2^4 bytes.
1565 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1567 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1569 if (Subtarget->hasAVX512())
1570 switch(VT.getVectorNumElements()) {
1571 case 8: return MVT::v8i1;
1572 case 16: return MVT::v16i1;
1575 return VT.changeVectorElementTypeToInteger();
1578 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1579 /// the desired ByVal argument alignment.
1580 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1583 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1584 if (VTy->getBitWidth() == 128)
1586 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1587 unsigned EltAlign = 0;
1588 getMaxByValAlign(ATy->getElementType(), EltAlign);
1589 if (EltAlign > MaxAlign)
1590 MaxAlign = EltAlign;
1591 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1592 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1593 unsigned EltAlign = 0;
1594 getMaxByValAlign(STy->getElementType(i), EltAlign);
1595 if (EltAlign > MaxAlign)
1596 MaxAlign = EltAlign;
1603 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1604 /// function arguments in the caller parameter area. For X86, aggregates
1605 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1606 /// are at 4-byte boundaries.
1607 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1608 if (Subtarget->is64Bit()) {
1609 // Max of 8 and alignment of type.
1610 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1617 if (Subtarget->hasSSE1())
1618 getMaxByValAlign(Ty, Align);
1622 /// getOptimalMemOpType - Returns the target specific optimal type for load
1623 /// and store operations as a result of memset, memcpy, and memmove
1624 /// lowering. If DstAlign is zero that means it's safe to destination
1625 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1626 /// means there isn't a need to check it against alignment requirement,
1627 /// probably because the source does not need to be loaded. If 'IsMemset' is
1628 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1629 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1630 /// source is constant so it does not need to be loaded.
1631 /// It returns EVT::Other if the type should be determined using generic
1632 /// target-independent logic.
1634 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1635 unsigned DstAlign, unsigned SrcAlign,
1636 bool IsMemset, bool ZeroMemset,
1638 MachineFunction &MF) const {
1639 const Function *F = MF.getFunction();
1640 if ((!IsMemset || ZeroMemset) &&
1641 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1642 Attribute::NoImplicitFloat)) {
1644 (Subtarget->isUnalignedMemAccessFast() ||
1645 ((DstAlign == 0 || DstAlign >= 16) &&
1646 (SrcAlign == 0 || SrcAlign >= 16)))) {
1648 if (Subtarget->hasInt256())
1650 if (Subtarget->hasFp256())
1653 if (Subtarget->hasSSE2())
1655 if (Subtarget->hasSSE1())
1657 } else if (!MemcpyStrSrc && Size >= 8 &&
1658 !Subtarget->is64Bit() &&
1659 Subtarget->hasSSE2()) {
1660 // Do not use f64 to lower memcpy if source is string constant. It's
1661 // better to use i32 to avoid the loads.
1665 if (Subtarget->is64Bit() && Size >= 8)
1670 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1672 return X86ScalarSSEf32;
1673 else if (VT == MVT::f64)
1674 return X86ScalarSSEf64;
1679 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1683 *Fast = Subtarget->isUnalignedMemAccessFast();
1687 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1688 /// current function. The returned value is a member of the
1689 /// MachineJumpTableInfo::JTEntryKind enum.
1690 unsigned X86TargetLowering::getJumpTableEncoding() const {
1691 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1693 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1694 Subtarget->isPICStyleGOT())
1695 return MachineJumpTableInfo::EK_Custom32;
1697 // Otherwise, use the normal jump table encoding heuristics.
1698 return TargetLowering::getJumpTableEncoding();
1702 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1703 const MachineBasicBlock *MBB,
1704 unsigned uid,MCContext &Ctx) const{
1705 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1706 Subtarget->isPICStyleGOT());
1707 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1709 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1710 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1713 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1715 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1716 SelectionDAG &DAG) const {
1717 if (!Subtarget->is64Bit())
1718 // This doesn't have SDLoc associated with it, but is not really the
1719 // same as a Register.
1720 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1724 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1725 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1727 const MCExpr *X86TargetLowering::
1728 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1729 MCContext &Ctx) const {
1730 // X86-64 uses RIP relative addressing based on the jump table label.
1731 if (Subtarget->isPICStyleRIPRel())
1732 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1734 // Otherwise, the reference is relative to the PIC base.
1735 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1738 // FIXME: Why this routine is here? Move to RegInfo!
1739 std::pair<const TargetRegisterClass*, uint8_t>
1740 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1741 const TargetRegisterClass *RRC = 0;
1743 switch (VT.SimpleTy) {
1745 return TargetLowering::findRepresentativeClass(VT);
1746 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1747 RRC = Subtarget->is64Bit() ?
1748 (const TargetRegisterClass*)&X86::GR64RegClass :
1749 (const TargetRegisterClass*)&X86::GR32RegClass;
1752 RRC = &X86::VR64RegClass;
1754 case MVT::f32: case MVT::f64:
1755 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1756 case MVT::v4f32: case MVT::v2f64:
1757 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1759 RRC = &X86::VR128RegClass;
1762 return std::make_pair(RRC, Cost);
1765 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1766 unsigned &Offset) const {
1767 if (!Subtarget->isTargetLinux())
1770 if (Subtarget->is64Bit()) {
1771 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1773 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1785 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1786 unsigned DestAS) const {
1787 assert(SrcAS != DestAS && "Expected different address spaces!");
1789 return SrcAS < 256 && DestAS < 256;
1792 //===----------------------------------------------------------------------===//
1793 // Return Value Calling Convention Implementation
1794 //===----------------------------------------------------------------------===//
1796 #include "X86GenCallingConv.inc"
1799 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1800 MachineFunction &MF, bool isVarArg,
1801 const SmallVectorImpl<ISD::OutputArg> &Outs,
1802 LLVMContext &Context) const {
1803 SmallVector<CCValAssign, 16> RVLocs;
1804 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1806 return CCInfo.CheckReturn(Outs, RetCC_X86);
1809 const uint16_t *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1810 static const uint16_t ScratchRegs[] = { X86::R11, 0 };
1815 X86TargetLowering::LowerReturn(SDValue Chain,
1816 CallingConv::ID CallConv, bool isVarArg,
1817 const SmallVectorImpl<ISD::OutputArg> &Outs,
1818 const SmallVectorImpl<SDValue> &OutVals,
1819 SDLoc dl, SelectionDAG &DAG) const {
1820 MachineFunction &MF = DAG.getMachineFunction();
1821 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1823 SmallVector<CCValAssign, 16> RVLocs;
1824 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1825 RVLocs, *DAG.getContext());
1826 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1829 SmallVector<SDValue, 6> RetOps;
1830 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1831 // Operand #1 = Bytes To Pop
1832 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1835 // Copy the result values into the output registers.
1836 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1837 CCValAssign &VA = RVLocs[i];
1838 assert(VA.isRegLoc() && "Can only return in registers!");
1839 SDValue ValToCopy = OutVals[i];
1840 EVT ValVT = ValToCopy.getValueType();
1842 // Promote values to the appropriate types
1843 if (VA.getLocInfo() == CCValAssign::SExt)
1844 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1845 else if (VA.getLocInfo() == CCValAssign::ZExt)
1846 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1847 else if (VA.getLocInfo() == CCValAssign::AExt)
1848 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1849 else if (VA.getLocInfo() == CCValAssign::BCvt)
1850 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1852 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1853 "Unexpected FP-extend for return value.");
1855 // If this is x86-64, and we disabled SSE, we can't return FP values,
1856 // or SSE or MMX vectors.
1857 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1858 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1859 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1860 report_fatal_error("SSE register return with SSE disabled");
1862 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1863 // llvm-gcc has never done it right and no one has noticed, so this
1864 // should be OK for now.
1865 if (ValVT == MVT::f64 &&
1866 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1867 report_fatal_error("SSE2 register return with SSE2 disabled");
1869 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1870 // the RET instruction and handled by the FP Stackifier.
1871 if (VA.getLocReg() == X86::ST0 ||
1872 VA.getLocReg() == X86::ST1) {
1873 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1874 // change the value to the FP stack register class.
1875 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1876 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1877 RetOps.push_back(ValToCopy);
1878 // Don't emit a copytoreg.
1882 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1883 // which is returned in RAX / RDX.
1884 if (Subtarget->is64Bit()) {
1885 if (ValVT == MVT::x86mmx) {
1886 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1887 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1888 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1890 // If we don't have SSE2 available, convert to v4f32 so the generated
1891 // register is legal.
1892 if (!Subtarget->hasSSE2())
1893 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1898 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1899 Flag = Chain.getValue(1);
1900 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1903 // The x86-64 ABIs require that for returning structs by value we copy
1904 // the sret argument into %rax/%eax (depending on ABI) for the return.
1905 // Win32 requires us to put the sret argument to %eax as well.
1906 // We saved the argument into a virtual register in the entry block,
1907 // so now we copy the value out and into %rax/%eax.
1908 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1909 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1910 MachineFunction &MF = DAG.getMachineFunction();
1911 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1912 unsigned Reg = FuncInfo->getSRetReturnReg();
1914 "SRetReturnReg should have been set in LowerFormalArguments().");
1915 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1918 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1919 X86::RAX : X86::EAX;
1920 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1921 Flag = Chain.getValue(1);
1923 // RAX/EAX now acts like a return value.
1924 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1927 RetOps[0] = Chain; // Update chain.
1929 // Add the flag if we have it.
1931 RetOps.push_back(Flag);
1933 return DAG.getNode(X86ISD::RET_FLAG, dl,
1934 MVT::Other, &RetOps[0], RetOps.size());
1937 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1938 if (N->getNumValues() != 1)
1940 if (!N->hasNUsesOfValue(1, 0))
1943 SDValue TCChain = Chain;
1944 SDNode *Copy = *N->use_begin();
1945 if (Copy->getOpcode() == ISD::CopyToReg) {
1946 // If the copy has a glue operand, we conservatively assume it isn't safe to
1947 // perform a tail call.
1948 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1950 TCChain = Copy->getOperand(0);
1951 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1954 bool HasRet = false;
1955 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1957 if (UI->getOpcode() != X86ISD::RET_FLAG)
1970 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1971 ISD::NodeType ExtendKind) const {
1973 // TODO: Is this also valid on 32-bit?
1974 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1975 ReturnMVT = MVT::i8;
1977 ReturnMVT = MVT::i32;
1979 MVT MinVT = getRegisterType(ReturnMVT);
1980 return VT.bitsLT(MinVT) ? MinVT : VT;
1983 /// LowerCallResult - Lower the result values of a call into the
1984 /// appropriate copies out of appropriate physical registers.
1987 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1988 CallingConv::ID CallConv, bool isVarArg,
1989 const SmallVectorImpl<ISD::InputArg> &Ins,
1990 SDLoc dl, SelectionDAG &DAG,
1991 SmallVectorImpl<SDValue> &InVals) const {
1993 // Assign locations to each value returned by this call.
1994 SmallVector<CCValAssign, 16> RVLocs;
1995 bool Is64Bit = Subtarget->is64Bit();
1996 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1997 getTargetMachine(), RVLocs, *DAG.getContext());
1998 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2000 // Copy all of the result registers out of their specified physreg.
2001 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2002 CCValAssign &VA = RVLocs[i];
2003 EVT CopyVT = VA.getValVT();
2005 // If this is x86-64, and we disabled SSE, we can't return FP values
2006 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2007 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2008 report_fatal_error("SSE register return with SSE disabled");
2013 // If this is a call to a function that returns an fp value on the floating
2014 // point stack, we must guarantee the value is popped from the stack, so
2015 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2016 // if the return value is not used. We use the FpPOP_RETVAL instruction
2018 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2019 // If we prefer to use the value in xmm registers, copy it out as f80 and
2020 // use a truncate to move it from fp stack reg to xmm reg.
2021 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2022 SDValue Ops[] = { Chain, InFlag };
2023 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2024 MVT::Other, MVT::Glue, Ops), 1);
2025 Val = Chain.getValue(0);
2027 // Round the f80 to the right size, which also moves it to the appropriate
2029 if (CopyVT != VA.getValVT())
2030 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2031 // This truncation won't change the value.
2032 DAG.getIntPtrConstant(1));
2034 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2035 CopyVT, InFlag).getValue(1);
2036 Val = Chain.getValue(0);
2038 InFlag = Chain.getValue(2);
2039 InVals.push_back(Val);
2045 //===----------------------------------------------------------------------===//
2046 // C & StdCall & Fast Calling Convention implementation
2047 //===----------------------------------------------------------------------===//
2048 // StdCall calling convention seems to be standard for many Windows' API
2049 // routines and around. It differs from C calling convention just a little:
2050 // callee should clean up the stack, not caller. Symbols should be also
2051 // decorated in some fancy way :) It doesn't support any vector arguments.
2052 // For info on fast calling convention see Fast Calling Convention (tail call)
2053 // implementation LowerX86_32FastCCCallTo.
2055 /// CallIsStructReturn - Determines whether a call uses struct return
2057 enum StructReturnType {
2062 static StructReturnType
2063 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2065 return NotStructReturn;
2067 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2068 if (!Flags.isSRet())
2069 return NotStructReturn;
2070 if (Flags.isInReg())
2071 return RegStructReturn;
2072 return StackStructReturn;
2075 /// ArgsAreStructReturn - Determines whether a function uses struct
2076 /// return semantics.
2077 static StructReturnType
2078 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2080 return NotStructReturn;
2082 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2083 if (!Flags.isSRet())
2084 return NotStructReturn;
2085 if (Flags.isInReg())
2086 return RegStructReturn;
2087 return StackStructReturn;
2090 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2091 /// by "Src" to address "Dst" with size and alignment information specified by
2092 /// the specific parameter attribute. The copy will be passed as a byval
2093 /// function parameter.
2095 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2096 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2098 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2100 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2101 /*isVolatile*/false, /*AlwaysInline=*/true,
2102 MachinePointerInfo(), MachinePointerInfo());
2105 /// IsTailCallConvention - Return true if the calling convention is one that
2106 /// supports tail call optimization.
2107 static bool IsTailCallConvention(CallingConv::ID CC) {
2108 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2109 CC == CallingConv::HiPE);
2112 /// \brief Return true if the calling convention is a C calling convention.
2113 static bool IsCCallConvention(CallingConv::ID CC) {
2114 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2115 CC == CallingConv::X86_64_SysV);
2118 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2119 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2123 CallingConv::ID CalleeCC = CS.getCallingConv();
2124 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2130 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2131 /// a tailcall target by changing its ABI.
2132 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2133 bool GuaranteedTailCallOpt) {
2134 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2138 X86TargetLowering::LowerMemArgument(SDValue Chain,
2139 CallingConv::ID CallConv,
2140 const SmallVectorImpl<ISD::InputArg> &Ins,
2141 SDLoc dl, SelectionDAG &DAG,
2142 const CCValAssign &VA,
2143 MachineFrameInfo *MFI,
2145 // Create the nodes corresponding to a load from this parameter slot.
2146 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2147 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2148 getTargetMachine().Options.GuaranteedTailCallOpt);
2149 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2152 // If value is passed by pointer we have address passed instead of the value
2154 if (VA.getLocInfo() == CCValAssign::Indirect)
2155 ValVT = VA.getLocVT();
2157 ValVT = VA.getValVT();
2159 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2160 // changed with more analysis.
2161 // In case of tail call optimization mark all arguments mutable. Since they
2162 // could be overwritten by lowering of arguments in case of a tail call.
2163 if (Flags.isByVal()) {
2164 unsigned Bytes = Flags.getByValSize();
2165 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2166 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2167 return DAG.getFrameIndex(FI, getPointerTy());
2169 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2170 VA.getLocMemOffset(), isImmutable);
2171 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2172 return DAG.getLoad(ValVT, dl, Chain, FIN,
2173 MachinePointerInfo::getFixedStack(FI),
2174 false, false, false, 0);
2179 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2180 CallingConv::ID CallConv,
2182 const SmallVectorImpl<ISD::InputArg> &Ins,
2185 SmallVectorImpl<SDValue> &InVals)
2187 MachineFunction &MF = DAG.getMachineFunction();
2188 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2190 const Function* Fn = MF.getFunction();
2191 if (Fn->hasExternalLinkage() &&
2192 Subtarget->isTargetCygMing() &&
2193 Fn->getName() == "main")
2194 FuncInfo->setForceFramePointer(true);
2196 MachineFrameInfo *MFI = MF.getFrameInfo();
2197 bool Is64Bit = Subtarget->is64Bit();
2198 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2200 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2201 "Var args not supported with calling convention fastcc, ghc or hipe");
2203 // Assign locations to all of the incoming arguments.
2204 SmallVector<CCValAssign, 16> ArgLocs;
2205 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2206 ArgLocs, *DAG.getContext());
2208 // Allocate shadow area for Win64
2210 CCInfo.AllocateStack(32, 8);
2212 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2214 unsigned LastVal = ~0U;
2216 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2217 CCValAssign &VA = ArgLocs[i];
2218 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2220 assert(VA.getValNo() != LastVal &&
2221 "Don't support value assigned to multiple locs yet");
2223 LastVal = VA.getValNo();
2225 if (VA.isRegLoc()) {
2226 EVT RegVT = VA.getLocVT();
2227 const TargetRegisterClass *RC;
2228 if (RegVT == MVT::i32)
2229 RC = &X86::GR32RegClass;
2230 else if (Is64Bit && RegVT == MVT::i64)
2231 RC = &X86::GR64RegClass;
2232 else if (RegVT == MVT::f32)
2233 RC = &X86::FR32RegClass;
2234 else if (RegVT == MVT::f64)
2235 RC = &X86::FR64RegClass;
2236 else if (RegVT.is512BitVector())
2237 RC = &X86::VR512RegClass;
2238 else if (RegVT.is256BitVector())
2239 RC = &X86::VR256RegClass;
2240 else if (RegVT.is128BitVector())
2241 RC = &X86::VR128RegClass;
2242 else if (RegVT == MVT::x86mmx)
2243 RC = &X86::VR64RegClass;
2244 else if (RegVT == MVT::i1)
2245 RC = &X86::VK1RegClass;
2246 else if (RegVT == MVT::v8i1)
2247 RC = &X86::VK8RegClass;
2248 else if (RegVT == MVT::v16i1)
2249 RC = &X86::VK16RegClass;
2251 llvm_unreachable("Unknown argument type!");
2253 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2254 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2256 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2257 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2259 if (VA.getLocInfo() == CCValAssign::SExt)
2260 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2261 DAG.getValueType(VA.getValVT()));
2262 else if (VA.getLocInfo() == CCValAssign::ZExt)
2263 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2264 DAG.getValueType(VA.getValVT()));
2265 else if (VA.getLocInfo() == CCValAssign::BCvt)
2266 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2268 if (VA.isExtInLoc()) {
2269 // Handle MMX values passed in XMM regs.
2270 if (RegVT.isVector())
2271 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2273 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2276 assert(VA.isMemLoc());
2277 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2280 // If value is passed via pointer - do a load.
2281 if (VA.getLocInfo() == CCValAssign::Indirect)
2282 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2283 MachinePointerInfo(), false, false, false, 0);
2285 InVals.push_back(ArgValue);
2288 // The x86-64 ABIs require that for returning structs by value we copy
2289 // the sret argument into %rax/%eax (depending on ABI) for the return.
2290 // Win32 requires us to put the sret argument to %eax as well.
2291 // Save the argument into a virtual register so that we can access it
2292 // from the return points.
2293 if (MF.getFunction()->hasStructRetAttr() &&
2294 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2295 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2296 unsigned Reg = FuncInfo->getSRetReturnReg();
2298 MVT PtrTy = getPointerTy();
2299 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2300 FuncInfo->setSRetReturnReg(Reg);
2302 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2303 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2306 unsigned StackSize = CCInfo.getNextStackOffset();
2307 // Align stack specially for tail calls.
2308 if (FuncIsMadeTailCallSafe(CallConv,
2309 MF.getTarget().Options.GuaranteedTailCallOpt))
2310 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2312 // If the function takes variable number of arguments, make a frame index for
2313 // the start of the first vararg value... for expansion of llvm.va_start.
2315 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2316 CallConv != CallingConv::X86_ThisCall)) {
2317 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2320 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2322 // FIXME: We should really autogenerate these arrays
2323 static const uint16_t GPR64ArgRegsWin64[] = {
2324 X86::RCX, X86::RDX, X86::R8, X86::R9
2326 static const uint16_t GPR64ArgRegs64Bit[] = {
2327 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2329 static const uint16_t XMMArgRegs64Bit[] = {
2330 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2331 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2333 const uint16_t *GPR64ArgRegs;
2334 unsigned NumXMMRegs = 0;
2337 // The XMM registers which might contain var arg parameters are shadowed
2338 // in their paired GPR. So we only need to save the GPR to their home
2340 TotalNumIntRegs = 4;
2341 GPR64ArgRegs = GPR64ArgRegsWin64;
2343 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2344 GPR64ArgRegs = GPR64ArgRegs64Bit;
2346 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2349 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2352 bool NoImplicitFloatOps = Fn->getAttributes().
2353 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2354 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2355 "SSE register cannot be used when SSE is disabled!");
2356 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2357 NoImplicitFloatOps) &&
2358 "SSE register cannot be used when SSE is disabled!");
2359 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2360 !Subtarget->hasSSE1())
2361 // Kernel mode asks for SSE to be disabled, so don't push them
2363 TotalNumXMMRegs = 0;
2366 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2367 // Get to the caller-allocated home save location. Add 8 to account
2368 // for the return address.
2369 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2370 FuncInfo->setRegSaveFrameIndex(
2371 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2372 // Fixup to set vararg frame on shadow area (4 x i64).
2374 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2376 // For X86-64, if there are vararg parameters that are passed via
2377 // registers, then we must store them to their spots on the stack so
2378 // they may be loaded by deferencing the result of va_next.
2379 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2380 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2381 FuncInfo->setRegSaveFrameIndex(
2382 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2386 // Store the integer parameter registers.
2387 SmallVector<SDValue, 8> MemOps;
2388 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2390 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2391 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2392 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2393 DAG.getIntPtrConstant(Offset));
2394 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2395 &X86::GR64RegClass);
2396 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2398 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2399 MachinePointerInfo::getFixedStack(
2400 FuncInfo->getRegSaveFrameIndex(), Offset),
2402 MemOps.push_back(Store);
2406 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2407 // Now store the XMM (fp + vector) parameter registers.
2408 SmallVector<SDValue, 11> SaveXMMOps;
2409 SaveXMMOps.push_back(Chain);
2411 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2412 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2413 SaveXMMOps.push_back(ALVal);
2415 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2416 FuncInfo->getRegSaveFrameIndex()));
2417 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2418 FuncInfo->getVarArgsFPOffset()));
2420 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2421 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2422 &X86::VR128RegClass);
2423 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2424 SaveXMMOps.push_back(Val);
2426 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2428 &SaveXMMOps[0], SaveXMMOps.size()));
2431 if (!MemOps.empty())
2432 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2433 &MemOps[0], MemOps.size());
2437 // Some CCs need callee pop.
2438 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2439 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2440 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2442 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2443 // If this is an sret function, the return should pop the hidden pointer.
2444 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2445 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2446 argsAreStructReturn(Ins) == StackStructReturn)
2447 FuncInfo->setBytesToPopOnReturn(4);
2451 // RegSaveFrameIndex is X86-64 only.
2452 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2453 if (CallConv == CallingConv::X86_FastCall ||
2454 CallConv == CallingConv::X86_ThisCall)
2455 // fastcc functions can't have varargs.
2456 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2459 FuncInfo->setArgumentStackSize(StackSize);
2465 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2466 SDValue StackPtr, SDValue Arg,
2467 SDLoc dl, SelectionDAG &DAG,
2468 const CCValAssign &VA,
2469 ISD::ArgFlagsTy Flags) const {
2470 unsigned LocMemOffset = VA.getLocMemOffset();
2471 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2472 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2473 if (Flags.isByVal())
2474 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2476 return DAG.getStore(Chain, dl, Arg, PtrOff,
2477 MachinePointerInfo::getStack(LocMemOffset),
2481 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2482 /// optimization is performed and it is required.
2484 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2485 SDValue &OutRetAddr, SDValue Chain,
2486 bool IsTailCall, bool Is64Bit,
2487 int FPDiff, SDLoc dl) const {
2488 // Adjust the Return address stack slot.
2489 EVT VT = getPointerTy();
2490 OutRetAddr = getReturnAddressFrameIndex(DAG);
2492 // Load the "old" Return address.
2493 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2494 false, false, false, 0);
2495 return SDValue(OutRetAddr.getNode(), 1);
2498 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2499 /// optimization is performed and it is required (FPDiff!=0).
2501 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2502 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2503 unsigned SlotSize, int FPDiff, SDLoc dl) {
2504 // Store the return address to the appropriate stack slot.
2505 if (!FPDiff) return Chain;
2506 // Calculate the new stack slot for the return address.
2507 int NewReturnAddrFI =
2508 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2510 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2511 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2512 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2518 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2519 SmallVectorImpl<SDValue> &InVals) const {
2520 SelectionDAG &DAG = CLI.DAG;
2522 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2523 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2524 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2525 SDValue Chain = CLI.Chain;
2526 SDValue Callee = CLI.Callee;
2527 CallingConv::ID CallConv = CLI.CallConv;
2528 bool &isTailCall = CLI.IsTailCall;
2529 bool isVarArg = CLI.IsVarArg;
2531 MachineFunction &MF = DAG.getMachineFunction();
2532 bool Is64Bit = Subtarget->is64Bit();
2533 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2534 StructReturnType SR = callIsStructReturn(Outs);
2535 bool IsSibcall = false;
2537 if (MF.getTarget().Options.DisableTailCalls)
2541 // Check if it's really possible to do a tail call.
2542 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2543 isVarArg, SR != NotStructReturn,
2544 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2545 Outs, OutVals, Ins, DAG);
2547 // Sibcalls are automatically detected tailcalls which do not require
2549 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2556 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2557 "Var args not supported with calling convention fastcc, ghc or hipe");
2559 // Analyze operands of the call, assigning locations to each operand.
2560 SmallVector<CCValAssign, 16> ArgLocs;
2561 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2562 ArgLocs, *DAG.getContext());
2564 // Allocate shadow area for Win64
2566 CCInfo.AllocateStack(32, 8);
2568 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2570 // Get a count of how many bytes are to be pushed on the stack.
2571 unsigned NumBytes = CCInfo.getNextStackOffset();
2573 // This is a sibcall. The memory operands are available in caller's
2574 // own caller's stack.
2576 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2577 IsTailCallConvention(CallConv))
2578 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2581 if (isTailCall && !IsSibcall) {
2582 // Lower arguments at fp - stackoffset + fpdiff.
2583 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2584 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2586 FPDiff = NumBytesCallerPushed - NumBytes;
2588 // Set the delta of movement of the returnaddr stackslot.
2589 // But only set if delta is greater than previous delta.
2590 if (FPDiff < X86Info->getTCReturnAddrDelta())
2591 X86Info->setTCReturnAddrDelta(FPDiff);
2594 unsigned NumBytesToPush = NumBytes;
2595 unsigned NumBytesToPop = NumBytes;
2597 // If we have an inalloca argument, all stack space has already been allocated
2598 // for us and be right at the top of the stack. We don't support multiple
2599 // arguments passed in memory when using inalloca.
2600 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2602 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2603 "an inalloca argument must be the only memory argument");
2607 Chain = DAG.getCALLSEQ_START(
2608 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2610 SDValue RetAddrFrIdx;
2611 // Load return address for tail calls.
2612 if (isTailCall && FPDiff)
2613 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2614 Is64Bit, FPDiff, dl);
2616 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2617 SmallVector<SDValue, 8> MemOpChains;
2620 // Walk the register/memloc assignments, inserting copies/loads. In the case
2621 // of tail call optimization arguments are handle later.
2622 const X86RegisterInfo *RegInfo =
2623 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2624 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2625 // Skip inalloca arguments, they have already been written.
2626 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2627 if (Flags.isInAlloca())
2630 CCValAssign &VA = ArgLocs[i];
2631 EVT RegVT = VA.getLocVT();
2632 SDValue Arg = OutVals[i];
2633 bool isByVal = Flags.isByVal();
2635 // Promote the value if needed.
2636 switch (VA.getLocInfo()) {
2637 default: llvm_unreachable("Unknown loc info!");
2638 case CCValAssign::Full: break;
2639 case CCValAssign::SExt:
2640 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2642 case CCValAssign::ZExt:
2643 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2645 case CCValAssign::AExt:
2646 if (RegVT.is128BitVector()) {
2647 // Special case: passing MMX values in XMM registers.
2648 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2649 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2650 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2652 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2654 case CCValAssign::BCvt:
2655 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2657 case CCValAssign::Indirect: {
2658 // Store the argument.
2659 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2660 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2661 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2662 MachinePointerInfo::getFixedStack(FI),
2669 if (VA.isRegLoc()) {
2670 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2671 if (isVarArg && IsWin64) {
2672 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2673 // shadow reg if callee is a varargs function.
2674 unsigned ShadowReg = 0;
2675 switch (VA.getLocReg()) {
2676 case X86::XMM0: ShadowReg = X86::RCX; break;
2677 case X86::XMM1: ShadowReg = X86::RDX; break;
2678 case X86::XMM2: ShadowReg = X86::R8; break;
2679 case X86::XMM3: ShadowReg = X86::R9; break;
2682 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2684 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2685 assert(VA.isMemLoc());
2686 if (StackPtr.getNode() == 0)
2687 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2689 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2690 dl, DAG, VA, Flags));
2694 if (!MemOpChains.empty())
2695 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2696 &MemOpChains[0], MemOpChains.size());
2698 if (Subtarget->isPICStyleGOT()) {
2699 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2702 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2703 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2705 // If we are tail calling and generating PIC/GOT style code load the
2706 // address of the callee into ECX. The value in ecx is used as target of
2707 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2708 // for tail calls on PIC/GOT architectures. Normally we would just put the
2709 // address of GOT into ebx and then call target@PLT. But for tail calls
2710 // ebx would be restored (since ebx is callee saved) before jumping to the
2713 // Note: The actual moving to ECX is done further down.
2714 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2715 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2716 !G->getGlobal()->hasProtectedVisibility())
2717 Callee = LowerGlobalAddress(Callee, DAG);
2718 else if (isa<ExternalSymbolSDNode>(Callee))
2719 Callee = LowerExternalSymbol(Callee, DAG);
2723 if (Is64Bit && isVarArg && !IsWin64) {
2724 // From AMD64 ABI document:
2725 // For calls that may call functions that use varargs or stdargs
2726 // (prototype-less calls or calls to functions containing ellipsis (...) in
2727 // the declaration) %al is used as hidden argument to specify the number
2728 // of SSE registers used. The contents of %al do not need to match exactly
2729 // the number of registers, but must be an ubound on the number of SSE
2730 // registers used and is in the range 0 - 8 inclusive.
2732 // Count the number of XMM registers allocated.
2733 static const uint16_t XMMArgRegs[] = {
2734 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2735 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2737 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2738 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2739 && "SSE registers cannot be used when SSE is disabled");
2741 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2742 DAG.getConstant(NumXMMRegs, MVT::i8)));
2745 // For tail calls lower the arguments to the 'real' stack slot.
2747 // Force all the incoming stack arguments to be loaded from the stack
2748 // before any new outgoing arguments are stored to the stack, because the
2749 // outgoing stack slots may alias the incoming argument stack slots, and
2750 // the alias isn't otherwise explicit. This is slightly more conservative
2751 // than necessary, because it means that each store effectively depends
2752 // on every argument instead of just those arguments it would clobber.
2753 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2755 SmallVector<SDValue, 8> MemOpChains2;
2758 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2759 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2760 CCValAssign &VA = ArgLocs[i];
2763 assert(VA.isMemLoc());
2764 SDValue Arg = OutVals[i];
2765 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2766 // Create frame index.
2767 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2768 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2769 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2770 FIN = DAG.getFrameIndex(FI, getPointerTy());
2772 if (Flags.isByVal()) {
2773 // Copy relative to framepointer.
2774 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2775 if (StackPtr.getNode() == 0)
2776 StackPtr = DAG.getCopyFromReg(Chain, dl,
2777 RegInfo->getStackRegister(),
2779 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2781 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2785 // Store relative to framepointer.
2786 MemOpChains2.push_back(
2787 DAG.getStore(ArgChain, dl, Arg, FIN,
2788 MachinePointerInfo::getFixedStack(FI),
2794 if (!MemOpChains2.empty())
2795 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2796 &MemOpChains2[0], MemOpChains2.size());
2798 // Store the return address to the appropriate stack slot.
2799 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2800 getPointerTy(), RegInfo->getSlotSize(),
2804 // Build a sequence of copy-to-reg nodes chained together with token chain
2805 // and flag operands which copy the outgoing args into registers.
2807 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2808 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2809 RegsToPass[i].second, InFlag);
2810 InFlag = Chain.getValue(1);
2813 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2814 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2815 // In the 64-bit large code model, we have to make all calls
2816 // through a register, since the call instruction's 32-bit
2817 // pc-relative offset may not be large enough to hold the whole
2819 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2820 // If the callee is a GlobalAddress node (quite common, every direct call
2821 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2824 // We should use extra load for direct calls to dllimported functions in
2826 const GlobalValue *GV = G->getGlobal();
2827 if (!GV->hasDLLImportStorageClass()) {
2828 unsigned char OpFlags = 0;
2829 bool ExtraLoad = false;
2830 unsigned WrapperKind = ISD::DELETED_NODE;
2832 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2833 // external symbols most go through the PLT in PIC mode. If the symbol
2834 // has hidden or protected visibility, or if it is static or local, then
2835 // we don't need to use the PLT - we can directly call it.
2836 if (Subtarget->isTargetELF() &&
2837 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2838 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2839 OpFlags = X86II::MO_PLT;
2840 } else if (Subtarget->isPICStyleStubAny() &&
2841 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2842 (!Subtarget->getTargetTriple().isMacOSX() ||
2843 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2844 // PC-relative references to external symbols should go through $stub,
2845 // unless we're building with the leopard linker or later, which
2846 // automatically synthesizes these stubs.
2847 OpFlags = X86II::MO_DARWIN_STUB;
2848 } else if (Subtarget->isPICStyleRIPRel() &&
2849 isa<Function>(GV) &&
2850 cast<Function>(GV)->getAttributes().
2851 hasAttribute(AttributeSet::FunctionIndex,
2852 Attribute::NonLazyBind)) {
2853 // If the function is marked as non-lazy, generate an indirect call
2854 // which loads from the GOT directly. This avoids runtime overhead
2855 // at the cost of eager binding (and one extra byte of encoding).
2856 OpFlags = X86II::MO_GOTPCREL;
2857 WrapperKind = X86ISD::WrapperRIP;
2861 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2862 G->getOffset(), OpFlags);
2864 // Add a wrapper if needed.
2865 if (WrapperKind != ISD::DELETED_NODE)
2866 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2867 // Add extra indirection if needed.
2869 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2870 MachinePointerInfo::getGOT(),
2871 false, false, false, 0);
2873 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2874 unsigned char OpFlags = 0;
2876 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2877 // external symbols should go through the PLT.
2878 if (Subtarget->isTargetELF() &&
2879 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2880 OpFlags = X86II::MO_PLT;
2881 } else if (Subtarget->isPICStyleStubAny() &&
2882 (!Subtarget->getTargetTriple().isMacOSX() ||
2883 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2884 // PC-relative references to external symbols should go through $stub,
2885 // unless we're building with the leopard linker or later, which
2886 // automatically synthesizes these stubs.
2887 OpFlags = X86II::MO_DARWIN_STUB;
2890 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2894 // Returns a chain & a flag for retval copy to use.
2895 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2896 SmallVector<SDValue, 8> Ops;
2898 if (!IsSibcall && isTailCall) {
2899 Chain = DAG.getCALLSEQ_END(Chain,
2900 DAG.getIntPtrConstant(NumBytesToPop, true),
2901 DAG.getIntPtrConstant(0, true), InFlag, dl);
2902 InFlag = Chain.getValue(1);
2905 Ops.push_back(Chain);
2906 Ops.push_back(Callee);
2909 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2911 // Add argument registers to the end of the list so that they are known live
2913 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2914 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2915 RegsToPass[i].second.getValueType()));
2917 // Add a register mask operand representing the call-preserved registers.
2918 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2919 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2920 assert(Mask && "Missing call preserved mask for calling convention");
2921 Ops.push_back(DAG.getRegisterMask(Mask));
2923 if (InFlag.getNode())
2924 Ops.push_back(InFlag);
2928 //// If this is the first return lowered for this function, add the regs
2929 //// to the liveout set for the function.
2930 // This isn't right, although it's probably harmless on x86; liveouts
2931 // should be computed from returns not tail calls. Consider a void
2932 // function making a tail call to a function returning int.
2933 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2936 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2937 InFlag = Chain.getValue(1);
2939 // Create the CALLSEQ_END node.
2940 unsigned NumBytesForCalleeToPop;
2941 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2942 getTargetMachine().Options.GuaranteedTailCallOpt))
2943 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2944 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2945 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2946 SR == StackStructReturn)
2947 // If this is a call to a struct-return function, the callee
2948 // pops the hidden struct pointer, so we have to push it back.
2949 // This is common for Darwin/X86, Linux & Mingw32 targets.
2950 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2951 NumBytesForCalleeToPop = 4;
2953 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2955 // Returns a flag for retval copy to use.
2957 Chain = DAG.getCALLSEQ_END(Chain,
2958 DAG.getIntPtrConstant(NumBytesToPop, true),
2959 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2962 InFlag = Chain.getValue(1);
2965 // Handle result values, copying them out of physregs into vregs that we
2967 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2968 Ins, dl, DAG, InVals);
2971 //===----------------------------------------------------------------------===//
2972 // Fast Calling Convention (tail call) implementation
2973 //===----------------------------------------------------------------------===//
2975 // Like std call, callee cleans arguments, convention except that ECX is
2976 // reserved for storing the tail called function address. Only 2 registers are
2977 // free for argument passing (inreg). Tail call optimization is performed
2979 // * tailcallopt is enabled
2980 // * caller/callee are fastcc
2981 // On X86_64 architecture with GOT-style position independent code only local
2982 // (within module) calls are supported at the moment.
2983 // To keep the stack aligned according to platform abi the function
2984 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2985 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2986 // If a tail called function callee has more arguments than the caller the
2987 // caller needs to make sure that there is room to move the RETADDR to. This is
2988 // achieved by reserving an area the size of the argument delta right after the
2989 // original REtADDR, but before the saved framepointer or the spilled registers
2990 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3002 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3003 /// for a 16 byte align requirement.
3005 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3006 SelectionDAG& DAG) const {
3007 MachineFunction &MF = DAG.getMachineFunction();
3008 const TargetMachine &TM = MF.getTarget();
3009 const X86RegisterInfo *RegInfo =
3010 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3011 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3012 unsigned StackAlignment = TFI.getStackAlignment();
3013 uint64_t AlignMask = StackAlignment - 1;
3014 int64_t Offset = StackSize;
3015 unsigned SlotSize = RegInfo->getSlotSize();
3016 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3017 // Number smaller than 12 so just add the difference.
3018 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3020 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3021 Offset = ((~AlignMask) & Offset) + StackAlignment +
3022 (StackAlignment-SlotSize);
3027 /// MatchingStackOffset - Return true if the given stack call argument is
3028 /// already available in the same position (relatively) of the caller's
3029 /// incoming argument stack.
3031 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3032 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3033 const X86InstrInfo *TII) {
3034 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3036 if (Arg.getOpcode() == ISD::CopyFromReg) {
3037 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3038 if (!TargetRegisterInfo::isVirtualRegister(VR))
3040 MachineInstr *Def = MRI->getVRegDef(VR);
3043 if (!Flags.isByVal()) {
3044 if (!TII->isLoadFromStackSlot(Def, FI))
3047 unsigned Opcode = Def->getOpcode();
3048 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3049 Def->getOperand(1).isFI()) {
3050 FI = Def->getOperand(1).getIndex();
3051 Bytes = Flags.getByValSize();
3055 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3056 if (Flags.isByVal())
3057 // ByVal argument is passed in as a pointer but it's now being
3058 // dereferenced. e.g.
3059 // define @foo(%struct.X* %A) {
3060 // tail call @bar(%struct.X* byval %A)
3063 SDValue Ptr = Ld->getBasePtr();
3064 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3067 FI = FINode->getIndex();
3068 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3069 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3070 FI = FINode->getIndex();
3071 Bytes = Flags.getByValSize();
3075 assert(FI != INT_MAX);
3076 if (!MFI->isFixedObjectIndex(FI))
3078 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3081 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3082 /// for tail call optimization. Targets which want to do tail call
3083 /// optimization should implement this function.
3085 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3086 CallingConv::ID CalleeCC,
3088 bool isCalleeStructRet,
3089 bool isCallerStructRet,
3091 const SmallVectorImpl<ISD::OutputArg> &Outs,
3092 const SmallVectorImpl<SDValue> &OutVals,
3093 const SmallVectorImpl<ISD::InputArg> &Ins,
3094 SelectionDAG &DAG) const {
3095 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3098 // If -tailcallopt is specified, make fastcc functions tail-callable.
3099 const MachineFunction &MF = DAG.getMachineFunction();
3100 const Function *CallerF = MF.getFunction();
3102 // If the function return type is x86_fp80 and the callee return type is not,
3103 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3104 // perform a tailcall optimization here.
3105 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3108 CallingConv::ID CallerCC = CallerF->getCallingConv();
3109 bool CCMatch = CallerCC == CalleeCC;
3110 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3111 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3113 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3114 if (IsTailCallConvention(CalleeCC) && CCMatch)
3119 // Look for obvious safe cases to perform tail call optimization that do not
3120 // require ABI changes. This is what gcc calls sibcall.
3122 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3123 // emit a special epilogue.
3124 const X86RegisterInfo *RegInfo =
3125 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3126 if (RegInfo->needsStackRealignment(MF))
3129 // Also avoid sibcall optimization if either caller or callee uses struct
3130 // return semantics.
3131 if (isCalleeStructRet || isCallerStructRet)
3134 // An stdcall/thiscall caller is expected to clean up its arguments; the
3135 // callee isn't going to do that.
3136 // FIXME: this is more restrictive than needed. We could produce a tailcall
3137 // when the stack adjustment matches. For example, with a thiscall that takes
3138 // only one argument.
3139 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3140 CallerCC == CallingConv::X86_ThisCall))
3143 // Do not sibcall optimize vararg calls unless all arguments are passed via
3145 if (isVarArg && !Outs.empty()) {
3147 // Optimizing for varargs on Win64 is unlikely to be safe without
3148 // additional testing.
3149 if (IsCalleeWin64 || IsCallerWin64)
3152 SmallVector<CCValAssign, 16> ArgLocs;
3153 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3154 getTargetMachine(), ArgLocs, *DAG.getContext());
3156 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3157 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3158 if (!ArgLocs[i].isRegLoc())
3162 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3163 // stack. Therefore, if it's not used by the call it is not safe to optimize
3164 // this into a sibcall.
3165 bool Unused = false;
3166 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3173 SmallVector<CCValAssign, 16> RVLocs;
3174 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3175 getTargetMachine(), RVLocs, *DAG.getContext());
3176 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3177 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3178 CCValAssign &VA = RVLocs[i];
3179 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3184 // If the calling conventions do not match, then we'd better make sure the
3185 // results are returned in the same way as what the caller expects.
3187 SmallVector<CCValAssign, 16> RVLocs1;
3188 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3189 getTargetMachine(), RVLocs1, *DAG.getContext());
3190 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3192 SmallVector<CCValAssign, 16> RVLocs2;
3193 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3194 getTargetMachine(), RVLocs2, *DAG.getContext());
3195 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3197 if (RVLocs1.size() != RVLocs2.size())
3199 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3200 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3202 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3204 if (RVLocs1[i].isRegLoc()) {
3205 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3208 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3214 // If the callee takes no arguments then go on to check the results of the
3216 if (!Outs.empty()) {
3217 // Check if stack adjustment is needed. For now, do not do this if any
3218 // argument is passed on the stack.
3219 SmallVector<CCValAssign, 16> ArgLocs;
3220 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3221 getTargetMachine(), ArgLocs, *DAG.getContext());
3223 // Allocate shadow area for Win64
3225 CCInfo.AllocateStack(32, 8);
3227 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3228 if (CCInfo.getNextStackOffset()) {
3229 MachineFunction &MF = DAG.getMachineFunction();
3230 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3233 // Check if the arguments are already laid out in the right way as
3234 // the caller's fixed stack objects.
3235 MachineFrameInfo *MFI = MF.getFrameInfo();
3236 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3237 const X86InstrInfo *TII =
3238 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3239 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3240 CCValAssign &VA = ArgLocs[i];
3241 SDValue Arg = OutVals[i];
3242 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3243 if (VA.getLocInfo() == CCValAssign::Indirect)
3245 if (!VA.isRegLoc()) {
3246 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3253 // If the tailcall address may be in a register, then make sure it's
3254 // possible to register allocate for it. In 32-bit, the call address can
3255 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3256 // callee-saved registers are restored. These happen to be the same
3257 // registers used to pass 'inreg' arguments so watch out for those.
3258 if (!Subtarget->is64Bit() &&
3259 ((!isa<GlobalAddressSDNode>(Callee) &&
3260 !isa<ExternalSymbolSDNode>(Callee)) ||
3261 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3262 unsigned NumInRegs = 0;
3263 // In PIC we need an extra register to formulate the address computation
3265 unsigned MaxInRegs =
3266 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3268 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3269 CCValAssign &VA = ArgLocs[i];
3272 unsigned Reg = VA.getLocReg();
3275 case X86::EAX: case X86::EDX: case X86::ECX:
3276 if (++NumInRegs == MaxInRegs)
3288 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3289 const TargetLibraryInfo *libInfo) const {
3290 return X86::createFastISel(funcInfo, libInfo);
3293 //===----------------------------------------------------------------------===//
3294 // Other Lowering Hooks
3295 //===----------------------------------------------------------------------===//
3297 static bool MayFoldLoad(SDValue Op) {
3298 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3301 static bool MayFoldIntoStore(SDValue Op) {
3302 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3305 static bool isTargetShuffle(unsigned Opcode) {
3307 default: return false;
3308 case X86ISD::PSHUFD:
3309 case X86ISD::PSHUFHW:
3310 case X86ISD::PSHUFLW:
3312 case X86ISD::PALIGNR:
3313 case X86ISD::MOVLHPS:
3314 case X86ISD::MOVLHPD:
3315 case X86ISD::MOVHLPS:
3316 case X86ISD::MOVLPS:
3317 case X86ISD::MOVLPD:
3318 case X86ISD::MOVSHDUP:
3319 case X86ISD::MOVSLDUP:
3320 case X86ISD::MOVDDUP:
3323 case X86ISD::UNPCKL:
3324 case X86ISD::UNPCKH:
3325 case X86ISD::VPERMILP:
3326 case X86ISD::VPERM2X128:
3327 case X86ISD::VPERMI:
3332 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3333 SDValue V1, SelectionDAG &DAG) {
3335 default: llvm_unreachable("Unknown x86 shuffle node");
3336 case X86ISD::MOVSHDUP:
3337 case X86ISD::MOVSLDUP:
3338 case X86ISD::MOVDDUP:
3339 return DAG.getNode(Opc, dl, VT, V1);
3343 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3344 SDValue V1, unsigned TargetMask,
3345 SelectionDAG &DAG) {
3347 default: llvm_unreachable("Unknown x86 shuffle node");
3348 case X86ISD::PSHUFD:
3349 case X86ISD::PSHUFHW:
3350 case X86ISD::PSHUFLW:
3351 case X86ISD::VPERMILP:
3352 case X86ISD::VPERMI:
3353 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3357 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3358 SDValue V1, SDValue V2, unsigned TargetMask,
3359 SelectionDAG &DAG) {
3361 default: llvm_unreachable("Unknown x86 shuffle node");
3362 case X86ISD::PALIGNR:
3364 case X86ISD::VPERM2X128:
3365 return DAG.getNode(Opc, dl, VT, V1, V2,
3366 DAG.getConstant(TargetMask, MVT::i8));
3370 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3371 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3373 default: llvm_unreachable("Unknown x86 shuffle node");
3374 case X86ISD::MOVLHPS:
3375 case X86ISD::MOVLHPD:
3376 case X86ISD::MOVHLPS:
3377 case X86ISD::MOVLPS:
3378 case X86ISD::MOVLPD:
3381 case X86ISD::UNPCKL:
3382 case X86ISD::UNPCKH:
3383 return DAG.getNode(Opc, dl, VT, V1, V2);
3387 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3388 MachineFunction &MF = DAG.getMachineFunction();
3389 const X86RegisterInfo *RegInfo =
3390 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3391 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3392 int ReturnAddrIndex = FuncInfo->getRAIndex();
3394 if (ReturnAddrIndex == 0) {
3395 // Set up a frame object for the return address.
3396 unsigned SlotSize = RegInfo->getSlotSize();
3397 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3400 FuncInfo->setRAIndex(ReturnAddrIndex);
3403 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3406 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3407 bool hasSymbolicDisplacement) {
3408 // Offset should fit into 32 bit immediate field.
3409 if (!isInt<32>(Offset))
3412 // If we don't have a symbolic displacement - we don't have any extra
3414 if (!hasSymbolicDisplacement)
3417 // FIXME: Some tweaks might be needed for medium code model.
3418 if (M != CodeModel::Small && M != CodeModel::Kernel)
3421 // For small code model we assume that latest object is 16MB before end of 31
3422 // bits boundary. We may also accept pretty large negative constants knowing
3423 // that all objects are in the positive half of address space.
3424 if (M == CodeModel::Small && Offset < 16*1024*1024)
3427 // For kernel code model we know that all object resist in the negative half
3428 // of 32bits address space. We may not accept negative offsets, since they may
3429 // be just off and we may accept pretty large positive ones.
3430 if (M == CodeModel::Kernel && Offset > 0)
3436 /// isCalleePop - Determines whether the callee is required to pop its
3437 /// own arguments. Callee pop is necessary to support tail calls.
3438 bool X86::isCalleePop(CallingConv::ID CallingConv,
3439 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3443 switch (CallingConv) {
3446 case CallingConv::X86_StdCall:
3448 case CallingConv::X86_FastCall:
3450 case CallingConv::X86_ThisCall:
3452 case CallingConv::Fast:
3454 case CallingConv::GHC:
3456 case CallingConv::HiPE:
3461 /// \brief Return true if the condition is an unsigned comparison operation.
3462 static bool isX86CCUnsigned(unsigned X86CC) {
3464 default: llvm_unreachable("Invalid integer condition!");
3465 case X86::COND_E: return true;
3466 case X86::COND_G: return false;
3467 case X86::COND_GE: return false;
3468 case X86::COND_L: return false;
3469 case X86::COND_LE: return false;
3470 case X86::COND_NE: return true;
3471 case X86::COND_B: return true;
3472 case X86::COND_A: return true;
3473 case X86::COND_BE: return true;
3474 case X86::COND_AE: return true;
3476 llvm_unreachable("covered switch fell through?!");
3479 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3480 /// specific condition code, returning the condition code and the LHS/RHS of the
3481 /// comparison to make.
3482 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3483 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3485 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3486 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3487 // X > -1 -> X == 0, jump !sign.
3488 RHS = DAG.getConstant(0, RHS.getValueType());
3489 return X86::COND_NS;
3491 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3492 // X < 0 -> X == 0, jump on sign.
3495 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3497 RHS = DAG.getConstant(0, RHS.getValueType());
3498 return X86::COND_LE;
3502 switch (SetCCOpcode) {
3503 default: llvm_unreachable("Invalid integer condition!");
3504 case ISD::SETEQ: return X86::COND_E;
3505 case ISD::SETGT: return X86::COND_G;
3506 case ISD::SETGE: return X86::COND_GE;
3507 case ISD::SETLT: return X86::COND_L;
3508 case ISD::SETLE: return X86::COND_LE;
3509 case ISD::SETNE: return X86::COND_NE;
3510 case ISD::SETULT: return X86::COND_B;
3511 case ISD::SETUGT: return X86::COND_A;
3512 case ISD::SETULE: return X86::COND_BE;
3513 case ISD::SETUGE: return X86::COND_AE;
3517 // First determine if it is required or is profitable to flip the operands.
3519 // If LHS is a foldable load, but RHS is not, flip the condition.
3520 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3521 !ISD::isNON_EXTLoad(RHS.getNode())) {
3522 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3523 std::swap(LHS, RHS);
3526 switch (SetCCOpcode) {
3532 std::swap(LHS, RHS);
3536 // On a floating point condition, the flags are set as follows:
3538 // 0 | 0 | 0 | X > Y
3539 // 0 | 0 | 1 | X < Y
3540 // 1 | 0 | 0 | X == Y
3541 // 1 | 1 | 1 | unordered
3542 switch (SetCCOpcode) {
3543 default: llvm_unreachable("Condcode should be pre-legalized away");
3545 case ISD::SETEQ: return X86::COND_E;
3546 case ISD::SETOLT: // flipped
3548 case ISD::SETGT: return X86::COND_A;
3549 case ISD::SETOLE: // flipped
3551 case ISD::SETGE: return X86::COND_AE;
3552 case ISD::SETUGT: // flipped
3554 case ISD::SETLT: return X86::COND_B;
3555 case ISD::SETUGE: // flipped
3557 case ISD::SETLE: return X86::COND_BE;
3559 case ISD::SETNE: return X86::COND_NE;
3560 case ISD::SETUO: return X86::COND_P;
3561 case ISD::SETO: return X86::COND_NP;
3563 case ISD::SETUNE: return X86::COND_INVALID;
3567 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3568 /// code. Current x86 isa includes the following FP cmov instructions:
3569 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3570 static bool hasFPCMov(unsigned X86CC) {
3586 /// isFPImmLegal - Returns true if the target can instruction select the
3587 /// specified FP immediate natively. If false, the legalizer will
3588 /// materialize the FP immediate as a load from a constant pool.
3589 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3590 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3591 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3597 /// \brief Returns true if it is beneficial to convert a load of a constant
3598 /// to just the constant itself.
3599 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3601 assert(Ty->isIntegerTy());
3603 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3604 if (BitSize == 0 || BitSize > 64)
3609 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3610 /// the specified range (L, H].
3611 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3612 return (Val < 0) || (Val >= Low && Val < Hi);
3615 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3616 /// specified value.
3617 static bool isUndefOrEqual(int Val, int CmpVal) {
3618 return (Val < 0 || Val == CmpVal);
3621 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3622 /// from position Pos and ending in Pos+Size, falls within the specified
3623 /// sequential range (L, L+Pos]. or is undef.
3624 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3625 unsigned Pos, unsigned Size, int Low) {
3626 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3627 if (!isUndefOrEqual(Mask[i], Low))
3632 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3633 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3634 /// the second operand.
3635 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3636 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3637 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3638 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3639 return (Mask[0] < 2 && Mask[1] < 2);
3643 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3644 /// is suitable for input to PSHUFHW.
3645 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3646 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3649 // Lower quadword copied in order or undef.
3650 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3653 // Upper quadword shuffled.
3654 for (unsigned i = 4; i != 8; ++i)
3655 if (!isUndefOrInRange(Mask[i], 4, 8))
3658 if (VT == MVT::v16i16) {
3659 // Lower quadword copied in order or undef.
3660 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3663 // Upper quadword shuffled.
3664 for (unsigned i = 12; i != 16; ++i)
3665 if (!isUndefOrInRange(Mask[i], 12, 16))
3672 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3673 /// is suitable for input to PSHUFLW.
3674 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3675 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3678 // Upper quadword copied in order.
3679 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3682 // Lower quadword shuffled.
3683 for (unsigned i = 0; i != 4; ++i)
3684 if (!isUndefOrInRange(Mask[i], 0, 4))
3687 if (VT == MVT::v16i16) {
3688 // Upper quadword copied in order.
3689 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3692 // Lower quadword shuffled.
3693 for (unsigned i = 8; i != 12; ++i)
3694 if (!isUndefOrInRange(Mask[i], 8, 12))
3701 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3702 /// is suitable for input to PALIGNR.
3703 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3704 const X86Subtarget *Subtarget) {
3705 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3706 (VT.is256BitVector() && !Subtarget->hasInt256()))
3709 unsigned NumElts = VT.getVectorNumElements();
3710 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3711 unsigned NumLaneElts = NumElts/NumLanes;
3713 // Do not handle 64-bit element shuffles with palignr.
3714 if (NumLaneElts == 2)
3717 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3719 for (i = 0; i != NumLaneElts; ++i) {
3724 // Lane is all undef, go to next lane
3725 if (i == NumLaneElts)
3728 int Start = Mask[i+l];
3730 // Make sure its in this lane in one of the sources
3731 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3732 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3735 // If not lane 0, then we must match lane 0
3736 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3739 // Correct second source to be contiguous with first source
3740 if (Start >= (int)NumElts)
3741 Start -= NumElts - NumLaneElts;
3743 // Make sure we're shifting in the right direction.
3744 if (Start <= (int)(i+l))
3749 // Check the rest of the elements to see if they are consecutive.
3750 for (++i; i != NumLaneElts; ++i) {
3751 int Idx = Mask[i+l];
3753 // Make sure its in this lane
3754 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3755 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3758 // If not lane 0, then we must match lane 0
3759 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3762 if (Idx >= (int)NumElts)
3763 Idx -= NumElts - NumLaneElts;
3765 if (!isUndefOrEqual(Idx, Start+i))
3774 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3775 /// the two vector operands have swapped position.
3776 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3777 unsigned NumElems) {
3778 for (unsigned i = 0; i != NumElems; ++i) {
3782 else if (idx < (int)NumElems)
3783 Mask[i] = idx + NumElems;
3785 Mask[i] = idx - NumElems;
3789 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3790 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3791 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3792 /// reverse of what x86 shuffles want.
3793 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3795 unsigned NumElems = VT.getVectorNumElements();
3796 unsigned NumLanes = VT.getSizeInBits()/128;
3797 unsigned NumLaneElems = NumElems/NumLanes;
3799 if (NumLaneElems != 2 && NumLaneElems != 4)
3802 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3803 bool symetricMaskRequired =
3804 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3806 // VSHUFPSY divides the resulting vector into 4 chunks.
3807 // The sources are also splitted into 4 chunks, and each destination
3808 // chunk must come from a different source chunk.
3810 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3811 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3813 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3814 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3816 // VSHUFPDY divides the resulting vector into 4 chunks.
3817 // The sources are also splitted into 4 chunks, and each destination
3818 // chunk must come from a different source chunk.
3820 // SRC1 => X3 X2 X1 X0
3821 // SRC2 => Y3 Y2 Y1 Y0
3823 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3825 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3826 unsigned HalfLaneElems = NumLaneElems/2;
3827 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3828 for (unsigned i = 0; i != NumLaneElems; ++i) {
3829 int Idx = Mask[i+l];
3830 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3831 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3833 // For VSHUFPSY, the mask of the second half must be the same as the
3834 // first but with the appropriate offsets. This works in the same way as
3835 // VPERMILPS works with masks.
3836 if (!symetricMaskRequired || Idx < 0)
3838 if (MaskVal[i] < 0) {
3839 MaskVal[i] = Idx - l;
3842 if ((signed)(Idx - l) != MaskVal[i])
3850 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3851 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3852 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3853 if (!VT.is128BitVector())
3856 unsigned NumElems = VT.getVectorNumElements();
3861 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3862 return isUndefOrEqual(Mask[0], 6) &&
3863 isUndefOrEqual(Mask[1], 7) &&
3864 isUndefOrEqual(Mask[2], 2) &&
3865 isUndefOrEqual(Mask[3], 3);
3868 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3869 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3871 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3872 if (!VT.is128BitVector())
3875 unsigned NumElems = VT.getVectorNumElements();
3880 return isUndefOrEqual(Mask[0], 2) &&
3881 isUndefOrEqual(Mask[1], 3) &&
3882 isUndefOrEqual(Mask[2], 2) &&
3883 isUndefOrEqual(Mask[3], 3);
3886 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3887 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3888 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3889 if (!VT.is128BitVector())
3892 unsigned NumElems = VT.getVectorNumElements();
3894 if (NumElems != 2 && NumElems != 4)
3897 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3898 if (!isUndefOrEqual(Mask[i], i + NumElems))
3901 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3902 if (!isUndefOrEqual(Mask[i], i))
3908 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3909 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3910 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3911 if (!VT.is128BitVector())
3914 unsigned NumElems = VT.getVectorNumElements();
3916 if (NumElems != 2 && NumElems != 4)
3919 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3920 if (!isUndefOrEqual(Mask[i], i))
3923 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3924 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3931 // Some special combinations that can be optimized.
3934 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3935 SelectionDAG &DAG) {
3936 MVT VT = SVOp->getSimpleValueType(0);
3939 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3942 ArrayRef<int> Mask = SVOp->getMask();
3944 // These are the special masks that may be optimized.
3945 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3946 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3947 bool MatchEvenMask = true;
3948 bool MatchOddMask = true;
3949 for (int i=0; i<8; ++i) {
3950 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3951 MatchEvenMask = false;
3952 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3953 MatchOddMask = false;
3956 if (!MatchEvenMask && !MatchOddMask)
3959 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3961 SDValue Op0 = SVOp->getOperand(0);
3962 SDValue Op1 = SVOp->getOperand(1);
3964 if (MatchEvenMask) {
3965 // Shift the second operand right to 32 bits.
3966 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3967 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3969 // Shift the first operand left to 32 bits.
3970 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3971 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3973 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3974 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3977 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3978 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3979 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3980 bool HasInt256, bool V2IsSplat = false) {
3982 assert(VT.getSizeInBits() >= 128 &&
3983 "Unsupported vector type for unpckl");
3985 // AVX defines UNPCK* to operate independently on 128-bit lanes.
3987 unsigned NumOf256BitLanes;
3988 unsigned NumElts = VT.getVectorNumElements();
3989 if (VT.is256BitVector()) {
3990 if (NumElts != 4 && NumElts != 8 &&
3991 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3994 NumOf256BitLanes = 1;
3995 } else if (VT.is512BitVector()) {
3996 assert(VT.getScalarType().getSizeInBits() >= 32 &&
3997 "Unsupported vector type for unpckh");
3999 NumOf256BitLanes = 2;
4002 NumOf256BitLanes = 1;
4005 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4006 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4008 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4009 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4010 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4011 int BitI = Mask[l256*NumEltsInStride+l+i];
4012 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4013 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4015 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4017 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4025 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4026 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4027 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4028 bool HasInt256, bool V2IsSplat = false) {
4029 assert(VT.getSizeInBits() >= 128 &&
4030 "Unsupported vector type for unpckh");
4032 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4034 unsigned NumOf256BitLanes;
4035 unsigned NumElts = VT.getVectorNumElements();
4036 if (VT.is256BitVector()) {
4037 if (NumElts != 4 && NumElts != 8 &&
4038 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4041 NumOf256BitLanes = 1;
4042 } else if (VT.is512BitVector()) {
4043 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4044 "Unsupported vector type for unpckh");
4046 NumOf256BitLanes = 2;
4049 NumOf256BitLanes = 1;
4052 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4053 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4055 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4056 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4057 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4058 int BitI = Mask[l256*NumEltsInStride+l+i];
4059 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4060 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4062 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4064 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4072 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4073 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4075 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4076 unsigned NumElts = VT.getVectorNumElements();
4077 bool Is256BitVec = VT.is256BitVector();
4079 if (VT.is512BitVector())
4081 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4082 "Unsupported vector type for unpckh");
4084 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4085 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4088 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4089 // FIXME: Need a better way to get rid of this, there's no latency difference
4090 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4091 // the former later. We should also remove the "_undef" special mask.
4092 if (NumElts == 4 && Is256BitVec)
4095 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4096 // independently on 128-bit lanes.
4097 unsigned NumLanes = VT.getSizeInBits()/128;
4098 unsigned NumLaneElts = NumElts/NumLanes;
4100 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4101 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4102 int BitI = Mask[l+i];
4103 int BitI1 = Mask[l+i+1];
4105 if (!isUndefOrEqual(BitI, j))
4107 if (!isUndefOrEqual(BitI1, j))
4115 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4116 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4118 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4119 unsigned NumElts = VT.getVectorNumElements();
4121 if (VT.is512BitVector())
4124 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4125 "Unsupported vector type for unpckh");
4127 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4128 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4131 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4132 // independently on 128-bit lanes.
4133 unsigned NumLanes = VT.getSizeInBits()/128;
4134 unsigned NumLaneElts = NumElts/NumLanes;
4136 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4137 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4138 int BitI = Mask[l+i];
4139 int BitI1 = Mask[l+i+1];
4140 if (!isUndefOrEqual(BitI, j))
4142 if (!isUndefOrEqual(BitI1, j))
4149 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4150 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4151 /// MOVSD, and MOVD, i.e. setting the lowest element.
4152 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4153 if (VT.getVectorElementType().getSizeInBits() < 32)
4155 if (!VT.is128BitVector())
4158 unsigned NumElts = VT.getVectorNumElements();
4160 if (!isUndefOrEqual(Mask[0], NumElts))
4163 for (unsigned i = 1; i != NumElts; ++i)
4164 if (!isUndefOrEqual(Mask[i], i))
4170 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4171 /// as permutations between 128-bit chunks or halves. As an example: this
4173 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4174 /// The first half comes from the second half of V1 and the second half from the
4175 /// the second half of V2.
4176 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4177 if (!HasFp256 || !VT.is256BitVector())
4180 // The shuffle result is divided into half A and half B. In total the two
4181 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4182 // B must come from C, D, E or F.
4183 unsigned HalfSize = VT.getVectorNumElements()/2;
4184 bool MatchA = false, MatchB = false;
4186 // Check if A comes from one of C, D, E, F.
4187 for (unsigned Half = 0; Half != 4; ++Half) {
4188 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4194 // Check if B comes from one of C, D, E, F.
4195 for (unsigned Half = 0; Half != 4; ++Half) {
4196 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4202 return MatchA && MatchB;
4205 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4206 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4207 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4208 MVT VT = SVOp->getSimpleValueType(0);
4210 unsigned HalfSize = VT.getVectorNumElements()/2;
4212 unsigned FstHalf = 0, SndHalf = 0;
4213 for (unsigned i = 0; i < HalfSize; ++i) {
4214 if (SVOp->getMaskElt(i) > 0) {
4215 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4219 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4220 if (SVOp->getMaskElt(i) > 0) {
4221 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4226 return (FstHalf | (SndHalf << 4));
4229 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4230 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4231 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4235 unsigned NumElts = VT.getVectorNumElements();
4237 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4238 for (unsigned i = 0; i != NumElts; ++i) {
4241 Imm8 |= Mask[i] << (i*2);
4246 unsigned LaneSize = 4;
4247 SmallVector<int, 4> MaskVal(LaneSize, -1);
4249 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4250 for (unsigned i = 0; i != LaneSize; ++i) {
4251 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4255 if (MaskVal[i] < 0) {
4256 MaskVal[i] = Mask[i+l] - l;
4257 Imm8 |= MaskVal[i] << (i*2);
4260 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4267 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4268 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4269 /// Note that VPERMIL mask matching is different depending whether theunderlying
4270 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4271 /// to the same elements of the low, but to the higher half of the source.
4272 /// In VPERMILPD the two lanes could be shuffled independently of each other
4273 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4274 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4275 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4276 if (VT.getSizeInBits() < 256 || EltSize < 32)
4278 bool symetricMaskRequired = (EltSize == 32);
4279 unsigned NumElts = VT.getVectorNumElements();
4281 unsigned NumLanes = VT.getSizeInBits()/128;
4282 unsigned LaneSize = NumElts/NumLanes;
4283 // 2 or 4 elements in one lane
4285 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4286 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4287 for (unsigned i = 0; i != LaneSize; ++i) {
4288 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4290 if (symetricMaskRequired) {
4291 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4292 ExpectedMaskVal[i] = Mask[i+l] - l;
4295 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4303 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4304 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4305 /// element of vector 2 and the other elements to come from vector 1 in order.
4306 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4307 bool V2IsSplat = false, bool V2IsUndef = false) {
4308 if (!VT.is128BitVector())
4311 unsigned NumOps = VT.getVectorNumElements();
4312 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4315 if (!isUndefOrEqual(Mask[0], 0))
4318 for (unsigned i = 1; i != NumOps; ++i)
4319 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4320 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4321 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4327 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4328 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4329 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4330 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4331 const X86Subtarget *Subtarget) {
4332 if (!Subtarget->hasSSE3())
4335 unsigned NumElems = VT.getVectorNumElements();
4337 if ((VT.is128BitVector() && NumElems != 4) ||
4338 (VT.is256BitVector() && NumElems != 8) ||
4339 (VT.is512BitVector() && NumElems != 16))
4342 // "i+1" is the value the indexed mask element must have
4343 for (unsigned i = 0; i != NumElems; i += 2)
4344 if (!isUndefOrEqual(Mask[i], i+1) ||
4345 !isUndefOrEqual(Mask[i+1], i+1))
4351 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4352 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4353 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4354 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4355 const X86Subtarget *Subtarget) {
4356 if (!Subtarget->hasSSE3())
4359 unsigned NumElems = VT.getVectorNumElements();
4361 if ((VT.is128BitVector() && NumElems != 4) ||
4362 (VT.is256BitVector() && NumElems != 8) ||
4363 (VT.is512BitVector() && NumElems != 16))
4366 // "i" is the value the indexed mask element must have
4367 for (unsigned i = 0; i != NumElems; i += 2)
4368 if (!isUndefOrEqual(Mask[i], i) ||
4369 !isUndefOrEqual(Mask[i+1], i))
4375 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4376 /// specifies a shuffle of elements that is suitable for input to 256-bit
4377 /// version of MOVDDUP.
4378 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4379 if (!HasFp256 || !VT.is256BitVector())
4382 unsigned NumElts = VT.getVectorNumElements();
4386 for (unsigned i = 0; i != NumElts/2; ++i)
4387 if (!isUndefOrEqual(Mask[i], 0))
4389 for (unsigned i = NumElts/2; i != NumElts; ++i)
4390 if (!isUndefOrEqual(Mask[i], NumElts/2))
4395 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4396 /// specifies a shuffle of elements that is suitable for input to 128-bit
4397 /// version of MOVDDUP.
4398 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4399 if (!VT.is128BitVector())
4402 unsigned e = VT.getVectorNumElements() / 2;
4403 for (unsigned i = 0; i != e; ++i)
4404 if (!isUndefOrEqual(Mask[i], i))
4406 for (unsigned i = 0; i != e; ++i)
4407 if (!isUndefOrEqual(Mask[e+i], i))
4412 /// isVEXTRACTIndex - Return true if the specified
4413 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4414 /// suitable for instruction that extract 128 or 256 bit vectors
4415 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4416 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4417 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4420 // The index should be aligned on a vecWidth-bit boundary.
4422 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4424 MVT VT = N->getSimpleValueType(0);
4425 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4426 bool Result = (Index * ElSize) % vecWidth == 0;
4431 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4432 /// operand specifies a subvector insert that is suitable for input to
4433 /// insertion of 128 or 256-bit subvectors
4434 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4435 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4436 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4438 // The index should be aligned on a vecWidth-bit boundary.
4440 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4442 MVT VT = N->getSimpleValueType(0);
4443 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4444 bool Result = (Index * ElSize) % vecWidth == 0;
4449 bool X86::isVINSERT128Index(SDNode *N) {
4450 return isVINSERTIndex(N, 128);
4453 bool X86::isVINSERT256Index(SDNode *N) {
4454 return isVINSERTIndex(N, 256);
4457 bool X86::isVEXTRACT128Index(SDNode *N) {
4458 return isVEXTRACTIndex(N, 128);
4461 bool X86::isVEXTRACT256Index(SDNode *N) {
4462 return isVEXTRACTIndex(N, 256);
4465 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4466 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4467 /// Handles 128-bit and 256-bit.
4468 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4469 MVT VT = N->getSimpleValueType(0);
4471 assert((VT.getSizeInBits() >= 128) &&
4472 "Unsupported vector type for PSHUF/SHUFP");
4474 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4475 // independently on 128-bit lanes.
4476 unsigned NumElts = VT.getVectorNumElements();
4477 unsigned NumLanes = VT.getSizeInBits()/128;
4478 unsigned NumLaneElts = NumElts/NumLanes;
4480 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4481 "Only supports 2, 4 or 8 elements per lane");
4483 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4485 for (unsigned i = 0; i != NumElts; ++i) {
4486 int Elt = N->getMaskElt(i);
4487 if (Elt < 0) continue;
4488 Elt &= NumLaneElts - 1;
4489 unsigned ShAmt = (i << Shift) % 8;
4490 Mask |= Elt << ShAmt;
4496 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4497 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4498 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4499 MVT VT = N->getSimpleValueType(0);
4501 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4502 "Unsupported vector type for PSHUFHW");
4504 unsigned NumElts = VT.getVectorNumElements();
4507 for (unsigned l = 0; l != NumElts; l += 8) {
4508 // 8 nodes per lane, but we only care about the last 4.
4509 for (unsigned i = 0; i < 4; ++i) {
4510 int Elt = N->getMaskElt(l+i+4);
4511 if (Elt < 0) continue;
4512 Elt &= 0x3; // only 2-bits.
4513 Mask |= Elt << (i * 2);
4520 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4521 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4522 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4523 MVT VT = N->getSimpleValueType(0);
4525 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4526 "Unsupported vector type for PSHUFHW");
4528 unsigned NumElts = VT.getVectorNumElements();
4531 for (unsigned l = 0; l != NumElts; l += 8) {
4532 // 8 nodes per lane, but we only care about the first 4.
4533 for (unsigned i = 0; i < 4; ++i) {
4534 int Elt = N->getMaskElt(l+i);
4535 if (Elt < 0) continue;
4536 Elt &= 0x3; // only 2-bits
4537 Mask |= Elt << (i * 2);
4544 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4545 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4546 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4547 MVT VT = SVOp->getSimpleValueType(0);
4548 unsigned EltSize = VT.is512BitVector() ? 1 :
4549 VT.getVectorElementType().getSizeInBits() >> 3;
4551 unsigned NumElts = VT.getVectorNumElements();
4552 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4553 unsigned NumLaneElts = NumElts/NumLanes;
4557 for (i = 0; i != NumElts; ++i) {
4558 Val = SVOp->getMaskElt(i);
4562 if (Val >= (int)NumElts)
4563 Val -= NumElts - NumLaneElts;
4565 assert(Val - i > 0 && "PALIGNR imm should be positive");
4566 return (Val - i) * EltSize;
4569 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4570 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4571 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4572 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4575 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4577 MVT VecVT = N->getOperand(0).getSimpleValueType();
4578 MVT ElVT = VecVT.getVectorElementType();
4580 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4581 return Index / NumElemsPerChunk;
4584 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4585 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4586 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4587 llvm_unreachable("Illegal insert subvector for VINSERT");
4590 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4592 MVT VecVT = N->getSimpleValueType(0);
4593 MVT ElVT = VecVT.getVectorElementType();
4595 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4596 return Index / NumElemsPerChunk;
4599 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4600 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4601 /// and VINSERTI128 instructions.
4602 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4603 return getExtractVEXTRACTImmediate(N, 128);
4606 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4607 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4608 /// and VINSERTI64x4 instructions.
4609 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4610 return getExtractVEXTRACTImmediate(N, 256);
4613 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4614 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4615 /// and VINSERTI128 instructions.
4616 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4617 return getInsertVINSERTImmediate(N, 128);
4620 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4621 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4622 /// and VINSERTI64x4 instructions.
4623 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4624 return getInsertVINSERTImmediate(N, 256);
4627 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4629 bool X86::isZeroNode(SDValue Elt) {
4630 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4631 return CN->isNullValue();
4632 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4633 return CFP->getValueAPF().isPosZero();
4637 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4638 /// their permute mask.
4639 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4640 SelectionDAG &DAG) {
4641 MVT VT = SVOp->getSimpleValueType(0);
4642 unsigned NumElems = VT.getVectorNumElements();
4643 SmallVector<int, 8> MaskVec;
4645 for (unsigned i = 0; i != NumElems; ++i) {
4646 int Idx = SVOp->getMaskElt(i);
4648 if (Idx < (int)NumElems)
4653 MaskVec.push_back(Idx);
4655 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4656 SVOp->getOperand(0), &MaskVec[0]);
4659 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4660 /// match movhlps. The lower half elements should come from upper half of
4661 /// V1 (and in order), and the upper half elements should come from the upper
4662 /// half of V2 (and in order).
4663 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4664 if (!VT.is128BitVector())
4666 if (VT.getVectorNumElements() != 4)
4668 for (unsigned i = 0, e = 2; i != e; ++i)
4669 if (!isUndefOrEqual(Mask[i], i+2))
4671 for (unsigned i = 2; i != 4; ++i)
4672 if (!isUndefOrEqual(Mask[i], i+4))
4677 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4678 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4680 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4681 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4683 N = N->getOperand(0).getNode();
4684 if (!ISD::isNON_EXTLoad(N))
4687 *LD = cast<LoadSDNode>(N);
4691 // Test whether the given value is a vector value which will be legalized
4693 static bool WillBeConstantPoolLoad(SDNode *N) {
4694 if (N->getOpcode() != ISD::BUILD_VECTOR)
4697 // Check for any non-constant elements.
4698 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4699 switch (N->getOperand(i).getNode()->getOpcode()) {
4701 case ISD::ConstantFP:
4708 // Vectors of all-zeros and all-ones are materialized with special
4709 // instructions rather than being loaded.
4710 return !ISD::isBuildVectorAllZeros(N) &&
4711 !ISD::isBuildVectorAllOnes(N);
4714 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4715 /// match movlp{s|d}. The lower half elements should come from lower half of
4716 /// V1 (and in order), and the upper half elements should come from the upper
4717 /// half of V2 (and in order). And since V1 will become the source of the
4718 /// MOVLP, it must be either a vector load or a scalar load to vector.
4719 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4720 ArrayRef<int> Mask, MVT VT) {
4721 if (!VT.is128BitVector())
4724 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4726 // Is V2 is a vector load, don't do this transformation. We will try to use
4727 // load folding shufps op.
4728 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4731 unsigned NumElems = VT.getVectorNumElements();
4733 if (NumElems != 2 && NumElems != 4)
4735 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4736 if (!isUndefOrEqual(Mask[i], i))
4738 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4739 if (!isUndefOrEqual(Mask[i], i+NumElems))
4744 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4746 static bool isSplatVector(SDNode *N) {
4747 if (N->getOpcode() != ISD::BUILD_VECTOR)
4750 SDValue SplatValue = N->getOperand(0);
4751 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4752 if (N->getOperand(i) != SplatValue)
4757 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4758 /// to an zero vector.
4759 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4760 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4761 SDValue V1 = N->getOperand(0);
4762 SDValue V2 = N->getOperand(1);
4763 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4764 for (unsigned i = 0; i != NumElems; ++i) {
4765 int Idx = N->getMaskElt(i);
4766 if (Idx >= (int)NumElems) {
4767 unsigned Opc = V2.getOpcode();
4768 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4770 if (Opc != ISD::BUILD_VECTOR ||
4771 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4773 } else if (Idx >= 0) {
4774 unsigned Opc = V1.getOpcode();
4775 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4777 if (Opc != ISD::BUILD_VECTOR ||
4778 !X86::isZeroNode(V1.getOperand(Idx)))
4785 /// getZeroVector - Returns a vector of specified type with all zero elements.
4787 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4788 SelectionDAG &DAG, SDLoc dl) {
4789 assert(VT.isVector() && "Expected a vector type");
4791 // Always build SSE zero vectors as <4 x i32> bitcasted
4792 // to their dest type. This ensures they get CSE'd.
4794 if (VT.is128BitVector()) { // SSE
4795 if (Subtarget->hasSSE2()) { // SSE2
4796 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4797 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4799 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4800 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4802 } else if (VT.is256BitVector()) { // AVX
4803 if (Subtarget->hasInt256()) { // AVX2
4804 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4805 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4806 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4807 array_lengthof(Ops));
4809 // 256-bit logic and arithmetic instructions in AVX are all
4810 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4811 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4812 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4813 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4814 array_lengthof(Ops));
4816 } else if (VT.is512BitVector()) { // AVX-512
4817 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4818 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4819 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4820 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4821 } else if (VT.getScalarType() == MVT::i1) {
4822 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4823 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4824 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4825 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4826 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4827 Ops, VT.getVectorNumElements());
4829 llvm_unreachable("Unexpected vector type");
4831 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4834 /// getOnesVector - Returns a vector of specified type with all bits set.
4835 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4836 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4837 /// Then bitcast to their original type, ensuring they get CSE'd.
4838 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4840 assert(VT.isVector() && "Expected a vector type");
4842 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4844 if (VT.is256BitVector()) {
4845 if (HasInt256) { // AVX2
4846 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4847 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4848 array_lengthof(Ops));
4850 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4851 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4853 } else if (VT.is128BitVector()) {
4854 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4856 llvm_unreachable("Unexpected vector type");
4858 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4861 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4862 /// that point to V2 points to its first element.
4863 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4864 for (unsigned i = 0; i != NumElems; ++i) {
4865 if (Mask[i] > (int)NumElems) {
4871 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4872 /// operation of specified width.
4873 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4875 unsigned NumElems = VT.getVectorNumElements();
4876 SmallVector<int, 8> Mask;
4877 Mask.push_back(NumElems);
4878 for (unsigned i = 1; i != NumElems; ++i)
4880 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4883 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4884 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4886 unsigned NumElems = VT.getVectorNumElements();
4887 SmallVector<int, 8> Mask;
4888 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4890 Mask.push_back(i + NumElems);
4892 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4895 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4896 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4898 unsigned NumElems = VT.getVectorNumElements();
4899 SmallVector<int, 8> Mask;
4900 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4901 Mask.push_back(i + Half);
4902 Mask.push_back(i + NumElems + Half);
4904 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4907 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4908 // a generic shuffle instruction because the target has no such instructions.
4909 // Generate shuffles which repeat i16 and i8 several times until they can be
4910 // represented by v4f32 and then be manipulated by target suported shuffles.
4911 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4912 MVT VT = V.getSimpleValueType();
4913 int NumElems = VT.getVectorNumElements();
4916 while (NumElems > 4) {
4917 if (EltNo < NumElems/2) {
4918 V = getUnpackl(DAG, dl, VT, V, V);
4920 V = getUnpackh(DAG, dl, VT, V, V);
4921 EltNo -= NumElems/2;
4928 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4929 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4930 MVT VT = V.getSimpleValueType();
4933 if (VT.is128BitVector()) {
4934 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4935 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4936 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4938 } else if (VT.is256BitVector()) {
4939 // To use VPERMILPS to splat scalars, the second half of indicies must
4940 // refer to the higher part, which is a duplication of the lower one,
4941 // because VPERMILPS can only handle in-lane permutations.
4942 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4943 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4945 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4946 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4949 llvm_unreachable("Vector size not supported");
4951 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4954 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4955 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4956 MVT SrcVT = SV->getSimpleValueType(0);
4957 SDValue V1 = SV->getOperand(0);
4960 int EltNo = SV->getSplatIndex();
4961 int NumElems = SrcVT.getVectorNumElements();
4962 bool Is256BitVec = SrcVT.is256BitVector();
4964 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4965 "Unknown how to promote splat for type");
4967 // Extract the 128-bit part containing the splat element and update
4968 // the splat element index when it refers to the higher register.
4970 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4971 if (EltNo >= NumElems/2)
4972 EltNo -= NumElems/2;
4975 // All i16 and i8 vector types can't be used directly by a generic shuffle
4976 // instruction because the target has no such instruction. Generate shuffles
4977 // which repeat i16 and i8 several times until they fit in i32, and then can
4978 // be manipulated by target suported shuffles.
4979 MVT EltVT = SrcVT.getVectorElementType();
4980 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4981 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4983 // Recreate the 256-bit vector and place the same 128-bit vector
4984 // into the low and high part. This is necessary because we want
4985 // to use VPERM* to shuffle the vectors
4987 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4990 return getLegalSplat(DAG, V1, EltNo);
4993 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4994 /// vector of zero or undef vector. This produces a shuffle where the low
4995 /// element of V2 is swizzled into the zero/undef vector, landing at element
4996 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4997 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4999 const X86Subtarget *Subtarget,
5000 SelectionDAG &DAG) {
5001 MVT VT = V2.getSimpleValueType();
5003 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5004 unsigned NumElems = VT.getVectorNumElements();
5005 SmallVector<int, 16> MaskVec;
5006 for (unsigned i = 0; i != NumElems; ++i)
5007 // If this is the insertion idx, put the low elt of V2 here.
5008 MaskVec.push_back(i == Idx ? NumElems : i);
5009 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5012 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5013 /// target specific opcode. Returns true if the Mask could be calculated.
5014 /// Sets IsUnary to true if only uses one source.
5015 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5016 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5017 unsigned NumElems = VT.getVectorNumElements();
5021 switch(N->getOpcode()) {
5023 ImmN = N->getOperand(N->getNumOperands()-1);
5024 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5026 case X86ISD::UNPCKH:
5027 DecodeUNPCKHMask(VT, Mask);
5029 case X86ISD::UNPCKL:
5030 DecodeUNPCKLMask(VT, Mask);
5032 case X86ISD::MOVHLPS:
5033 DecodeMOVHLPSMask(NumElems, Mask);
5035 case X86ISD::MOVLHPS:
5036 DecodeMOVLHPSMask(NumElems, Mask);
5038 case X86ISD::PALIGNR:
5039 ImmN = N->getOperand(N->getNumOperands()-1);
5040 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5042 case X86ISD::PSHUFD:
5043 case X86ISD::VPERMILP:
5044 ImmN = N->getOperand(N->getNumOperands()-1);
5045 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5048 case X86ISD::PSHUFHW:
5049 ImmN = N->getOperand(N->getNumOperands()-1);
5050 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5053 case X86ISD::PSHUFLW:
5054 ImmN = N->getOperand(N->getNumOperands()-1);
5055 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5058 case X86ISD::VPERMI:
5059 ImmN = N->getOperand(N->getNumOperands()-1);
5060 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5064 case X86ISD::MOVSD: {
5065 // The index 0 always comes from the first element of the second source,
5066 // this is why MOVSS and MOVSD are used in the first place. The other
5067 // elements come from the other positions of the first source vector
5068 Mask.push_back(NumElems);
5069 for (unsigned i = 1; i != NumElems; ++i) {
5074 case X86ISD::VPERM2X128:
5075 ImmN = N->getOperand(N->getNumOperands()-1);
5076 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5077 if (Mask.empty()) return false;
5079 case X86ISD::MOVDDUP:
5080 case X86ISD::MOVLHPD:
5081 case X86ISD::MOVLPD:
5082 case X86ISD::MOVLPS:
5083 case X86ISD::MOVSHDUP:
5084 case X86ISD::MOVSLDUP:
5085 // Not yet implemented
5087 default: llvm_unreachable("unknown target shuffle node");
5093 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5094 /// element of the result of the vector shuffle.
5095 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5098 return SDValue(); // Limit search depth.
5100 SDValue V = SDValue(N, 0);
5101 EVT VT = V.getValueType();
5102 unsigned Opcode = V.getOpcode();
5104 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5105 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5106 int Elt = SV->getMaskElt(Index);
5109 return DAG.getUNDEF(VT.getVectorElementType());
5111 unsigned NumElems = VT.getVectorNumElements();
5112 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5113 : SV->getOperand(1);
5114 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5117 // Recurse into target specific vector shuffles to find scalars.
5118 if (isTargetShuffle(Opcode)) {
5119 MVT ShufVT = V.getSimpleValueType();
5120 unsigned NumElems = ShufVT.getVectorNumElements();
5121 SmallVector<int, 16> ShuffleMask;
5124 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5127 int Elt = ShuffleMask[Index];
5129 return DAG.getUNDEF(ShufVT.getVectorElementType());
5131 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5133 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5137 // Actual nodes that may contain scalar elements
5138 if (Opcode == ISD::BITCAST) {
5139 V = V.getOperand(0);
5140 EVT SrcVT = V.getValueType();
5141 unsigned NumElems = VT.getVectorNumElements();
5143 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5147 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5148 return (Index == 0) ? V.getOperand(0)
5149 : DAG.getUNDEF(VT.getVectorElementType());
5151 if (V.getOpcode() == ISD::BUILD_VECTOR)
5152 return V.getOperand(Index);
5157 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5158 /// shuffle operation which come from a consecutively from a zero. The
5159 /// search can start in two different directions, from left or right.
5160 /// We count undefs as zeros until PreferredNum is reached.
5161 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5162 unsigned NumElems, bool ZerosFromLeft,
5164 unsigned PreferredNum = -1U) {
5165 unsigned NumZeros = 0;
5166 for (unsigned i = 0; i != NumElems; ++i) {
5167 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5168 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5172 if (X86::isZeroNode(Elt))
5174 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5175 NumZeros = std::min(NumZeros + 1, PreferredNum);
5183 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5184 /// correspond consecutively to elements from one of the vector operands,
5185 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5187 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5188 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5189 unsigned NumElems, unsigned &OpNum) {
5190 bool SeenV1 = false;
5191 bool SeenV2 = false;
5193 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5194 int Idx = SVOp->getMaskElt(i);
5195 // Ignore undef indicies
5199 if (Idx < (int)NumElems)
5204 // Only accept consecutive elements from the same vector
5205 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5209 OpNum = SeenV1 ? 0 : 1;
5213 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5214 /// logical left shift of a vector.
5215 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5216 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5218 SVOp->getSimpleValueType(0).getVectorNumElements();
5219 unsigned NumZeros = getNumOfConsecutiveZeros(
5220 SVOp, NumElems, false /* check zeros from right */, DAG,
5221 SVOp->getMaskElt(0));
5227 // Considering the elements in the mask that are not consecutive zeros,
5228 // check if they consecutively come from only one of the source vectors.
5230 // V1 = {X, A, B, C} 0
5232 // vector_shuffle V1, V2 <1, 2, 3, X>
5234 if (!isShuffleMaskConsecutive(SVOp,
5235 0, // Mask Start Index
5236 NumElems-NumZeros, // Mask End Index(exclusive)
5237 NumZeros, // Where to start looking in the src vector
5238 NumElems, // Number of elements in vector
5239 OpSrc)) // Which source operand ?
5244 ShVal = SVOp->getOperand(OpSrc);
5248 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5249 /// logical left shift of a vector.
5250 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5251 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5253 SVOp->getSimpleValueType(0).getVectorNumElements();
5254 unsigned NumZeros = getNumOfConsecutiveZeros(
5255 SVOp, NumElems, true /* check zeros from left */, DAG,
5256 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5262 // Considering the elements in the mask that are not consecutive zeros,
5263 // check if they consecutively come from only one of the source vectors.
5265 // 0 { A, B, X, X } = V2
5267 // vector_shuffle V1, V2 <X, X, 4, 5>
5269 if (!isShuffleMaskConsecutive(SVOp,
5270 NumZeros, // Mask Start Index
5271 NumElems, // Mask End Index(exclusive)
5272 0, // Where to start looking in the src vector
5273 NumElems, // Number of elements in vector
5274 OpSrc)) // Which source operand ?
5279 ShVal = SVOp->getOperand(OpSrc);
5283 /// isVectorShift - Returns true if the shuffle can be implemented as a
5284 /// logical left or right shift of a vector.
5285 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5286 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5287 // Although the logic below support any bitwidth size, there are no
5288 // shift instructions which handle more than 128-bit vectors.
5289 if (!SVOp->getSimpleValueType(0).is128BitVector())
5292 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5293 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5299 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5301 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5302 unsigned NumNonZero, unsigned NumZero,
5304 const X86Subtarget* Subtarget,
5305 const TargetLowering &TLI) {
5312 for (unsigned i = 0; i < 16; ++i) {
5313 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5314 if (ThisIsNonZero && First) {
5316 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5318 V = DAG.getUNDEF(MVT::v8i16);
5323 SDValue ThisElt(0, 0), LastElt(0, 0);
5324 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5325 if (LastIsNonZero) {
5326 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5327 MVT::i16, Op.getOperand(i-1));
5329 if (ThisIsNonZero) {
5330 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5331 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5332 ThisElt, DAG.getConstant(8, MVT::i8));
5334 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5338 if (ThisElt.getNode())
5339 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5340 DAG.getIntPtrConstant(i/2));
5344 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5347 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5349 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5350 unsigned NumNonZero, unsigned NumZero,
5352 const X86Subtarget* Subtarget,
5353 const TargetLowering &TLI) {
5360 for (unsigned i = 0; i < 8; ++i) {
5361 bool isNonZero = (NonZeros & (1 << i)) != 0;
5365 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5367 V = DAG.getUNDEF(MVT::v8i16);
5370 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5371 MVT::v8i16, V, Op.getOperand(i),
5372 DAG.getIntPtrConstant(i));
5379 /// getVShift - Return a vector logical shift node.
5381 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5382 unsigned NumBits, SelectionDAG &DAG,
5383 const TargetLowering &TLI, SDLoc dl) {
5384 assert(VT.is128BitVector() && "Unknown type for VShift");
5385 EVT ShVT = MVT::v2i64;
5386 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5387 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5388 return DAG.getNode(ISD::BITCAST, dl, VT,
5389 DAG.getNode(Opc, dl, ShVT, SrcOp,
5390 DAG.getConstant(NumBits,
5391 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5395 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5397 // Check if the scalar load can be widened into a vector load. And if
5398 // the address is "base + cst" see if the cst can be "absorbed" into
5399 // the shuffle mask.
5400 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5401 SDValue Ptr = LD->getBasePtr();
5402 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5404 EVT PVT = LD->getValueType(0);
5405 if (PVT != MVT::i32 && PVT != MVT::f32)
5410 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5411 FI = FINode->getIndex();
5413 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5414 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5415 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5416 Offset = Ptr.getConstantOperandVal(1);
5417 Ptr = Ptr.getOperand(0);
5422 // FIXME: 256-bit vector instructions don't require a strict alignment,
5423 // improve this code to support it better.
5424 unsigned RequiredAlign = VT.getSizeInBits()/8;
5425 SDValue Chain = LD->getChain();
5426 // Make sure the stack object alignment is at least 16 or 32.
5427 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5428 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5429 if (MFI->isFixedObjectIndex(FI)) {
5430 // Can't change the alignment. FIXME: It's possible to compute
5431 // the exact stack offset and reference FI + adjust offset instead.
5432 // If someone *really* cares about this. That's the way to implement it.
5435 MFI->setObjectAlignment(FI, RequiredAlign);
5439 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5440 // Ptr + (Offset & ~15).
5443 if ((Offset % RequiredAlign) & 3)
5445 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5447 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5448 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5450 int EltNo = (Offset - StartOffset) >> 2;
5451 unsigned NumElems = VT.getVectorNumElements();
5453 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5454 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5455 LD->getPointerInfo().getWithOffset(StartOffset),
5456 false, false, false, 0);
5458 SmallVector<int, 8> Mask;
5459 for (unsigned i = 0; i != NumElems; ++i)
5460 Mask.push_back(EltNo);
5462 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5468 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5469 /// vector of type 'VT', see if the elements can be replaced by a single large
5470 /// load which has the same value as a build_vector whose operands are 'elts'.
5472 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5474 /// FIXME: we'd also like to handle the case where the last elements are zero
5475 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5476 /// There's even a handy isZeroNode for that purpose.
5477 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5478 SDLoc &DL, SelectionDAG &DAG,
5479 bool isAfterLegalize) {
5480 EVT EltVT = VT.getVectorElementType();
5481 unsigned NumElems = Elts.size();
5483 LoadSDNode *LDBase = NULL;
5484 unsigned LastLoadedElt = -1U;
5486 // For each element in the initializer, see if we've found a load or an undef.
5487 // If we don't find an initial load element, or later load elements are
5488 // non-consecutive, bail out.
5489 for (unsigned i = 0; i < NumElems; ++i) {
5490 SDValue Elt = Elts[i];
5492 if (!Elt.getNode() ||
5493 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5496 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5498 LDBase = cast<LoadSDNode>(Elt.getNode());
5502 if (Elt.getOpcode() == ISD::UNDEF)
5505 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5506 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5511 // If we have found an entire vector of loads and undefs, then return a large
5512 // load of the entire vector width starting at the base pointer. If we found
5513 // consecutive loads for the low half, generate a vzext_load node.
5514 if (LastLoadedElt == NumElems - 1) {
5516 if (isAfterLegalize &&
5517 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5520 SDValue NewLd = SDValue();
5522 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5523 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5524 LDBase->getPointerInfo(),
5525 LDBase->isVolatile(), LDBase->isNonTemporal(),
5526 LDBase->isInvariant(), 0);
5527 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5528 LDBase->getPointerInfo(),
5529 LDBase->isVolatile(), LDBase->isNonTemporal(),
5530 LDBase->isInvariant(), LDBase->getAlignment());
5532 if (LDBase->hasAnyUseOfValue(1)) {
5533 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5535 SDValue(NewLd.getNode(), 1));
5536 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5537 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5538 SDValue(NewLd.getNode(), 1));
5543 if (NumElems == 4 && LastLoadedElt == 1 &&
5544 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5545 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5546 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5548 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5549 array_lengthof(Ops), MVT::i64,
5550 LDBase->getPointerInfo(),
5551 LDBase->getAlignment(),
5552 false/*isVolatile*/, true/*ReadMem*/,
5555 // Make sure the newly-created LOAD is in the same position as LDBase in
5556 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5557 // update uses of LDBase's output chain to use the TokenFactor.
5558 if (LDBase->hasAnyUseOfValue(1)) {
5559 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5560 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5561 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5562 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5563 SDValue(ResNode.getNode(), 1));
5566 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5571 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5572 /// to generate a splat value for the following cases:
5573 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5574 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5575 /// a scalar load, or a constant.
5576 /// The VBROADCAST node is returned when a pattern is found,
5577 /// or SDValue() otherwise.
5578 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5579 SelectionDAG &DAG) {
5580 if (!Subtarget->hasFp256())
5583 MVT VT = Op.getSimpleValueType();
5586 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5587 "Unsupported vector type for broadcast.");
5592 switch (Op.getOpcode()) {
5594 // Unknown pattern found.
5597 case ISD::BUILD_VECTOR: {
5598 // The BUILD_VECTOR node must be a splat.
5599 if (!isSplatVector(Op.getNode()))
5602 Ld = Op.getOperand(0);
5603 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5604 Ld.getOpcode() == ISD::ConstantFP);
5606 // The suspected load node has several users. Make sure that all
5607 // of its users are from the BUILD_VECTOR node.
5608 // Constants may have multiple users.
5609 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5614 case ISD::VECTOR_SHUFFLE: {
5615 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5617 // Shuffles must have a splat mask where the first element is
5619 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5622 SDValue Sc = Op.getOperand(0);
5623 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5624 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5626 if (!Subtarget->hasInt256())
5629 // Use the register form of the broadcast instruction available on AVX2.
5630 if (VT.getSizeInBits() >= 256)
5631 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5632 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5635 Ld = Sc.getOperand(0);
5636 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5637 Ld.getOpcode() == ISD::ConstantFP);
5639 // The scalar_to_vector node and the suspected
5640 // load node must have exactly one user.
5641 // Constants may have multiple users.
5643 // AVX-512 has register version of the broadcast
5644 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5645 Ld.getValueType().getSizeInBits() >= 32;
5646 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5653 bool IsGE256 = (VT.getSizeInBits() >= 256);
5655 // Handle the broadcasting a single constant scalar from the constant pool
5656 // into a vector. On Sandybridge it is still better to load a constant vector
5657 // from the constant pool and not to broadcast it from a scalar.
5658 if (ConstSplatVal && Subtarget->hasInt256()) {
5659 EVT CVT = Ld.getValueType();
5660 assert(!CVT.isVector() && "Must not broadcast a vector type");
5661 unsigned ScalarSize = CVT.getSizeInBits();
5663 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5664 const Constant *C = 0;
5665 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5666 C = CI->getConstantIntValue();
5667 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5668 C = CF->getConstantFPValue();
5670 assert(C && "Invalid constant type");
5672 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5673 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5674 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5675 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5676 MachinePointerInfo::getConstantPool(),
5677 false, false, false, Alignment);
5679 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5683 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5684 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5686 // Handle AVX2 in-register broadcasts.
5687 if (!IsLoad && Subtarget->hasInt256() &&
5688 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5689 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5691 // The scalar source must be a normal load.
5695 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5696 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5698 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5699 // double since there is no vbroadcastsd xmm
5700 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5701 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5702 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5705 // Unsupported broadcast.
5709 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5710 MVT VT = Op.getSimpleValueType();
5712 // Skip if insert_vec_elt is not supported.
5713 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5714 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5718 unsigned NumElems = Op.getNumOperands();
5722 SmallVector<unsigned, 4> InsertIndices;
5723 SmallVector<int, 8> Mask(NumElems, -1);
5725 for (unsigned i = 0; i != NumElems; ++i) {
5726 unsigned Opc = Op.getOperand(i).getOpcode();
5728 if (Opc == ISD::UNDEF)
5731 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5732 // Quit if more than 1 elements need inserting.
5733 if (InsertIndices.size() > 1)
5736 InsertIndices.push_back(i);
5740 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5741 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5743 // Quit if extracted from vector of different type.
5744 if (ExtractedFromVec.getValueType() != VT)
5747 // Quit if non-constant index.
5748 if (!isa<ConstantSDNode>(ExtIdx))
5751 if (VecIn1.getNode() == 0)
5752 VecIn1 = ExtractedFromVec;
5753 else if (VecIn1 != ExtractedFromVec) {
5754 if (VecIn2.getNode() == 0)
5755 VecIn2 = ExtractedFromVec;
5756 else if (VecIn2 != ExtractedFromVec)
5757 // Quit if more than 2 vectors to shuffle
5761 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5763 if (ExtractedFromVec == VecIn1)
5765 else if (ExtractedFromVec == VecIn2)
5766 Mask[i] = Idx + NumElems;
5769 if (VecIn1.getNode() == 0)
5772 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5773 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5774 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5775 unsigned Idx = InsertIndices[i];
5776 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5777 DAG.getIntPtrConstant(Idx));
5783 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5785 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5787 MVT VT = Op.getSimpleValueType();
5788 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5789 "Unexpected type in LowerBUILD_VECTORvXi1!");
5792 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5793 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5794 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5795 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5796 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5797 Ops, VT.getVectorNumElements());
5800 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5801 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5802 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5803 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5804 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5805 Ops, VT.getVectorNumElements());
5808 bool AllContants = true;
5809 uint64_t Immediate = 0;
5810 int NonConstIdx = -1;
5811 bool IsSplat = true;
5812 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5813 SDValue In = Op.getOperand(idx);
5814 if (In.getOpcode() == ISD::UNDEF)
5816 if (!isa<ConstantSDNode>(In)) {
5817 AllContants = false;
5820 else if (cast<ConstantSDNode>(In)->getZExtValue())
5821 Immediate |= (1ULL << idx);
5822 if (In != Op.getOperand(0))
5827 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5828 DAG.getConstant(Immediate, MVT::i16));
5829 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5830 DAG.getIntPtrConstant(0));
5833 if (!IsSplat && (NonConstIdx != 0))
5834 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5835 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5838 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5839 DAG.getConstant(-1, SelectVT),
5840 DAG.getConstant(0, SelectVT));
5842 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5843 DAG.getConstant((Immediate | 1), SelectVT),
5844 DAG.getConstant(Immediate, SelectVT));
5845 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5849 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5852 MVT VT = Op.getSimpleValueType();
5853 MVT ExtVT = VT.getVectorElementType();
5854 unsigned NumElems = Op.getNumOperands();
5856 // Generate vectors for predicate vectors.
5857 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5858 return LowerBUILD_VECTORvXi1(Op, DAG);
5860 // Vectors containing all zeros can be matched by pxor and xorps later
5861 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5862 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5863 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5864 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5867 return getZeroVector(VT, Subtarget, DAG, dl);
5870 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5871 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5872 // vpcmpeqd on 256-bit vectors.
5873 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5874 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5877 if (!VT.is512BitVector())
5878 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5881 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5882 if (Broadcast.getNode())
5885 unsigned EVTBits = ExtVT.getSizeInBits();
5887 unsigned NumZero = 0;
5888 unsigned NumNonZero = 0;
5889 unsigned NonZeros = 0;
5890 bool IsAllConstants = true;
5891 SmallSet<SDValue, 8> Values;
5892 for (unsigned i = 0; i < NumElems; ++i) {
5893 SDValue Elt = Op.getOperand(i);
5894 if (Elt.getOpcode() == ISD::UNDEF)
5897 if (Elt.getOpcode() != ISD::Constant &&
5898 Elt.getOpcode() != ISD::ConstantFP)
5899 IsAllConstants = false;
5900 if (X86::isZeroNode(Elt))
5903 NonZeros |= (1 << i);
5908 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5909 if (NumNonZero == 0)
5910 return DAG.getUNDEF(VT);
5912 // Special case for single non-zero, non-undef, element.
5913 if (NumNonZero == 1) {
5914 unsigned Idx = countTrailingZeros(NonZeros);
5915 SDValue Item = Op.getOperand(Idx);
5917 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5918 // the value are obviously zero, truncate the value to i32 and do the
5919 // insertion that way. Only do this if the value is non-constant or if the
5920 // value is a constant being inserted into element 0. It is cheaper to do
5921 // a constant pool load than it is to do a movd + shuffle.
5922 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5923 (!IsAllConstants || Idx == 0)) {
5924 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5926 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5927 EVT VecVT = MVT::v4i32;
5928 unsigned VecElts = 4;
5930 // Truncate the value (which may itself be a constant) to i32, and
5931 // convert it to a vector with movd (S2V+shuffle to zero extend).
5932 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5933 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5934 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5936 // Now we have our 32-bit value zero extended in the low element of
5937 // a vector. If Idx != 0, swizzle it into place.
5939 SmallVector<int, 4> Mask;
5940 Mask.push_back(Idx);
5941 for (unsigned i = 1; i != VecElts; ++i)
5943 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5946 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5950 // If we have a constant or non-constant insertion into the low element of
5951 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5952 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5953 // depending on what the source datatype is.
5956 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5958 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5959 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5960 if (VT.is256BitVector() || VT.is512BitVector()) {
5961 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5962 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5963 Item, DAG.getIntPtrConstant(0));
5965 assert(VT.is128BitVector() && "Expected an SSE value type!");
5966 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5967 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5968 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5971 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5972 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5973 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5974 if (VT.is256BitVector()) {
5975 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5976 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5978 assert(VT.is128BitVector() && "Expected an SSE value type!");
5979 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5981 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5985 // Is it a vector logical left shift?
5986 if (NumElems == 2 && Idx == 1 &&
5987 X86::isZeroNode(Op.getOperand(0)) &&
5988 !X86::isZeroNode(Op.getOperand(1))) {
5989 unsigned NumBits = VT.getSizeInBits();
5990 return getVShift(true, VT,
5991 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5992 VT, Op.getOperand(1)),
5993 NumBits/2, DAG, *this, dl);
5996 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5999 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6000 // is a non-constant being inserted into an element other than the low one,
6001 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6002 // movd/movss) to move this into the low element, then shuffle it into
6004 if (EVTBits == 32) {
6005 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6007 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6008 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6009 SmallVector<int, 8> MaskVec;
6010 for (unsigned i = 0; i != NumElems; ++i)
6011 MaskVec.push_back(i == Idx ? 0 : 1);
6012 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6016 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6017 if (Values.size() == 1) {
6018 if (EVTBits == 32) {
6019 // Instead of a shuffle like this:
6020 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6021 // Check if it's possible to issue this instead.
6022 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6023 unsigned Idx = countTrailingZeros(NonZeros);
6024 SDValue Item = Op.getOperand(Idx);
6025 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6026 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6031 // A vector full of immediates; various special cases are already
6032 // handled, so this is best done with a single constant-pool load.
6036 // For AVX-length vectors, build the individual 128-bit pieces and use
6037 // shuffles to put them in place.
6038 if (VT.is256BitVector() || VT.is512BitVector()) {
6039 SmallVector<SDValue, 64> V;
6040 for (unsigned i = 0; i != NumElems; ++i)
6041 V.push_back(Op.getOperand(i));
6043 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6045 // Build both the lower and upper subvector.
6046 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6047 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6050 // Recreate the wider vector with the lower and upper part.
6051 if (VT.is256BitVector())
6052 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6053 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6056 // Let legalizer expand 2-wide build_vectors.
6057 if (EVTBits == 64) {
6058 if (NumNonZero == 1) {
6059 // One half is zero or undef.
6060 unsigned Idx = countTrailingZeros(NonZeros);
6061 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6062 Op.getOperand(Idx));
6063 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6068 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6069 if (EVTBits == 8 && NumElems == 16) {
6070 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6072 if (V.getNode()) return V;
6075 if (EVTBits == 16 && NumElems == 8) {
6076 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6078 if (V.getNode()) return V;
6081 // If element VT is == 32 bits, turn it into a number of shuffles.
6082 SmallVector<SDValue, 8> V(NumElems);
6083 if (NumElems == 4 && NumZero > 0) {
6084 for (unsigned i = 0; i < 4; ++i) {
6085 bool isZero = !(NonZeros & (1 << i));
6087 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6089 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6092 for (unsigned i = 0; i < 2; ++i) {
6093 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6096 V[i] = V[i*2]; // Must be a zero vector.
6099 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6102 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6105 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6110 bool Reverse1 = (NonZeros & 0x3) == 2;
6111 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6115 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6116 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6118 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6121 if (Values.size() > 1 && VT.is128BitVector()) {
6122 // Check for a build vector of consecutive loads.
6123 for (unsigned i = 0; i < NumElems; ++i)
6124 V[i] = Op.getOperand(i);
6126 // Check for elements which are consecutive loads.
6127 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6131 // Check for a build vector from mostly shuffle plus few inserting.
6132 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6136 // For SSE 4.1, use insertps to put the high elements into the low element.
6137 if (getSubtarget()->hasSSE41()) {
6139 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6140 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6142 Result = DAG.getUNDEF(VT);
6144 for (unsigned i = 1; i < NumElems; ++i) {
6145 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6146 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6147 Op.getOperand(i), DAG.getIntPtrConstant(i));
6152 // Otherwise, expand into a number of unpckl*, start by extending each of
6153 // our (non-undef) elements to the full vector width with the element in the
6154 // bottom slot of the vector (which generates no code for SSE).
6155 for (unsigned i = 0; i < NumElems; ++i) {
6156 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6157 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6159 V[i] = DAG.getUNDEF(VT);
6162 // Next, we iteratively mix elements, e.g. for v4f32:
6163 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6164 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6165 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6166 unsigned EltStride = NumElems >> 1;
6167 while (EltStride != 0) {
6168 for (unsigned i = 0; i < EltStride; ++i) {
6169 // If V[i+EltStride] is undef and this is the first round of mixing,
6170 // then it is safe to just drop this shuffle: V[i] is already in the
6171 // right place, the one element (since it's the first round) being
6172 // inserted as undef can be dropped. This isn't safe for successive
6173 // rounds because they will permute elements within both vectors.
6174 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6175 EltStride == NumElems/2)
6178 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6187 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6188 // to create 256-bit vectors from two other 128-bit ones.
6189 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6191 MVT ResVT = Op.getSimpleValueType();
6193 assert((ResVT.is256BitVector() ||
6194 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6196 SDValue V1 = Op.getOperand(0);
6197 SDValue V2 = Op.getOperand(1);
6198 unsigned NumElems = ResVT.getVectorNumElements();
6199 if(ResVT.is256BitVector())
6200 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6202 if (Op.getNumOperands() == 4) {
6203 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6204 ResVT.getVectorNumElements()/2);
6205 SDValue V3 = Op.getOperand(2);
6206 SDValue V4 = Op.getOperand(3);
6207 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6208 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6210 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6213 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6214 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6215 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6216 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6217 Op.getNumOperands() == 4)));
6219 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6220 // from two other 128-bit ones.
6222 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6223 return LowerAVXCONCAT_VECTORS(Op, DAG);
6226 // Try to lower a shuffle node into a simple blend instruction.
6228 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6229 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6230 SDValue V1 = SVOp->getOperand(0);
6231 SDValue V2 = SVOp->getOperand(1);
6233 MVT VT = SVOp->getSimpleValueType(0);
6234 MVT EltVT = VT.getVectorElementType();
6235 unsigned NumElems = VT.getVectorNumElements();
6237 // There is no blend with immediate in AVX-512.
6238 if (VT.is512BitVector())
6241 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6243 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6246 // Check the mask for BLEND and build the value.
6247 unsigned MaskValue = 0;
6248 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6249 unsigned NumLanes = (NumElems-1)/8 + 1;
6250 unsigned NumElemsInLane = NumElems / NumLanes;
6252 // Blend for v16i16 should be symetric for the both lanes.
6253 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6255 int SndLaneEltIdx = (NumLanes == 2) ?
6256 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6257 int EltIdx = SVOp->getMaskElt(i);
6259 if ((EltIdx < 0 || EltIdx == (int)i) &&
6260 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6263 if (((unsigned)EltIdx == (i + NumElems)) &&
6264 (SndLaneEltIdx < 0 ||
6265 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6266 MaskValue |= (1<<i);
6271 // Convert i32 vectors to floating point if it is not AVX2.
6272 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6274 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6275 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6277 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6278 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6281 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6282 DAG.getConstant(MaskValue, MVT::i32));
6283 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6286 /// 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->isTargetWindows() || 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->resolveAliasedGlobal(false);
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. This avoids subregister
9814 // aliasing issues. Keep the smaller reference if we're optimizing for
9815 // size, however, as that'll allow better folding of memory operations.
9816 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9817 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9818 AttributeSet::FunctionIndex, Attribute::MinSize)) {
9820 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9821 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9822 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9824 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9825 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9826 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9828 return SDValue(Sub.getNode(), 1);
9830 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9833 /// Convert a comparison if required by the subtarget.
9834 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9835 SelectionDAG &DAG) const {
9836 // If the subtarget does not support the FUCOMI instruction, floating-point
9837 // comparisons have to be converted.
9838 if (Subtarget->hasCMov() ||
9839 Cmp.getOpcode() != X86ISD::CMP ||
9840 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9841 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9844 // The instruction selector will select an FUCOM instruction instead of
9845 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9846 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9847 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9849 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9850 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9851 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9852 DAG.getConstant(8, MVT::i8));
9853 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9854 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9857 static bool isAllOnes(SDValue V) {
9858 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9859 return C && C->isAllOnesValue();
9862 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9863 /// if it's possible.
9864 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9865 SDLoc dl, SelectionDAG &DAG) const {
9866 SDValue Op0 = And.getOperand(0);
9867 SDValue Op1 = And.getOperand(1);
9868 if (Op0.getOpcode() == ISD::TRUNCATE)
9869 Op0 = Op0.getOperand(0);
9870 if (Op1.getOpcode() == ISD::TRUNCATE)
9871 Op1 = Op1.getOperand(0);
9874 if (Op1.getOpcode() == ISD::SHL)
9875 std::swap(Op0, Op1);
9876 if (Op0.getOpcode() == ISD::SHL) {
9877 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9878 if (And00C->getZExtValue() == 1) {
9879 // If we looked past a truncate, check that it's only truncating away
9881 unsigned BitWidth = Op0.getValueSizeInBits();
9882 unsigned AndBitWidth = And.getValueSizeInBits();
9883 if (BitWidth > AndBitWidth) {
9885 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9886 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9890 RHS = Op0.getOperand(1);
9892 } else if (Op1.getOpcode() == ISD::Constant) {
9893 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9894 uint64_t AndRHSVal = AndRHS->getZExtValue();
9895 SDValue AndLHS = Op0;
9897 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9898 LHS = AndLHS.getOperand(0);
9899 RHS = AndLHS.getOperand(1);
9902 // Use BT if the immediate can't be encoded in a TEST instruction.
9903 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9905 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9909 if (LHS.getNode()) {
9910 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9911 // instruction. Since the shift amount is in-range-or-undefined, we know
9912 // that doing a bittest on the i32 value is ok. We extend to i32 because
9913 // the encoding for the i16 version is larger than the i32 version.
9914 // Also promote i16 to i32 for performance / code size reason.
9915 if (LHS.getValueType() == MVT::i8 ||
9916 LHS.getValueType() == MVT::i16)
9917 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9919 // If the operand types disagree, extend the shift amount to match. Since
9920 // BT ignores high bits (like shifts) we can use anyextend.
9921 if (LHS.getValueType() != RHS.getValueType())
9922 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9924 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9925 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9926 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9927 DAG.getConstant(Cond, MVT::i8), BT);
9933 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9935 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9940 // SSE Condition code mapping:
9949 switch (SetCCOpcode) {
9950 default: llvm_unreachable("Unexpected SETCC condition");
9952 case ISD::SETEQ: SSECC = 0; break;
9954 case ISD::SETGT: Swap = true; // Fallthrough
9956 case ISD::SETOLT: SSECC = 1; break;
9958 case ISD::SETGE: Swap = true; // Fallthrough
9960 case ISD::SETOLE: SSECC = 2; break;
9961 case ISD::SETUO: SSECC = 3; break;
9963 case ISD::SETNE: SSECC = 4; break;
9964 case ISD::SETULE: Swap = true; // Fallthrough
9965 case ISD::SETUGE: SSECC = 5; break;
9966 case ISD::SETULT: Swap = true; // Fallthrough
9967 case ISD::SETUGT: SSECC = 6; break;
9968 case ISD::SETO: SSECC = 7; break;
9970 case ISD::SETONE: SSECC = 8; break;
9973 std::swap(Op0, Op1);
9978 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9979 // ones, and then concatenate the result back.
9980 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9981 MVT VT = Op.getSimpleValueType();
9983 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9984 "Unsupported value type for operation");
9986 unsigned NumElems = VT.getVectorNumElements();
9988 SDValue CC = Op.getOperand(2);
9990 // Extract the LHS vectors
9991 SDValue LHS = Op.getOperand(0);
9992 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9993 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9995 // Extract the RHS vectors
9996 SDValue RHS = Op.getOperand(1);
9997 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9998 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10000 // Issue the operation on the smaller types and concatenate the result back
10001 MVT EltVT = VT.getVectorElementType();
10002 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10003 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10004 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10005 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10008 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10009 const X86Subtarget *Subtarget) {
10010 SDValue Op0 = Op.getOperand(0);
10011 SDValue Op1 = Op.getOperand(1);
10012 SDValue CC = Op.getOperand(2);
10013 MVT VT = Op.getSimpleValueType();
10016 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10017 Op.getValueType().getScalarType() == MVT::i1 &&
10018 "Cannot set masked compare for this operation");
10020 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10022 bool Unsigned = false;
10025 switch (SetCCOpcode) {
10026 default: llvm_unreachable("Unexpected SETCC condition");
10027 case ISD::SETNE: SSECC = 4; break;
10028 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10029 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10030 case ISD::SETLT: Swap = true; //fall-through
10031 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10032 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10033 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10034 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10035 case ISD::SETULE: Unsigned = true; //fall-through
10036 case ISD::SETLE: SSECC = 2; break;
10040 std::swap(Op0, Op1);
10042 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10043 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10044 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10045 DAG.getConstant(SSECC, MVT::i8));
10048 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10049 /// operand \p Op1. If non-trivial (for example because it's not constant)
10050 /// return an empty value.
10051 static SDValue ChangeVSETULTtoVSETULE(SDValue Op1, SelectionDAG &DAG)
10053 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10057 MVT VT = Op1.getSimpleValueType();
10058 MVT EVT = VT.getVectorElementType();
10059 unsigned n = VT.getVectorNumElements();
10060 SmallVector<SDValue, 8> ULTOp1;
10062 for (unsigned i = 0; i < n; ++i) {
10063 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10064 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10067 // Avoid underflow.
10068 APInt Val = Elt->getAPIntValue();
10072 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10075 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op1), VT, ULTOp1.data(),
10079 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10080 SelectionDAG &DAG) {
10081 SDValue Op0 = Op.getOperand(0);
10082 SDValue Op1 = Op.getOperand(1);
10083 SDValue CC = Op.getOperand(2);
10084 MVT VT = Op.getSimpleValueType();
10085 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10086 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10091 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10092 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10095 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10096 unsigned Opc = X86ISD::CMPP;
10097 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10098 assert(VT.getVectorNumElements() <= 16);
10099 Opc = X86ISD::CMPM;
10101 // In the two special cases we can't handle, emit two comparisons.
10104 unsigned CombineOpc;
10105 if (SetCCOpcode == ISD::SETUEQ) {
10106 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10108 assert(SetCCOpcode == ISD::SETONE);
10109 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10112 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10113 DAG.getConstant(CC0, MVT::i8));
10114 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10115 DAG.getConstant(CC1, MVT::i8));
10116 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10118 // Handle all other FP comparisons here.
10119 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10120 DAG.getConstant(SSECC, MVT::i8));
10123 // Break 256-bit integer vector compare into smaller ones.
10124 if (VT.is256BitVector() && !Subtarget->hasInt256())
10125 return Lower256IntVSETCC(Op, DAG);
10127 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10128 EVT OpVT = Op1.getValueType();
10129 if (Subtarget->hasAVX512()) {
10130 if (Op1.getValueType().is512BitVector() ||
10131 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10132 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10134 // In AVX-512 architecture setcc returns mask with i1 elements,
10135 // But there is no compare instruction for i8 and i16 elements.
10136 // We are not talking about 512-bit operands in this case, these
10137 // types are illegal.
10139 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10140 OpVT.getVectorElementType().getSizeInBits() >= 8))
10141 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10142 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10145 // We are handling one of the integer comparisons here. Since SSE only has
10146 // GT and EQ comparisons for integer, swapping operands and multiple
10147 // operations may be required for some comparisons.
10149 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10150 bool Subus = false;
10152 switch (SetCCOpcode) {
10153 default: llvm_unreachable("Unexpected SETCC condition");
10154 case ISD::SETNE: Invert = true;
10155 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10156 case ISD::SETLT: Swap = true;
10157 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10158 case ISD::SETGE: Swap = true;
10159 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10160 Invert = true; break;
10161 case ISD::SETULT: Swap = true;
10162 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10163 FlipSigns = true; break;
10164 case ISD::SETUGE: Swap = true;
10165 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10166 FlipSigns = true; Invert = true; break;
10169 // Special case: Use min/max operations for SETULE/SETUGE
10170 MVT VET = VT.getVectorElementType();
10172 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10173 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10176 switch (SetCCOpcode) {
10178 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10179 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10182 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10185 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10186 if (!MinMax && hasSubus) {
10187 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10189 // t = psubus Op0, Op1
10190 // pcmpeq t, <0..0>
10191 switch (SetCCOpcode) {
10193 case ISD::SETULT: {
10194 // If the comparison is against a constant we can turn this into a
10195 // setule. With psubus, setule does not require a swap. This is
10196 // beneficial because the constant in the register is no longer
10197 // destructed as the destination so it can be hoisted out of a loop.
10198 // Only do this pre-AVX since vpcmp* is no longer destructive.
10199 if (Subtarget->hasAVX())
10201 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(Op1, DAG);
10202 if (ULEOp1.getNode()) {
10204 Subus = true; Invert = false; Swap = false;
10208 // Psubus is better than flip-sign because it requires no inversion.
10209 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10210 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10214 Opc = X86ISD::SUBUS;
10220 std::swap(Op0, Op1);
10222 // Check that the operation in question is available (most are plain SSE2,
10223 // but PCMPGTQ and PCMPEQQ have different requirements).
10224 if (VT == MVT::v2i64) {
10225 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10226 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10228 // First cast everything to the right type.
10229 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10230 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10232 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10233 // bits of the inputs before performing those operations. The lower
10234 // compare is always unsigned.
10237 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10239 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10240 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10241 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10242 Sign, Zero, Sign, Zero);
10244 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10245 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10247 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10248 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10249 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10251 // Create masks for only the low parts/high parts of the 64 bit integers.
10252 static const int MaskHi[] = { 1, 1, 3, 3 };
10253 static const int MaskLo[] = { 0, 0, 2, 2 };
10254 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10255 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10256 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10258 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10259 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10262 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10264 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10267 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10268 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10269 // pcmpeqd + pshufd + pand.
10270 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10272 // First cast everything to the right type.
10273 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10274 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10277 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10279 // Make sure the lower and upper halves are both all-ones.
10280 static const int Mask[] = { 1, 0, 3, 2 };
10281 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10282 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10285 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10287 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10291 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10292 // bits of the inputs before performing those operations.
10294 EVT EltVT = VT.getVectorElementType();
10295 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10296 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10297 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10300 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10302 // If the logical-not of the result is required, perform that now.
10304 Result = DAG.getNOT(dl, Result, VT);
10307 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10310 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10311 getZeroVector(VT, Subtarget, DAG, dl));
10316 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10318 MVT VT = Op.getSimpleValueType();
10320 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10322 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10323 && "SetCC type must be 8-bit or 1-bit integer");
10324 SDValue Op0 = Op.getOperand(0);
10325 SDValue Op1 = Op.getOperand(1);
10327 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10329 // Optimize to BT if possible.
10330 // Lower (X & (1 << N)) == 0 to BT(X, N).
10331 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10332 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10333 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10334 Op1.getOpcode() == ISD::Constant &&
10335 cast<ConstantSDNode>(Op1)->isNullValue() &&
10336 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10337 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10338 if (NewSetCC.getNode())
10342 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10344 if (Op1.getOpcode() == ISD::Constant &&
10345 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10346 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10347 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10349 // If the input is a setcc, then reuse the input setcc or use a new one with
10350 // the inverted condition.
10351 if (Op0.getOpcode() == X86ISD::SETCC) {
10352 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10353 bool Invert = (CC == ISD::SETNE) ^
10354 cast<ConstantSDNode>(Op1)->isNullValue();
10358 CCode = X86::GetOppositeBranchCondition(CCode);
10359 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10360 DAG.getConstant(CCode, MVT::i8),
10361 Op0.getOperand(1));
10363 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10367 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10368 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10369 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10371 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10372 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10375 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10376 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10377 if (X86CC == X86::COND_INVALID)
10380 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10381 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10382 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10383 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10385 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10389 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10390 static bool isX86LogicalCmp(SDValue Op) {
10391 unsigned Opc = Op.getNode()->getOpcode();
10392 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10393 Opc == X86ISD::SAHF)
10395 if (Op.getResNo() == 1 &&
10396 (Opc == X86ISD::ADD ||
10397 Opc == X86ISD::SUB ||
10398 Opc == X86ISD::ADC ||
10399 Opc == X86ISD::SBB ||
10400 Opc == X86ISD::SMUL ||
10401 Opc == X86ISD::UMUL ||
10402 Opc == X86ISD::INC ||
10403 Opc == X86ISD::DEC ||
10404 Opc == X86ISD::OR ||
10405 Opc == X86ISD::XOR ||
10406 Opc == X86ISD::AND))
10409 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10415 static bool isZero(SDValue V) {
10416 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10417 return C && C->isNullValue();
10420 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10421 if (V.getOpcode() != ISD::TRUNCATE)
10424 SDValue VOp0 = V.getOperand(0);
10425 unsigned InBits = VOp0.getValueSizeInBits();
10426 unsigned Bits = V.getValueSizeInBits();
10427 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10430 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10431 bool addTest = true;
10432 SDValue Cond = Op.getOperand(0);
10433 SDValue Op1 = Op.getOperand(1);
10434 SDValue Op2 = Op.getOperand(2);
10436 EVT VT = Op1.getValueType();
10439 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10440 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10441 // sequence later on.
10442 if (Cond.getOpcode() == ISD::SETCC &&
10443 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10444 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10445 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10446 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10447 int SSECC = translateX86FSETCC(
10448 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10451 if (Subtarget->hasAVX512()) {
10452 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10453 DAG.getConstant(SSECC, MVT::i8));
10454 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10456 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10457 DAG.getConstant(SSECC, MVT::i8));
10458 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10459 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10460 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10464 if (Cond.getOpcode() == ISD::SETCC) {
10465 SDValue NewCond = LowerSETCC(Cond, DAG);
10466 if (NewCond.getNode())
10470 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10471 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10472 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10473 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10474 if (Cond.getOpcode() == X86ISD::SETCC &&
10475 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10476 isZero(Cond.getOperand(1).getOperand(1))) {
10477 SDValue Cmp = Cond.getOperand(1);
10479 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10481 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10482 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10483 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10485 SDValue CmpOp0 = Cmp.getOperand(0);
10486 // Apply further optimizations for special cases
10487 // (select (x != 0), -1, 0) -> neg & sbb
10488 // (select (x == 0), 0, -1) -> neg & sbb
10489 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10490 if (YC->isNullValue() &&
10491 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10492 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10493 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10494 DAG.getConstant(0, CmpOp0.getValueType()),
10496 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10497 DAG.getConstant(X86::COND_B, MVT::i8),
10498 SDValue(Neg.getNode(), 1));
10502 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10503 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10504 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10506 SDValue Res = // Res = 0 or -1.
10507 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10508 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10510 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10511 Res = DAG.getNOT(DL, Res, Res.getValueType());
10513 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10514 if (N2C == 0 || !N2C->isNullValue())
10515 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10520 // Look past (and (setcc_carry (cmp ...)), 1).
10521 if (Cond.getOpcode() == ISD::AND &&
10522 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10523 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10524 if (C && C->getAPIntValue() == 1)
10525 Cond = Cond.getOperand(0);
10528 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10529 // setting operand in place of the X86ISD::SETCC.
10530 unsigned CondOpcode = Cond.getOpcode();
10531 if (CondOpcode == X86ISD::SETCC ||
10532 CondOpcode == X86ISD::SETCC_CARRY) {
10533 CC = Cond.getOperand(0);
10535 SDValue Cmp = Cond.getOperand(1);
10536 unsigned Opc = Cmp.getOpcode();
10537 MVT VT = Op.getSimpleValueType();
10539 bool IllegalFPCMov = false;
10540 if (VT.isFloatingPoint() && !VT.isVector() &&
10541 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10542 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10544 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10545 Opc == X86ISD::BT) { // FIXME
10549 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10550 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10551 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10552 Cond.getOperand(0).getValueType() != MVT::i8)) {
10553 SDValue LHS = Cond.getOperand(0);
10554 SDValue RHS = Cond.getOperand(1);
10555 unsigned X86Opcode;
10558 switch (CondOpcode) {
10559 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10560 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10561 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10562 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10563 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10564 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10565 default: llvm_unreachable("unexpected overflowing operator");
10567 if (CondOpcode == ISD::UMULO)
10568 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10571 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10573 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10575 if (CondOpcode == ISD::UMULO)
10576 Cond = X86Op.getValue(2);
10578 Cond = X86Op.getValue(1);
10580 CC = DAG.getConstant(X86Cond, MVT::i8);
10585 // Look pass the truncate if the high bits are known zero.
10586 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10587 Cond = Cond.getOperand(0);
10589 // We know the result of AND is compared against zero. Try to match
10591 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10592 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10593 if (NewSetCC.getNode()) {
10594 CC = NewSetCC.getOperand(0);
10595 Cond = NewSetCC.getOperand(1);
10602 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10603 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10606 // a < b ? -1 : 0 -> RES = ~setcc_carry
10607 // a < b ? 0 : -1 -> RES = setcc_carry
10608 // a >= b ? -1 : 0 -> RES = setcc_carry
10609 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10610 if (Cond.getOpcode() == X86ISD::SUB) {
10611 Cond = ConvertCmpIfNecessary(Cond, DAG);
10612 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10614 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10615 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10616 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10617 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10618 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10619 return DAG.getNOT(DL, Res, Res.getValueType());
10624 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10625 // widen the cmov and push the truncate through. This avoids introducing a new
10626 // branch during isel and doesn't add any extensions.
10627 if (Op.getValueType() == MVT::i8 &&
10628 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10629 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10630 if (T1.getValueType() == T2.getValueType() &&
10631 // Blacklist CopyFromReg to avoid partial register stalls.
10632 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10633 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10634 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10635 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10639 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10640 // condition is true.
10641 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10642 SDValue Ops[] = { Op2, Op1, CC, Cond };
10643 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10646 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10647 MVT VT = Op->getSimpleValueType(0);
10648 SDValue In = Op->getOperand(0);
10649 MVT InVT = In.getSimpleValueType();
10652 unsigned int NumElts = VT.getVectorNumElements();
10653 if (NumElts != 8 && NumElts != 16)
10656 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10657 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10659 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10660 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10662 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10663 Constant *C = ConstantInt::get(*DAG.getContext(),
10664 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10666 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10667 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10668 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10669 MachinePointerInfo::getConstantPool(),
10670 false, false, false, Alignment);
10671 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10672 if (VT.is512BitVector())
10674 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10677 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10678 SelectionDAG &DAG) {
10679 MVT VT = Op->getSimpleValueType(0);
10680 SDValue In = Op->getOperand(0);
10681 MVT InVT = In.getSimpleValueType();
10684 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10685 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10687 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10688 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10689 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10692 if (Subtarget->hasInt256())
10693 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10695 // Optimize vectors in AVX mode
10696 // Sign extend v8i16 to v8i32 and
10699 // Divide input vector into two parts
10700 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10701 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10702 // concat the vectors to original VT
10704 unsigned NumElems = InVT.getVectorNumElements();
10705 SDValue Undef = DAG.getUNDEF(InVT);
10707 SmallVector<int,8> ShufMask1(NumElems, -1);
10708 for (unsigned i = 0; i != NumElems/2; ++i)
10711 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10713 SmallVector<int,8> ShufMask2(NumElems, -1);
10714 for (unsigned i = 0; i != NumElems/2; ++i)
10715 ShufMask2[i] = i + NumElems/2;
10717 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10719 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10720 VT.getVectorNumElements()/2);
10722 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10723 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10725 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10728 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10729 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10730 // from the AND / OR.
10731 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10732 Opc = Op.getOpcode();
10733 if (Opc != ISD::OR && Opc != ISD::AND)
10735 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10736 Op.getOperand(0).hasOneUse() &&
10737 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10738 Op.getOperand(1).hasOneUse());
10741 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10742 // 1 and that the SETCC node has a single use.
10743 static bool isXor1OfSetCC(SDValue Op) {
10744 if (Op.getOpcode() != ISD::XOR)
10746 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10747 if (N1C && N1C->getAPIntValue() == 1) {
10748 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10749 Op.getOperand(0).hasOneUse();
10754 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10755 bool addTest = true;
10756 SDValue Chain = Op.getOperand(0);
10757 SDValue Cond = Op.getOperand(1);
10758 SDValue Dest = Op.getOperand(2);
10761 bool Inverted = false;
10763 if (Cond.getOpcode() == ISD::SETCC) {
10764 // Check for setcc([su]{add,sub,mul}o == 0).
10765 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10766 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10767 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10768 Cond.getOperand(0).getResNo() == 1 &&
10769 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10770 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10771 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10772 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10773 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10774 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10776 Cond = Cond.getOperand(0);
10778 SDValue NewCond = LowerSETCC(Cond, DAG);
10779 if (NewCond.getNode())
10784 // FIXME: LowerXALUO doesn't handle these!!
10785 else if (Cond.getOpcode() == X86ISD::ADD ||
10786 Cond.getOpcode() == X86ISD::SUB ||
10787 Cond.getOpcode() == X86ISD::SMUL ||
10788 Cond.getOpcode() == X86ISD::UMUL)
10789 Cond = LowerXALUO(Cond, DAG);
10792 // Look pass (and (setcc_carry (cmp ...)), 1).
10793 if (Cond.getOpcode() == ISD::AND &&
10794 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10795 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10796 if (C && C->getAPIntValue() == 1)
10797 Cond = Cond.getOperand(0);
10800 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10801 // setting operand in place of the X86ISD::SETCC.
10802 unsigned CondOpcode = Cond.getOpcode();
10803 if (CondOpcode == X86ISD::SETCC ||
10804 CondOpcode == X86ISD::SETCC_CARRY) {
10805 CC = Cond.getOperand(0);
10807 SDValue Cmp = Cond.getOperand(1);
10808 unsigned Opc = Cmp.getOpcode();
10809 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10810 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10814 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10818 // These can only come from an arithmetic instruction with overflow,
10819 // e.g. SADDO, UADDO.
10820 Cond = Cond.getNode()->getOperand(1);
10826 CondOpcode = Cond.getOpcode();
10827 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10828 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10829 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10830 Cond.getOperand(0).getValueType() != MVT::i8)) {
10831 SDValue LHS = Cond.getOperand(0);
10832 SDValue RHS = Cond.getOperand(1);
10833 unsigned X86Opcode;
10836 // Keep this in sync with LowerXALUO, otherwise we might create redundant
10837 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10839 switch (CondOpcode) {
10840 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10842 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10844 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10847 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10848 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10850 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10852 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10855 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10856 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10857 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10858 default: llvm_unreachable("unexpected overflowing operator");
10861 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10862 if (CondOpcode == ISD::UMULO)
10863 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10866 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10868 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10870 if (CondOpcode == ISD::UMULO)
10871 Cond = X86Op.getValue(2);
10873 Cond = X86Op.getValue(1);
10875 CC = DAG.getConstant(X86Cond, MVT::i8);
10879 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10880 SDValue Cmp = Cond.getOperand(0).getOperand(1);
10881 if (CondOpc == ISD::OR) {
10882 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10883 // two branches instead of an explicit OR instruction with a
10885 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10886 isX86LogicalCmp(Cmp)) {
10887 CC = Cond.getOperand(0).getOperand(0);
10888 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10889 Chain, Dest, CC, Cmp);
10890 CC = Cond.getOperand(1).getOperand(0);
10894 } else { // ISD::AND
10895 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10896 // two branches instead of an explicit AND instruction with a
10897 // separate test. However, we only do this if this block doesn't
10898 // have a fall-through edge, because this requires an explicit
10899 // jmp when the condition is false.
10900 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10901 isX86LogicalCmp(Cmp) &&
10902 Op.getNode()->hasOneUse()) {
10903 X86::CondCode CCode =
10904 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10905 CCode = X86::GetOppositeBranchCondition(CCode);
10906 CC = DAG.getConstant(CCode, MVT::i8);
10907 SDNode *User = *Op.getNode()->use_begin();
10908 // Look for an unconditional branch following this conditional branch.
10909 // We need this because we need to reverse the successors in order
10910 // to implement FCMP_OEQ.
10911 if (User->getOpcode() == ISD::BR) {
10912 SDValue FalseBB = User->getOperand(1);
10914 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10915 assert(NewBR == User);
10919 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10920 Chain, Dest, CC, Cmp);
10921 X86::CondCode CCode =
10922 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10923 CCode = X86::GetOppositeBranchCondition(CCode);
10924 CC = DAG.getConstant(CCode, MVT::i8);
10930 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10931 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10932 // It should be transformed during dag combiner except when the condition
10933 // is set by a arithmetics with overflow node.
10934 X86::CondCode CCode =
10935 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10936 CCode = X86::GetOppositeBranchCondition(CCode);
10937 CC = DAG.getConstant(CCode, MVT::i8);
10938 Cond = Cond.getOperand(0).getOperand(1);
10940 } else if (Cond.getOpcode() == ISD::SETCC &&
10941 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10942 // For FCMP_OEQ, we can emit
10943 // two branches instead of an explicit AND instruction with a
10944 // separate test. However, we only do this if this block doesn't
10945 // have a fall-through edge, because this requires an explicit
10946 // jmp when the condition is false.
10947 if (Op.getNode()->hasOneUse()) {
10948 SDNode *User = *Op.getNode()->use_begin();
10949 // Look for an unconditional branch following this conditional branch.
10950 // We need this because we need to reverse the successors in order
10951 // to implement FCMP_OEQ.
10952 if (User->getOpcode() == ISD::BR) {
10953 SDValue FalseBB = User->getOperand(1);
10955 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10956 assert(NewBR == User);
10960 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10961 Cond.getOperand(0), Cond.getOperand(1));
10962 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10963 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10964 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10965 Chain, Dest, CC, Cmp);
10966 CC = DAG.getConstant(X86::COND_P, MVT::i8);
10971 } else if (Cond.getOpcode() == ISD::SETCC &&
10972 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10973 // For FCMP_UNE, we can emit
10974 // two branches instead of an explicit AND instruction with a
10975 // separate test. However, we only do this if this block doesn't
10976 // have a fall-through edge, because this requires an explicit
10977 // jmp when the condition is false.
10978 if (Op.getNode()->hasOneUse()) {
10979 SDNode *User = *Op.getNode()->use_begin();
10980 // Look for an unconditional branch following this conditional branch.
10981 // We need this because we need to reverse the successors in order
10982 // to implement FCMP_UNE.
10983 if (User->getOpcode() == ISD::BR) {
10984 SDValue FalseBB = User->getOperand(1);
10986 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10987 assert(NewBR == User);
10990 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10991 Cond.getOperand(0), Cond.getOperand(1));
10992 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10993 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10994 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10995 Chain, Dest, CC, Cmp);
10996 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11006 // Look pass the truncate if the high bits are known zero.
11007 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11008 Cond = Cond.getOperand(0);
11010 // We know the result of AND is compared against zero. Try to match
11012 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11013 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11014 if (NewSetCC.getNode()) {
11015 CC = NewSetCC.getOperand(0);
11016 Cond = NewSetCC.getOperand(1);
11023 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11024 Cond = EmitTest(Cond, X86::COND_NE, DAG);
11026 Cond = ConvertCmpIfNecessary(Cond, DAG);
11027 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11028 Chain, Dest, CC, Cond);
11031 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11032 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11033 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11034 // that the guard pages used by the OS virtual memory manager are allocated in
11035 // correct sequence.
11037 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11038 SelectionDAG &DAG) const {
11039 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
11040 getTargetMachine().Options.EnableSegmentedStacks) &&
11041 "This should be used only on Windows targets or when segmented stacks "
11043 assert(!Subtarget->isTargetMacho() && "Not implemented");
11047 SDValue Chain = Op.getOperand(0);
11048 SDValue Size = Op.getOperand(1);
11049 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11050 EVT VT = Op.getNode()->getValueType(0);
11052 bool Is64Bit = Subtarget->is64Bit();
11053 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11055 if (getTargetMachine().Options.EnableSegmentedStacks) {
11056 MachineFunction &MF = DAG.getMachineFunction();
11057 MachineRegisterInfo &MRI = MF.getRegInfo();
11060 // The 64 bit implementation of segmented stacks needs to clobber both r10
11061 // r11. This makes it impossible to use it along with nested parameters.
11062 const Function *F = MF.getFunction();
11064 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11066 if (I->hasNestAttr())
11067 report_fatal_error("Cannot use segmented stacks with functions that "
11068 "have nested arguments.");
11071 const TargetRegisterClass *AddrRegClass =
11072 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11073 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11074 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11075 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11076 DAG.getRegister(Vreg, SPTy));
11077 SDValue Ops1[2] = { Value, Chain };
11078 return DAG.getMergeValues(Ops1, 2, dl);
11081 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11083 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11084 Flag = Chain.getValue(1);
11085 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11087 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11089 const X86RegisterInfo *RegInfo =
11090 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11091 unsigned SPReg = RegInfo->getStackRegister();
11092 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11093 Chain = SP.getValue(1);
11096 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11097 DAG.getConstant(-(uint64_t)Align, VT));
11098 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11101 SDValue Ops1[2] = { SP, Chain };
11102 return DAG.getMergeValues(Ops1, 2, dl);
11106 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11107 MachineFunction &MF = DAG.getMachineFunction();
11108 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11110 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11113 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11114 // vastart just stores the address of the VarArgsFrameIndex slot into the
11115 // memory location argument.
11116 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11118 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11119 MachinePointerInfo(SV), false, false, 0);
11123 // gp_offset (0 - 6 * 8)
11124 // fp_offset (48 - 48 + 8 * 16)
11125 // overflow_arg_area (point to parameters coming in memory).
11127 SmallVector<SDValue, 8> MemOps;
11128 SDValue FIN = Op.getOperand(1);
11130 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11131 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11133 FIN, MachinePointerInfo(SV), false, false, 0);
11134 MemOps.push_back(Store);
11137 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11138 FIN, DAG.getIntPtrConstant(4));
11139 Store = DAG.getStore(Op.getOperand(0), DL,
11140 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11142 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11143 MemOps.push_back(Store);
11145 // Store ptr to overflow_arg_area
11146 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11147 FIN, DAG.getIntPtrConstant(4));
11148 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11150 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11151 MachinePointerInfo(SV, 8),
11153 MemOps.push_back(Store);
11155 // Store ptr to reg_save_area.
11156 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11157 FIN, DAG.getIntPtrConstant(8));
11158 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11160 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11161 MachinePointerInfo(SV, 16), false, false, 0);
11162 MemOps.push_back(Store);
11163 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11164 &MemOps[0], MemOps.size());
11167 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11168 assert(Subtarget->is64Bit() &&
11169 "LowerVAARG only handles 64-bit va_arg!");
11170 assert((Subtarget->isTargetLinux() ||
11171 Subtarget->isTargetDarwin()) &&
11172 "Unhandled target in LowerVAARG");
11173 assert(Op.getNode()->getNumOperands() == 4);
11174 SDValue Chain = Op.getOperand(0);
11175 SDValue SrcPtr = Op.getOperand(1);
11176 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11177 unsigned Align = Op.getConstantOperandVal(3);
11180 EVT ArgVT = Op.getNode()->getValueType(0);
11181 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11182 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11185 // Decide which area this value should be read from.
11186 // TODO: Implement the AMD64 ABI in its entirety. This simple
11187 // selection mechanism works only for the basic types.
11188 if (ArgVT == MVT::f80) {
11189 llvm_unreachable("va_arg for f80 not yet implemented");
11190 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11191 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11192 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11193 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11195 llvm_unreachable("Unhandled argument type in LowerVAARG");
11198 if (ArgMode == 2) {
11199 // Sanity Check: Make sure using fp_offset makes sense.
11200 assert(!getTargetMachine().Options.UseSoftFloat &&
11201 !(DAG.getMachineFunction()
11202 .getFunction()->getAttributes()
11203 .hasAttribute(AttributeSet::FunctionIndex,
11204 Attribute::NoImplicitFloat)) &&
11205 Subtarget->hasSSE1());
11208 // Insert VAARG_64 node into the DAG
11209 // VAARG_64 returns two values: Variable Argument Address, Chain
11210 SmallVector<SDValue, 11> InstOps;
11211 InstOps.push_back(Chain);
11212 InstOps.push_back(SrcPtr);
11213 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11214 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11215 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11216 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11217 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11218 VTs, &InstOps[0], InstOps.size(),
11220 MachinePointerInfo(SV),
11222 /*Volatile=*/false,
11224 /*WriteMem=*/true);
11225 Chain = VAARG.getValue(1);
11227 // Load the next argument and return it
11228 return DAG.getLoad(ArgVT, dl,
11231 MachinePointerInfo(),
11232 false, false, false, 0);
11235 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11236 SelectionDAG &DAG) {
11237 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11238 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11239 SDValue Chain = Op.getOperand(0);
11240 SDValue DstPtr = Op.getOperand(1);
11241 SDValue SrcPtr = Op.getOperand(2);
11242 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11243 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11246 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11247 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11249 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11252 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11253 // amount is a constant. Takes immediate version of shift as input.
11254 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11255 SDValue SrcOp, uint64_t ShiftAmt,
11256 SelectionDAG &DAG) {
11257 MVT ElementType = VT.getVectorElementType();
11259 // Check for ShiftAmt >= element width
11260 if (ShiftAmt >= ElementType.getSizeInBits()) {
11261 if (Opc == X86ISD::VSRAI)
11262 ShiftAmt = ElementType.getSizeInBits() - 1;
11264 return DAG.getConstant(0, VT);
11267 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11268 && "Unknown target vector shift-by-constant node");
11270 // Fold this packed vector shift into a build vector if SrcOp is a
11271 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11272 if (VT == SrcOp.getSimpleValueType() &&
11273 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11274 SmallVector<SDValue, 8> Elts;
11275 unsigned NumElts = SrcOp->getNumOperands();
11276 ConstantSDNode *ND;
11279 default: llvm_unreachable(0);
11280 case X86ISD::VSHLI:
11281 for (unsigned i=0; i!=NumElts; ++i) {
11282 SDValue CurrentOp = SrcOp->getOperand(i);
11283 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11284 Elts.push_back(CurrentOp);
11287 ND = cast<ConstantSDNode>(CurrentOp);
11288 const APInt &C = ND->getAPIntValue();
11289 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11292 case X86ISD::VSRLI:
11293 for (unsigned i=0; i!=NumElts; ++i) {
11294 SDValue CurrentOp = SrcOp->getOperand(i);
11295 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11296 Elts.push_back(CurrentOp);
11299 ND = cast<ConstantSDNode>(CurrentOp);
11300 const APInt &C = ND->getAPIntValue();
11301 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11304 case X86ISD::VSRAI:
11305 for (unsigned i=0; i!=NumElts; ++i) {
11306 SDValue CurrentOp = SrcOp->getOperand(i);
11307 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11308 Elts.push_back(CurrentOp);
11311 ND = cast<ConstantSDNode>(CurrentOp);
11312 const APInt &C = ND->getAPIntValue();
11313 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11318 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11321 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11324 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11325 // may or may not be a constant. Takes immediate version of shift as input.
11326 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11327 SDValue SrcOp, SDValue ShAmt,
11328 SelectionDAG &DAG) {
11329 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11331 // Catch shift-by-constant.
11332 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11333 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11334 CShAmt->getZExtValue(), DAG);
11336 // Change opcode to non-immediate version
11338 default: llvm_unreachable("Unknown target vector shift node");
11339 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11340 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11341 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11344 // Need to build a vector containing shift amount
11345 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11348 ShOps[1] = DAG.getConstant(0, MVT::i32);
11349 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11350 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11352 // The return type has to be a 128-bit type with the same element
11353 // type as the input type.
11354 MVT EltVT = VT.getVectorElementType();
11355 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11357 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11358 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11361 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11363 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11365 default: return SDValue(); // Don't custom lower most intrinsics.
11366 // Comparison intrinsics.
11367 case Intrinsic::x86_sse_comieq_ss:
11368 case Intrinsic::x86_sse_comilt_ss:
11369 case Intrinsic::x86_sse_comile_ss:
11370 case Intrinsic::x86_sse_comigt_ss:
11371 case Intrinsic::x86_sse_comige_ss:
11372 case Intrinsic::x86_sse_comineq_ss:
11373 case Intrinsic::x86_sse_ucomieq_ss:
11374 case Intrinsic::x86_sse_ucomilt_ss:
11375 case Intrinsic::x86_sse_ucomile_ss:
11376 case Intrinsic::x86_sse_ucomigt_ss:
11377 case Intrinsic::x86_sse_ucomige_ss:
11378 case Intrinsic::x86_sse_ucomineq_ss:
11379 case Intrinsic::x86_sse2_comieq_sd:
11380 case Intrinsic::x86_sse2_comilt_sd:
11381 case Intrinsic::x86_sse2_comile_sd:
11382 case Intrinsic::x86_sse2_comigt_sd:
11383 case Intrinsic::x86_sse2_comige_sd:
11384 case Intrinsic::x86_sse2_comineq_sd:
11385 case Intrinsic::x86_sse2_ucomieq_sd:
11386 case Intrinsic::x86_sse2_ucomilt_sd:
11387 case Intrinsic::x86_sse2_ucomile_sd:
11388 case Intrinsic::x86_sse2_ucomigt_sd:
11389 case Intrinsic::x86_sse2_ucomige_sd:
11390 case Intrinsic::x86_sse2_ucomineq_sd: {
11394 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11395 case Intrinsic::x86_sse_comieq_ss:
11396 case Intrinsic::x86_sse2_comieq_sd:
11397 Opc = X86ISD::COMI;
11400 case Intrinsic::x86_sse_comilt_ss:
11401 case Intrinsic::x86_sse2_comilt_sd:
11402 Opc = X86ISD::COMI;
11405 case Intrinsic::x86_sse_comile_ss:
11406 case Intrinsic::x86_sse2_comile_sd:
11407 Opc = X86ISD::COMI;
11410 case Intrinsic::x86_sse_comigt_ss:
11411 case Intrinsic::x86_sse2_comigt_sd:
11412 Opc = X86ISD::COMI;
11415 case Intrinsic::x86_sse_comige_ss:
11416 case Intrinsic::x86_sse2_comige_sd:
11417 Opc = X86ISD::COMI;
11420 case Intrinsic::x86_sse_comineq_ss:
11421 case Intrinsic::x86_sse2_comineq_sd:
11422 Opc = X86ISD::COMI;
11425 case Intrinsic::x86_sse_ucomieq_ss:
11426 case Intrinsic::x86_sse2_ucomieq_sd:
11427 Opc = X86ISD::UCOMI;
11430 case Intrinsic::x86_sse_ucomilt_ss:
11431 case Intrinsic::x86_sse2_ucomilt_sd:
11432 Opc = X86ISD::UCOMI;
11435 case Intrinsic::x86_sse_ucomile_ss:
11436 case Intrinsic::x86_sse2_ucomile_sd:
11437 Opc = X86ISD::UCOMI;
11440 case Intrinsic::x86_sse_ucomigt_ss:
11441 case Intrinsic::x86_sse2_ucomigt_sd:
11442 Opc = X86ISD::UCOMI;
11445 case Intrinsic::x86_sse_ucomige_ss:
11446 case Intrinsic::x86_sse2_ucomige_sd:
11447 Opc = X86ISD::UCOMI;
11450 case Intrinsic::x86_sse_ucomineq_ss:
11451 case Intrinsic::x86_sse2_ucomineq_sd:
11452 Opc = X86ISD::UCOMI;
11457 SDValue LHS = Op.getOperand(1);
11458 SDValue RHS = Op.getOperand(2);
11459 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11460 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11461 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11462 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11463 DAG.getConstant(X86CC, MVT::i8), Cond);
11464 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11467 // Arithmetic intrinsics.
11468 case Intrinsic::x86_sse2_pmulu_dq:
11469 case Intrinsic::x86_avx2_pmulu_dq:
11470 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11471 Op.getOperand(1), Op.getOperand(2));
11473 // SSE2/AVX2 sub with unsigned saturation intrinsics
11474 case Intrinsic::x86_sse2_psubus_b:
11475 case Intrinsic::x86_sse2_psubus_w:
11476 case Intrinsic::x86_avx2_psubus_b:
11477 case Intrinsic::x86_avx2_psubus_w:
11478 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11479 Op.getOperand(1), Op.getOperand(2));
11481 // SSE3/AVX horizontal add/sub intrinsics
11482 case Intrinsic::x86_sse3_hadd_ps:
11483 case Intrinsic::x86_sse3_hadd_pd:
11484 case Intrinsic::x86_avx_hadd_ps_256:
11485 case Intrinsic::x86_avx_hadd_pd_256:
11486 case Intrinsic::x86_sse3_hsub_ps:
11487 case Intrinsic::x86_sse3_hsub_pd:
11488 case Intrinsic::x86_avx_hsub_ps_256:
11489 case Intrinsic::x86_avx_hsub_pd_256:
11490 case Intrinsic::x86_ssse3_phadd_w_128:
11491 case Intrinsic::x86_ssse3_phadd_d_128:
11492 case Intrinsic::x86_avx2_phadd_w:
11493 case Intrinsic::x86_avx2_phadd_d:
11494 case Intrinsic::x86_ssse3_phsub_w_128:
11495 case Intrinsic::x86_ssse3_phsub_d_128:
11496 case Intrinsic::x86_avx2_phsub_w:
11497 case Intrinsic::x86_avx2_phsub_d: {
11500 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11501 case Intrinsic::x86_sse3_hadd_ps:
11502 case Intrinsic::x86_sse3_hadd_pd:
11503 case Intrinsic::x86_avx_hadd_ps_256:
11504 case Intrinsic::x86_avx_hadd_pd_256:
11505 Opcode = X86ISD::FHADD;
11507 case Intrinsic::x86_sse3_hsub_ps:
11508 case Intrinsic::x86_sse3_hsub_pd:
11509 case Intrinsic::x86_avx_hsub_ps_256:
11510 case Intrinsic::x86_avx_hsub_pd_256:
11511 Opcode = X86ISD::FHSUB;
11513 case Intrinsic::x86_ssse3_phadd_w_128:
11514 case Intrinsic::x86_ssse3_phadd_d_128:
11515 case Intrinsic::x86_avx2_phadd_w:
11516 case Intrinsic::x86_avx2_phadd_d:
11517 Opcode = X86ISD::HADD;
11519 case Intrinsic::x86_ssse3_phsub_w_128:
11520 case Intrinsic::x86_ssse3_phsub_d_128:
11521 case Intrinsic::x86_avx2_phsub_w:
11522 case Intrinsic::x86_avx2_phsub_d:
11523 Opcode = X86ISD::HSUB;
11526 return DAG.getNode(Opcode, dl, Op.getValueType(),
11527 Op.getOperand(1), Op.getOperand(2));
11530 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11531 case Intrinsic::x86_sse2_pmaxu_b:
11532 case Intrinsic::x86_sse41_pmaxuw:
11533 case Intrinsic::x86_sse41_pmaxud:
11534 case Intrinsic::x86_avx2_pmaxu_b:
11535 case Intrinsic::x86_avx2_pmaxu_w:
11536 case Intrinsic::x86_avx2_pmaxu_d:
11537 case Intrinsic::x86_sse2_pminu_b:
11538 case Intrinsic::x86_sse41_pminuw:
11539 case Intrinsic::x86_sse41_pminud:
11540 case Intrinsic::x86_avx2_pminu_b:
11541 case Intrinsic::x86_avx2_pminu_w:
11542 case Intrinsic::x86_avx2_pminu_d:
11543 case Intrinsic::x86_sse41_pmaxsb:
11544 case Intrinsic::x86_sse2_pmaxs_w:
11545 case Intrinsic::x86_sse41_pmaxsd:
11546 case Intrinsic::x86_avx2_pmaxs_b:
11547 case Intrinsic::x86_avx2_pmaxs_w:
11548 case Intrinsic::x86_avx2_pmaxs_d:
11549 case Intrinsic::x86_sse41_pminsb:
11550 case Intrinsic::x86_sse2_pmins_w:
11551 case Intrinsic::x86_sse41_pminsd:
11552 case Intrinsic::x86_avx2_pmins_b:
11553 case Intrinsic::x86_avx2_pmins_w:
11554 case Intrinsic::x86_avx2_pmins_d: {
11557 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11558 case Intrinsic::x86_sse2_pmaxu_b:
11559 case Intrinsic::x86_sse41_pmaxuw:
11560 case Intrinsic::x86_sse41_pmaxud:
11561 case Intrinsic::x86_avx2_pmaxu_b:
11562 case Intrinsic::x86_avx2_pmaxu_w:
11563 case Intrinsic::x86_avx2_pmaxu_d:
11564 Opcode = X86ISD::UMAX;
11566 case Intrinsic::x86_sse2_pminu_b:
11567 case Intrinsic::x86_sse41_pminuw:
11568 case Intrinsic::x86_sse41_pminud:
11569 case Intrinsic::x86_avx2_pminu_b:
11570 case Intrinsic::x86_avx2_pminu_w:
11571 case Intrinsic::x86_avx2_pminu_d:
11572 Opcode = X86ISD::UMIN;
11574 case Intrinsic::x86_sse41_pmaxsb:
11575 case Intrinsic::x86_sse2_pmaxs_w:
11576 case Intrinsic::x86_sse41_pmaxsd:
11577 case Intrinsic::x86_avx2_pmaxs_b:
11578 case Intrinsic::x86_avx2_pmaxs_w:
11579 case Intrinsic::x86_avx2_pmaxs_d:
11580 Opcode = X86ISD::SMAX;
11582 case Intrinsic::x86_sse41_pminsb:
11583 case Intrinsic::x86_sse2_pmins_w:
11584 case Intrinsic::x86_sse41_pminsd:
11585 case Intrinsic::x86_avx2_pmins_b:
11586 case Intrinsic::x86_avx2_pmins_w:
11587 case Intrinsic::x86_avx2_pmins_d:
11588 Opcode = X86ISD::SMIN;
11591 return DAG.getNode(Opcode, dl, Op.getValueType(),
11592 Op.getOperand(1), Op.getOperand(2));
11595 // SSE/SSE2/AVX floating point max/min intrinsics.
11596 case Intrinsic::x86_sse_max_ps:
11597 case Intrinsic::x86_sse2_max_pd:
11598 case Intrinsic::x86_avx_max_ps_256:
11599 case Intrinsic::x86_avx_max_pd_256:
11600 case Intrinsic::x86_sse_min_ps:
11601 case Intrinsic::x86_sse2_min_pd:
11602 case Intrinsic::x86_avx_min_ps_256:
11603 case Intrinsic::x86_avx_min_pd_256: {
11606 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11607 case Intrinsic::x86_sse_max_ps:
11608 case Intrinsic::x86_sse2_max_pd:
11609 case Intrinsic::x86_avx_max_ps_256:
11610 case Intrinsic::x86_avx_max_pd_256:
11611 Opcode = X86ISD::FMAX;
11613 case Intrinsic::x86_sse_min_ps:
11614 case Intrinsic::x86_sse2_min_pd:
11615 case Intrinsic::x86_avx_min_ps_256:
11616 case Intrinsic::x86_avx_min_pd_256:
11617 Opcode = X86ISD::FMIN;
11620 return DAG.getNode(Opcode, dl, Op.getValueType(),
11621 Op.getOperand(1), Op.getOperand(2));
11624 // AVX2 variable shift intrinsics
11625 case Intrinsic::x86_avx2_psllv_d:
11626 case Intrinsic::x86_avx2_psllv_q:
11627 case Intrinsic::x86_avx2_psllv_d_256:
11628 case Intrinsic::x86_avx2_psllv_q_256:
11629 case Intrinsic::x86_avx2_psrlv_d:
11630 case Intrinsic::x86_avx2_psrlv_q:
11631 case Intrinsic::x86_avx2_psrlv_d_256:
11632 case Intrinsic::x86_avx2_psrlv_q_256:
11633 case Intrinsic::x86_avx2_psrav_d:
11634 case Intrinsic::x86_avx2_psrav_d_256: {
11637 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11638 case Intrinsic::x86_avx2_psllv_d:
11639 case Intrinsic::x86_avx2_psllv_q:
11640 case Intrinsic::x86_avx2_psllv_d_256:
11641 case Intrinsic::x86_avx2_psllv_q_256:
11644 case Intrinsic::x86_avx2_psrlv_d:
11645 case Intrinsic::x86_avx2_psrlv_q:
11646 case Intrinsic::x86_avx2_psrlv_d_256:
11647 case Intrinsic::x86_avx2_psrlv_q_256:
11650 case Intrinsic::x86_avx2_psrav_d:
11651 case Intrinsic::x86_avx2_psrav_d_256:
11655 return DAG.getNode(Opcode, dl, Op.getValueType(),
11656 Op.getOperand(1), Op.getOperand(2));
11659 case Intrinsic::x86_ssse3_pshuf_b_128:
11660 case Intrinsic::x86_avx2_pshuf_b:
11661 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11662 Op.getOperand(1), Op.getOperand(2));
11664 case Intrinsic::x86_ssse3_psign_b_128:
11665 case Intrinsic::x86_ssse3_psign_w_128:
11666 case Intrinsic::x86_ssse3_psign_d_128:
11667 case Intrinsic::x86_avx2_psign_b:
11668 case Intrinsic::x86_avx2_psign_w:
11669 case Intrinsic::x86_avx2_psign_d:
11670 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11671 Op.getOperand(1), Op.getOperand(2));
11673 case Intrinsic::x86_sse41_insertps:
11674 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11675 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11677 case Intrinsic::x86_avx_vperm2f128_ps_256:
11678 case Intrinsic::x86_avx_vperm2f128_pd_256:
11679 case Intrinsic::x86_avx_vperm2f128_si_256:
11680 case Intrinsic::x86_avx2_vperm2i128:
11681 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11682 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11684 case Intrinsic::x86_avx2_permd:
11685 case Intrinsic::x86_avx2_permps:
11686 // Operands intentionally swapped. Mask is last operand to intrinsic,
11687 // but second operand for node/instruction.
11688 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11689 Op.getOperand(2), Op.getOperand(1));
11691 case Intrinsic::x86_sse_sqrt_ps:
11692 case Intrinsic::x86_sse2_sqrt_pd:
11693 case Intrinsic::x86_avx_sqrt_ps_256:
11694 case Intrinsic::x86_avx_sqrt_pd_256:
11695 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11697 // ptest and testp intrinsics. The intrinsic these come from are designed to
11698 // return an integer value, not just an instruction so lower it to the ptest
11699 // or testp pattern and a setcc for the result.
11700 case Intrinsic::x86_sse41_ptestz:
11701 case Intrinsic::x86_sse41_ptestc:
11702 case Intrinsic::x86_sse41_ptestnzc:
11703 case Intrinsic::x86_avx_ptestz_256:
11704 case Intrinsic::x86_avx_ptestc_256:
11705 case Intrinsic::x86_avx_ptestnzc_256:
11706 case Intrinsic::x86_avx_vtestz_ps:
11707 case Intrinsic::x86_avx_vtestc_ps:
11708 case Intrinsic::x86_avx_vtestnzc_ps:
11709 case Intrinsic::x86_avx_vtestz_pd:
11710 case Intrinsic::x86_avx_vtestc_pd:
11711 case Intrinsic::x86_avx_vtestnzc_pd:
11712 case Intrinsic::x86_avx_vtestz_ps_256:
11713 case Intrinsic::x86_avx_vtestc_ps_256:
11714 case Intrinsic::x86_avx_vtestnzc_ps_256:
11715 case Intrinsic::x86_avx_vtestz_pd_256:
11716 case Intrinsic::x86_avx_vtestc_pd_256:
11717 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11718 bool IsTestPacked = false;
11721 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11722 case Intrinsic::x86_avx_vtestz_ps:
11723 case Intrinsic::x86_avx_vtestz_pd:
11724 case Intrinsic::x86_avx_vtestz_ps_256:
11725 case Intrinsic::x86_avx_vtestz_pd_256:
11726 IsTestPacked = true; // Fallthrough
11727 case Intrinsic::x86_sse41_ptestz:
11728 case Intrinsic::x86_avx_ptestz_256:
11730 X86CC = X86::COND_E;
11732 case Intrinsic::x86_avx_vtestc_ps:
11733 case Intrinsic::x86_avx_vtestc_pd:
11734 case Intrinsic::x86_avx_vtestc_ps_256:
11735 case Intrinsic::x86_avx_vtestc_pd_256:
11736 IsTestPacked = true; // Fallthrough
11737 case Intrinsic::x86_sse41_ptestc:
11738 case Intrinsic::x86_avx_ptestc_256:
11740 X86CC = X86::COND_B;
11742 case Intrinsic::x86_avx_vtestnzc_ps:
11743 case Intrinsic::x86_avx_vtestnzc_pd:
11744 case Intrinsic::x86_avx_vtestnzc_ps_256:
11745 case Intrinsic::x86_avx_vtestnzc_pd_256:
11746 IsTestPacked = true; // Fallthrough
11747 case Intrinsic::x86_sse41_ptestnzc:
11748 case Intrinsic::x86_avx_ptestnzc_256:
11750 X86CC = X86::COND_A;
11754 SDValue LHS = Op.getOperand(1);
11755 SDValue RHS = Op.getOperand(2);
11756 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11757 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11758 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11759 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11760 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11762 case Intrinsic::x86_avx512_kortestz_w:
11763 case Intrinsic::x86_avx512_kortestc_w: {
11764 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11765 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11766 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11767 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11768 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11769 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11770 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11773 // SSE/AVX shift intrinsics
11774 case Intrinsic::x86_sse2_psll_w:
11775 case Intrinsic::x86_sse2_psll_d:
11776 case Intrinsic::x86_sse2_psll_q:
11777 case Intrinsic::x86_avx2_psll_w:
11778 case Intrinsic::x86_avx2_psll_d:
11779 case Intrinsic::x86_avx2_psll_q:
11780 case Intrinsic::x86_sse2_psrl_w:
11781 case Intrinsic::x86_sse2_psrl_d:
11782 case Intrinsic::x86_sse2_psrl_q:
11783 case Intrinsic::x86_avx2_psrl_w:
11784 case Intrinsic::x86_avx2_psrl_d:
11785 case Intrinsic::x86_avx2_psrl_q:
11786 case Intrinsic::x86_sse2_psra_w:
11787 case Intrinsic::x86_sse2_psra_d:
11788 case Intrinsic::x86_avx2_psra_w:
11789 case Intrinsic::x86_avx2_psra_d: {
11792 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11793 case Intrinsic::x86_sse2_psll_w:
11794 case Intrinsic::x86_sse2_psll_d:
11795 case Intrinsic::x86_sse2_psll_q:
11796 case Intrinsic::x86_avx2_psll_w:
11797 case Intrinsic::x86_avx2_psll_d:
11798 case Intrinsic::x86_avx2_psll_q:
11799 Opcode = X86ISD::VSHL;
11801 case Intrinsic::x86_sse2_psrl_w:
11802 case Intrinsic::x86_sse2_psrl_d:
11803 case Intrinsic::x86_sse2_psrl_q:
11804 case Intrinsic::x86_avx2_psrl_w:
11805 case Intrinsic::x86_avx2_psrl_d:
11806 case Intrinsic::x86_avx2_psrl_q:
11807 Opcode = X86ISD::VSRL;
11809 case Intrinsic::x86_sse2_psra_w:
11810 case Intrinsic::x86_sse2_psra_d:
11811 case Intrinsic::x86_avx2_psra_w:
11812 case Intrinsic::x86_avx2_psra_d:
11813 Opcode = X86ISD::VSRA;
11816 return DAG.getNode(Opcode, dl, Op.getValueType(),
11817 Op.getOperand(1), Op.getOperand(2));
11820 // SSE/AVX immediate shift intrinsics
11821 case Intrinsic::x86_sse2_pslli_w:
11822 case Intrinsic::x86_sse2_pslli_d:
11823 case Intrinsic::x86_sse2_pslli_q:
11824 case Intrinsic::x86_avx2_pslli_w:
11825 case Intrinsic::x86_avx2_pslli_d:
11826 case Intrinsic::x86_avx2_pslli_q:
11827 case Intrinsic::x86_sse2_psrli_w:
11828 case Intrinsic::x86_sse2_psrli_d:
11829 case Intrinsic::x86_sse2_psrli_q:
11830 case Intrinsic::x86_avx2_psrli_w:
11831 case Intrinsic::x86_avx2_psrli_d:
11832 case Intrinsic::x86_avx2_psrli_q:
11833 case Intrinsic::x86_sse2_psrai_w:
11834 case Intrinsic::x86_sse2_psrai_d:
11835 case Intrinsic::x86_avx2_psrai_w:
11836 case Intrinsic::x86_avx2_psrai_d: {
11839 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11840 case Intrinsic::x86_sse2_pslli_w:
11841 case Intrinsic::x86_sse2_pslli_d:
11842 case Intrinsic::x86_sse2_pslli_q:
11843 case Intrinsic::x86_avx2_pslli_w:
11844 case Intrinsic::x86_avx2_pslli_d:
11845 case Intrinsic::x86_avx2_pslli_q:
11846 Opcode = X86ISD::VSHLI;
11848 case Intrinsic::x86_sse2_psrli_w:
11849 case Intrinsic::x86_sse2_psrli_d:
11850 case Intrinsic::x86_sse2_psrli_q:
11851 case Intrinsic::x86_avx2_psrli_w:
11852 case Intrinsic::x86_avx2_psrli_d:
11853 case Intrinsic::x86_avx2_psrli_q:
11854 Opcode = X86ISD::VSRLI;
11856 case Intrinsic::x86_sse2_psrai_w:
11857 case Intrinsic::x86_sse2_psrai_d:
11858 case Intrinsic::x86_avx2_psrai_w:
11859 case Intrinsic::x86_avx2_psrai_d:
11860 Opcode = X86ISD::VSRAI;
11863 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11864 Op.getOperand(1), Op.getOperand(2), DAG);
11867 case Intrinsic::x86_sse42_pcmpistria128:
11868 case Intrinsic::x86_sse42_pcmpestria128:
11869 case Intrinsic::x86_sse42_pcmpistric128:
11870 case Intrinsic::x86_sse42_pcmpestric128:
11871 case Intrinsic::x86_sse42_pcmpistrio128:
11872 case Intrinsic::x86_sse42_pcmpestrio128:
11873 case Intrinsic::x86_sse42_pcmpistris128:
11874 case Intrinsic::x86_sse42_pcmpestris128:
11875 case Intrinsic::x86_sse42_pcmpistriz128:
11876 case Intrinsic::x86_sse42_pcmpestriz128: {
11880 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11881 case Intrinsic::x86_sse42_pcmpistria128:
11882 Opcode = X86ISD::PCMPISTRI;
11883 X86CC = X86::COND_A;
11885 case Intrinsic::x86_sse42_pcmpestria128:
11886 Opcode = X86ISD::PCMPESTRI;
11887 X86CC = X86::COND_A;
11889 case Intrinsic::x86_sse42_pcmpistric128:
11890 Opcode = X86ISD::PCMPISTRI;
11891 X86CC = X86::COND_B;
11893 case Intrinsic::x86_sse42_pcmpestric128:
11894 Opcode = X86ISD::PCMPESTRI;
11895 X86CC = X86::COND_B;
11897 case Intrinsic::x86_sse42_pcmpistrio128:
11898 Opcode = X86ISD::PCMPISTRI;
11899 X86CC = X86::COND_O;
11901 case Intrinsic::x86_sse42_pcmpestrio128:
11902 Opcode = X86ISD::PCMPESTRI;
11903 X86CC = X86::COND_O;
11905 case Intrinsic::x86_sse42_pcmpistris128:
11906 Opcode = X86ISD::PCMPISTRI;
11907 X86CC = X86::COND_S;
11909 case Intrinsic::x86_sse42_pcmpestris128:
11910 Opcode = X86ISD::PCMPESTRI;
11911 X86CC = X86::COND_S;
11913 case Intrinsic::x86_sse42_pcmpistriz128:
11914 Opcode = X86ISD::PCMPISTRI;
11915 X86CC = X86::COND_E;
11917 case Intrinsic::x86_sse42_pcmpestriz128:
11918 Opcode = X86ISD::PCMPESTRI;
11919 X86CC = X86::COND_E;
11922 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11923 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11924 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11925 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11926 DAG.getConstant(X86CC, MVT::i8),
11927 SDValue(PCMP.getNode(), 1));
11928 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11931 case Intrinsic::x86_sse42_pcmpistri128:
11932 case Intrinsic::x86_sse42_pcmpestri128: {
11934 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11935 Opcode = X86ISD::PCMPISTRI;
11937 Opcode = X86ISD::PCMPESTRI;
11939 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11940 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11941 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11943 case Intrinsic::x86_fma_vfmadd_ps:
11944 case Intrinsic::x86_fma_vfmadd_pd:
11945 case Intrinsic::x86_fma_vfmsub_ps:
11946 case Intrinsic::x86_fma_vfmsub_pd:
11947 case Intrinsic::x86_fma_vfnmadd_ps:
11948 case Intrinsic::x86_fma_vfnmadd_pd:
11949 case Intrinsic::x86_fma_vfnmsub_ps:
11950 case Intrinsic::x86_fma_vfnmsub_pd:
11951 case Intrinsic::x86_fma_vfmaddsub_ps:
11952 case Intrinsic::x86_fma_vfmaddsub_pd:
11953 case Intrinsic::x86_fma_vfmsubadd_ps:
11954 case Intrinsic::x86_fma_vfmsubadd_pd:
11955 case Intrinsic::x86_fma_vfmadd_ps_256:
11956 case Intrinsic::x86_fma_vfmadd_pd_256:
11957 case Intrinsic::x86_fma_vfmsub_ps_256:
11958 case Intrinsic::x86_fma_vfmsub_pd_256:
11959 case Intrinsic::x86_fma_vfnmadd_ps_256:
11960 case Intrinsic::x86_fma_vfnmadd_pd_256:
11961 case Intrinsic::x86_fma_vfnmsub_ps_256:
11962 case Intrinsic::x86_fma_vfnmsub_pd_256:
11963 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11964 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11965 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11966 case Intrinsic::x86_fma_vfmsubadd_pd_256:
11967 case Intrinsic::x86_fma_vfmadd_ps_512:
11968 case Intrinsic::x86_fma_vfmadd_pd_512:
11969 case Intrinsic::x86_fma_vfmsub_ps_512:
11970 case Intrinsic::x86_fma_vfmsub_pd_512:
11971 case Intrinsic::x86_fma_vfnmadd_ps_512:
11972 case Intrinsic::x86_fma_vfnmadd_pd_512:
11973 case Intrinsic::x86_fma_vfnmsub_ps_512:
11974 case Intrinsic::x86_fma_vfnmsub_pd_512:
11975 case Intrinsic::x86_fma_vfmaddsub_ps_512:
11976 case Intrinsic::x86_fma_vfmaddsub_pd_512:
11977 case Intrinsic::x86_fma_vfmsubadd_ps_512:
11978 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11981 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11982 case Intrinsic::x86_fma_vfmadd_ps:
11983 case Intrinsic::x86_fma_vfmadd_pd:
11984 case Intrinsic::x86_fma_vfmadd_ps_256:
11985 case Intrinsic::x86_fma_vfmadd_pd_256:
11986 case Intrinsic::x86_fma_vfmadd_ps_512:
11987 case Intrinsic::x86_fma_vfmadd_pd_512:
11988 Opc = X86ISD::FMADD;
11990 case Intrinsic::x86_fma_vfmsub_ps:
11991 case Intrinsic::x86_fma_vfmsub_pd:
11992 case Intrinsic::x86_fma_vfmsub_ps_256:
11993 case Intrinsic::x86_fma_vfmsub_pd_256:
11994 case Intrinsic::x86_fma_vfmsub_ps_512:
11995 case Intrinsic::x86_fma_vfmsub_pd_512:
11996 Opc = X86ISD::FMSUB;
11998 case Intrinsic::x86_fma_vfnmadd_ps:
11999 case Intrinsic::x86_fma_vfnmadd_pd:
12000 case Intrinsic::x86_fma_vfnmadd_ps_256:
12001 case Intrinsic::x86_fma_vfnmadd_pd_256:
12002 case Intrinsic::x86_fma_vfnmadd_ps_512:
12003 case Intrinsic::x86_fma_vfnmadd_pd_512:
12004 Opc = X86ISD::FNMADD;
12006 case Intrinsic::x86_fma_vfnmsub_ps:
12007 case Intrinsic::x86_fma_vfnmsub_pd:
12008 case Intrinsic::x86_fma_vfnmsub_ps_256:
12009 case Intrinsic::x86_fma_vfnmsub_pd_256:
12010 case Intrinsic::x86_fma_vfnmsub_ps_512:
12011 case Intrinsic::x86_fma_vfnmsub_pd_512:
12012 Opc = X86ISD::FNMSUB;
12014 case Intrinsic::x86_fma_vfmaddsub_ps:
12015 case Intrinsic::x86_fma_vfmaddsub_pd:
12016 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12017 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12018 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12019 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12020 Opc = X86ISD::FMADDSUB;
12022 case Intrinsic::x86_fma_vfmsubadd_ps:
12023 case Intrinsic::x86_fma_vfmsubadd_pd:
12024 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12025 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12026 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12027 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12028 Opc = X86ISD::FMSUBADD;
12032 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12033 Op.getOperand(2), Op.getOperand(3));
12038 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12039 SDValue Base, SDValue Index,
12040 SDValue ScaleOp, SDValue Chain,
12041 const X86Subtarget * Subtarget) {
12043 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12044 assert(C && "Invalid scale type");
12045 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12046 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12047 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12048 Index.getSimpleValueType().getVectorNumElements());
12049 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12050 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12051 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12052 SDValue Segment = DAG.getRegister(0, MVT::i32);
12053 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12054 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12055 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12056 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12059 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12060 SDValue Src, SDValue Mask, SDValue Base,
12061 SDValue Index, SDValue ScaleOp, SDValue Chain,
12062 const X86Subtarget * Subtarget) {
12064 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12065 assert(C && "Invalid scale type");
12066 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12067 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12068 Index.getSimpleValueType().getVectorNumElements());
12069 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12070 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12071 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12072 SDValue Segment = DAG.getRegister(0, MVT::i32);
12073 if (Src.getOpcode() == ISD::UNDEF)
12074 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12075 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12076 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12077 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12078 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12081 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12082 SDValue Src, SDValue Base, SDValue Index,
12083 SDValue ScaleOp, SDValue Chain) {
12085 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12086 assert(C && "Invalid scale type");
12087 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12088 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12089 SDValue Segment = DAG.getRegister(0, MVT::i32);
12090 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12091 Index.getSimpleValueType().getVectorNumElements());
12092 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12093 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12094 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12095 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12096 return SDValue(Res, 1);
12099 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12100 SDValue Src, SDValue Mask, SDValue Base,
12101 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12103 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12104 assert(C && "Invalid scale type");
12105 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12106 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12107 SDValue Segment = DAG.getRegister(0, MVT::i32);
12108 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12109 Index.getSimpleValueType().getVectorNumElements());
12110 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12111 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12112 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12113 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12114 return SDValue(Res, 1);
12117 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12118 SelectionDAG &DAG) {
12120 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12122 default: return SDValue(); // Don't custom lower most intrinsics.
12124 // RDRAND/RDSEED intrinsics.
12125 case Intrinsic::x86_rdrand_16:
12126 case Intrinsic::x86_rdrand_32:
12127 case Intrinsic::x86_rdrand_64:
12128 case Intrinsic::x86_rdseed_16:
12129 case Intrinsic::x86_rdseed_32:
12130 case Intrinsic::x86_rdseed_64: {
12131 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12132 IntNo == Intrinsic::x86_rdseed_32 ||
12133 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12135 // Emit the node with the right value type.
12136 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12137 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12139 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12140 // Otherwise return the value from Rand, which is always 0, casted to i32.
12141 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12142 DAG.getConstant(1, Op->getValueType(1)),
12143 DAG.getConstant(X86::COND_B, MVT::i32),
12144 SDValue(Result.getNode(), 1) };
12145 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12146 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12147 Ops, array_lengthof(Ops));
12149 // Return { result, isValid, chain }.
12150 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12151 SDValue(Result.getNode(), 2));
12153 //int_gather(index, base, scale);
12154 case Intrinsic::x86_avx512_gather_qpd_512:
12155 case Intrinsic::x86_avx512_gather_qps_512:
12156 case Intrinsic::x86_avx512_gather_dpd_512:
12157 case Intrinsic::x86_avx512_gather_qpi_512:
12158 case Intrinsic::x86_avx512_gather_qpq_512:
12159 case Intrinsic::x86_avx512_gather_dpq_512:
12160 case Intrinsic::x86_avx512_gather_dps_512:
12161 case Intrinsic::x86_avx512_gather_dpi_512: {
12164 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12165 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12166 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12167 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12168 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12169 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12170 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12171 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12172 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12174 SDValue Chain = Op.getOperand(0);
12175 SDValue Index = Op.getOperand(2);
12176 SDValue Base = Op.getOperand(3);
12177 SDValue Scale = Op.getOperand(4);
12178 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12180 //int_gather_mask(v1, mask, index, base, scale);
12181 case Intrinsic::x86_avx512_gather_qps_mask_512:
12182 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12183 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12184 case Intrinsic::x86_avx512_gather_dps_mask_512:
12185 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12186 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12187 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12188 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12191 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12192 case Intrinsic::x86_avx512_gather_qps_mask_512:
12193 Opc = X86::VGATHERQPSZrm; break;
12194 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12195 Opc = X86::VGATHERQPDZrm; break;
12196 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12197 Opc = X86::VGATHERDPDZrm; break;
12198 case Intrinsic::x86_avx512_gather_dps_mask_512:
12199 Opc = X86::VGATHERDPSZrm; break;
12200 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12201 Opc = X86::VPGATHERQDZrm; break;
12202 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12203 Opc = X86::VPGATHERQQZrm; break;
12204 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12205 Opc = X86::VPGATHERDDZrm; break;
12206 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12207 Opc = X86::VPGATHERDQZrm; break;
12209 SDValue Chain = Op.getOperand(0);
12210 SDValue Src = Op.getOperand(2);
12211 SDValue Mask = Op.getOperand(3);
12212 SDValue Index = Op.getOperand(4);
12213 SDValue Base = Op.getOperand(5);
12214 SDValue Scale = Op.getOperand(6);
12215 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12218 //int_scatter(base, index, v1, scale);
12219 case Intrinsic::x86_avx512_scatter_qpd_512:
12220 case Intrinsic::x86_avx512_scatter_qps_512:
12221 case Intrinsic::x86_avx512_scatter_dpd_512:
12222 case Intrinsic::x86_avx512_scatter_qpi_512:
12223 case Intrinsic::x86_avx512_scatter_qpq_512:
12224 case Intrinsic::x86_avx512_scatter_dpq_512:
12225 case Intrinsic::x86_avx512_scatter_dps_512:
12226 case Intrinsic::x86_avx512_scatter_dpi_512: {
12229 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12230 case Intrinsic::x86_avx512_scatter_qpd_512:
12231 Opc = X86::VSCATTERQPDZmr; break;
12232 case Intrinsic::x86_avx512_scatter_qps_512:
12233 Opc = X86::VSCATTERQPSZmr; break;
12234 case Intrinsic::x86_avx512_scatter_dpd_512:
12235 Opc = X86::VSCATTERDPDZmr; break;
12236 case Intrinsic::x86_avx512_scatter_dps_512:
12237 Opc = X86::VSCATTERDPSZmr; break;
12238 case Intrinsic::x86_avx512_scatter_qpi_512:
12239 Opc = X86::VPSCATTERQDZmr; break;
12240 case Intrinsic::x86_avx512_scatter_qpq_512:
12241 Opc = X86::VPSCATTERQQZmr; break;
12242 case Intrinsic::x86_avx512_scatter_dpq_512:
12243 Opc = X86::VPSCATTERDQZmr; break;
12244 case Intrinsic::x86_avx512_scatter_dpi_512:
12245 Opc = X86::VPSCATTERDDZmr; break;
12247 SDValue Chain = Op.getOperand(0);
12248 SDValue Base = Op.getOperand(2);
12249 SDValue Index = Op.getOperand(3);
12250 SDValue Src = Op.getOperand(4);
12251 SDValue Scale = Op.getOperand(5);
12252 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12254 //int_scatter_mask(base, mask, index, v1, scale);
12255 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12256 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12257 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12258 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12259 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12260 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12261 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12262 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12265 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12266 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12267 Opc = X86::VSCATTERQPDZmr; break;
12268 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12269 Opc = X86::VSCATTERQPSZmr; break;
12270 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12271 Opc = X86::VSCATTERDPDZmr; break;
12272 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12273 Opc = X86::VSCATTERDPSZmr; break;
12274 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12275 Opc = X86::VPSCATTERQDZmr; break;
12276 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12277 Opc = X86::VPSCATTERQQZmr; break;
12278 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12279 Opc = X86::VPSCATTERDQZmr; break;
12280 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12281 Opc = X86::VPSCATTERDDZmr; break;
12283 SDValue Chain = Op.getOperand(0);
12284 SDValue Base = Op.getOperand(2);
12285 SDValue Mask = Op.getOperand(3);
12286 SDValue Index = Op.getOperand(4);
12287 SDValue Src = Op.getOperand(5);
12288 SDValue Scale = Op.getOperand(6);
12289 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12291 // XTEST intrinsics.
12292 case Intrinsic::x86_xtest: {
12293 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12294 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12295 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12296 DAG.getConstant(X86::COND_NE, MVT::i8),
12298 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12299 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12300 Ret, SDValue(InTrans.getNode(), 1));
12305 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12306 SelectionDAG &DAG) const {
12307 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12308 MFI->setReturnAddressIsTaken(true);
12310 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12313 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12315 EVT PtrVT = getPointerTy();
12318 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12319 const X86RegisterInfo *RegInfo =
12320 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12321 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12322 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12323 DAG.getNode(ISD::ADD, dl, PtrVT,
12324 FrameAddr, Offset),
12325 MachinePointerInfo(), false, false, false, 0);
12328 // Just load the return address.
12329 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12330 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12331 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12334 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12335 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12336 MFI->setFrameAddressIsTaken(true);
12338 EVT VT = Op.getValueType();
12339 SDLoc dl(Op); // FIXME probably not meaningful
12340 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12341 const X86RegisterInfo *RegInfo =
12342 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12343 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12344 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12345 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12346 "Invalid Frame Register!");
12347 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12349 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12350 MachinePointerInfo(),
12351 false, false, false, 0);
12355 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12356 SelectionDAG &DAG) const {
12357 const X86RegisterInfo *RegInfo =
12358 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12359 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12362 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12363 SDValue Chain = Op.getOperand(0);
12364 SDValue Offset = Op.getOperand(1);
12365 SDValue Handler = Op.getOperand(2);
12368 EVT PtrVT = getPointerTy();
12369 const X86RegisterInfo *RegInfo =
12370 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12371 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12372 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12373 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12374 "Invalid Frame Register!");
12375 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12376 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12378 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12379 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12380 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12381 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12383 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12385 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12386 DAG.getRegister(StoreAddrReg, PtrVT));
12389 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12390 SelectionDAG &DAG) const {
12392 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12393 DAG.getVTList(MVT::i32, MVT::Other),
12394 Op.getOperand(0), Op.getOperand(1));
12397 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12398 SelectionDAG &DAG) const {
12400 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12401 Op.getOperand(0), Op.getOperand(1));
12404 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12405 return Op.getOperand(0);
12408 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12409 SelectionDAG &DAG) const {
12410 SDValue Root = Op.getOperand(0);
12411 SDValue Trmp = Op.getOperand(1); // trampoline
12412 SDValue FPtr = Op.getOperand(2); // nested function
12413 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12416 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12417 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12419 if (Subtarget->is64Bit()) {
12420 SDValue OutChains[6];
12422 // Large code-model.
12423 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12424 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12426 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12427 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12429 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12431 // Load the pointer to the nested function into R11.
12432 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12433 SDValue Addr = Trmp;
12434 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12435 Addr, MachinePointerInfo(TrmpAddr),
12438 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12439 DAG.getConstant(2, MVT::i64));
12440 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12441 MachinePointerInfo(TrmpAddr, 2),
12444 // Load the 'nest' parameter value into R10.
12445 // R10 is specified in X86CallingConv.td
12446 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12447 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12448 DAG.getConstant(10, MVT::i64));
12449 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12450 Addr, MachinePointerInfo(TrmpAddr, 10),
12453 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12454 DAG.getConstant(12, MVT::i64));
12455 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12456 MachinePointerInfo(TrmpAddr, 12),
12459 // Jump to the nested function.
12460 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12461 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12462 DAG.getConstant(20, MVT::i64));
12463 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12464 Addr, MachinePointerInfo(TrmpAddr, 20),
12467 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12468 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12469 DAG.getConstant(22, MVT::i64));
12470 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12471 MachinePointerInfo(TrmpAddr, 22),
12474 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12476 const Function *Func =
12477 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12478 CallingConv::ID CC = Func->getCallingConv();
12483 llvm_unreachable("Unsupported calling convention");
12484 case CallingConv::C:
12485 case CallingConv::X86_StdCall: {
12486 // Pass 'nest' parameter in ECX.
12487 // Must be kept in sync with X86CallingConv.td
12488 NestReg = X86::ECX;
12490 // Check that ECX wasn't needed by an 'inreg' parameter.
12491 FunctionType *FTy = Func->getFunctionType();
12492 const AttributeSet &Attrs = Func->getAttributes();
12494 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12495 unsigned InRegCount = 0;
12498 for (FunctionType::param_iterator I = FTy->param_begin(),
12499 E = FTy->param_end(); I != E; ++I, ++Idx)
12500 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12501 // FIXME: should only count parameters that are lowered to integers.
12502 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12504 if (InRegCount > 2) {
12505 report_fatal_error("Nest register in use - reduce number of inreg"
12511 case CallingConv::X86_FastCall:
12512 case CallingConv::X86_ThisCall:
12513 case CallingConv::Fast:
12514 // Pass 'nest' parameter in EAX.
12515 // Must be kept in sync with X86CallingConv.td
12516 NestReg = X86::EAX;
12520 SDValue OutChains[4];
12521 SDValue Addr, Disp;
12523 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12524 DAG.getConstant(10, MVT::i32));
12525 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12527 // This is storing the opcode for MOV32ri.
12528 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12529 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12530 OutChains[0] = DAG.getStore(Root, dl,
12531 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12532 Trmp, MachinePointerInfo(TrmpAddr),
12535 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12536 DAG.getConstant(1, MVT::i32));
12537 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12538 MachinePointerInfo(TrmpAddr, 1),
12541 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12542 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12543 DAG.getConstant(5, MVT::i32));
12544 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12545 MachinePointerInfo(TrmpAddr, 5),
12548 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12549 DAG.getConstant(6, MVT::i32));
12550 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12551 MachinePointerInfo(TrmpAddr, 6),
12554 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12558 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12559 SelectionDAG &DAG) const {
12561 The rounding mode is in bits 11:10 of FPSR, and has the following
12563 00 Round to nearest
12568 FLT_ROUNDS, on the other hand, expects the following:
12575 To perform the conversion, we do:
12576 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12579 MachineFunction &MF = DAG.getMachineFunction();
12580 const TargetMachine &TM = MF.getTarget();
12581 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12582 unsigned StackAlignment = TFI.getStackAlignment();
12583 MVT VT = Op.getSimpleValueType();
12586 // Save FP Control Word to stack slot
12587 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12588 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12590 MachineMemOperand *MMO =
12591 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12592 MachineMemOperand::MOStore, 2, 2);
12594 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12595 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12596 DAG.getVTList(MVT::Other),
12597 Ops, array_lengthof(Ops), MVT::i16,
12600 // Load FP Control Word from stack slot
12601 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12602 MachinePointerInfo(), false, false, false, 0);
12604 // Transform as necessary
12606 DAG.getNode(ISD::SRL, DL, MVT::i16,
12607 DAG.getNode(ISD::AND, DL, MVT::i16,
12608 CWD, DAG.getConstant(0x800, MVT::i16)),
12609 DAG.getConstant(11, MVT::i8));
12611 DAG.getNode(ISD::SRL, DL, MVT::i16,
12612 DAG.getNode(ISD::AND, DL, MVT::i16,
12613 CWD, DAG.getConstant(0x400, MVT::i16)),
12614 DAG.getConstant(9, MVT::i8));
12617 DAG.getNode(ISD::AND, DL, MVT::i16,
12618 DAG.getNode(ISD::ADD, DL, MVT::i16,
12619 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12620 DAG.getConstant(1, MVT::i16)),
12621 DAG.getConstant(3, MVT::i16));
12623 return DAG.getNode((VT.getSizeInBits() < 16 ?
12624 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12627 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12628 MVT VT = Op.getSimpleValueType();
12630 unsigned NumBits = VT.getSizeInBits();
12633 Op = Op.getOperand(0);
12634 if (VT == MVT::i8) {
12635 // Zero extend to i32 since there is not an i8 bsr.
12637 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12640 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12641 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12642 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12644 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12647 DAG.getConstant(NumBits+NumBits-1, OpVT),
12648 DAG.getConstant(X86::COND_E, MVT::i8),
12651 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12653 // Finally xor with NumBits-1.
12654 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12657 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12661 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12662 MVT VT = Op.getSimpleValueType();
12664 unsigned NumBits = VT.getSizeInBits();
12667 Op = Op.getOperand(0);
12668 if (VT == MVT::i8) {
12669 // Zero extend to i32 since there is not an i8 bsr.
12671 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12674 // Issue a bsr (scan bits in reverse).
12675 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12676 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12678 // And xor with NumBits-1.
12679 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12682 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12686 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12687 MVT VT = Op.getSimpleValueType();
12688 unsigned NumBits = VT.getSizeInBits();
12690 Op = Op.getOperand(0);
12692 // Issue a bsf (scan bits forward) which also sets EFLAGS.
12693 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12694 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12696 // If src is zero (i.e. bsf sets ZF), returns NumBits.
12699 DAG.getConstant(NumBits, VT),
12700 DAG.getConstant(X86::COND_E, MVT::i8),
12703 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12706 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12707 // ones, and then concatenate the result back.
12708 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12709 MVT VT = Op.getSimpleValueType();
12711 assert(VT.is256BitVector() && VT.isInteger() &&
12712 "Unsupported value type for operation");
12714 unsigned NumElems = VT.getVectorNumElements();
12717 // Extract the LHS vectors
12718 SDValue LHS = Op.getOperand(0);
12719 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12720 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12722 // Extract the RHS vectors
12723 SDValue RHS = Op.getOperand(1);
12724 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12725 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12727 MVT EltVT = VT.getVectorElementType();
12728 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12730 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12731 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12732 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12735 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12736 assert(Op.getSimpleValueType().is256BitVector() &&
12737 Op.getSimpleValueType().isInteger() &&
12738 "Only handle AVX 256-bit vector integer operation");
12739 return Lower256IntArith(Op, DAG);
12742 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12743 assert(Op.getSimpleValueType().is256BitVector() &&
12744 Op.getSimpleValueType().isInteger() &&
12745 "Only handle AVX 256-bit vector integer operation");
12746 return Lower256IntArith(Op, DAG);
12749 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12750 SelectionDAG &DAG) {
12752 MVT VT = Op.getSimpleValueType();
12754 // Decompose 256-bit ops into smaller 128-bit ops.
12755 if (VT.is256BitVector() && !Subtarget->hasInt256())
12756 return Lower256IntArith(Op, DAG);
12758 SDValue A = Op.getOperand(0);
12759 SDValue B = Op.getOperand(1);
12761 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12762 if (VT == MVT::v4i32) {
12763 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12764 "Should not custom lower when pmuldq is available!");
12766 // Extract the odd parts.
12767 static const int UnpackMask[] = { 1, -1, 3, -1 };
12768 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12769 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12771 // Multiply the even parts.
12772 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12773 // Now multiply odd parts.
12774 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12776 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12777 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12779 // Merge the two vectors back together with a shuffle. This expands into 2
12781 static const int ShufMask[] = { 0, 4, 2, 6 };
12782 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12785 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12786 "Only know how to lower V2I64/V4I64/V8I64 multiply");
12788 // Ahi = psrlqi(a, 32);
12789 // Bhi = psrlqi(b, 32);
12791 // AloBlo = pmuludq(a, b);
12792 // AloBhi = pmuludq(a, Bhi);
12793 // AhiBlo = pmuludq(Ahi, b);
12795 // AloBhi = psllqi(AloBhi, 32);
12796 // AhiBlo = psllqi(AhiBlo, 32);
12797 // return AloBlo + AloBhi + AhiBlo;
12799 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12800 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12802 // Bit cast to 32-bit vectors for MULUDQ
12803 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12804 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12805 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12806 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12807 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12808 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12810 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12811 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12812 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12814 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12815 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12817 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12818 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12821 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12822 MVT VT = Op.getSimpleValueType();
12823 MVT EltTy = VT.getVectorElementType();
12824 unsigned NumElts = VT.getVectorNumElements();
12825 SDValue N0 = Op.getOperand(0);
12828 // Lower sdiv X, pow2-const.
12829 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12833 APInt SplatValue, SplatUndef;
12834 unsigned SplatBitSize;
12836 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12838 EltTy.getSizeInBits() < SplatBitSize)
12841 if ((SplatValue != 0) &&
12842 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12843 unsigned Lg2 = SplatValue.countTrailingZeros();
12844 // Splat the sign bit.
12845 SmallVector<SDValue, 16> Sz(NumElts,
12846 DAG.getConstant(EltTy.getSizeInBits() - 1,
12848 SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12849 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12851 // Add (N0 < 0) ? abs2 - 1 : 0;
12852 SmallVector<SDValue, 16> Amt(NumElts,
12853 DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12855 SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12856 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12858 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12859 SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12860 SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12861 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12864 // If we're dividing by a positive value, we're done. Otherwise, we must
12865 // negate the result.
12866 if (SplatValue.isNonNegative())
12869 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12870 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12871 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12876 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12877 const X86Subtarget *Subtarget) {
12878 MVT VT = Op.getSimpleValueType();
12880 SDValue R = Op.getOperand(0);
12881 SDValue Amt = Op.getOperand(1);
12883 // Optimize shl/srl/sra with constant shift amount.
12884 if (isSplatVector(Amt.getNode())) {
12885 SDValue SclrAmt = Amt->getOperand(0);
12886 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12887 uint64_t ShiftAmt = C->getZExtValue();
12889 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12890 (Subtarget->hasInt256() &&
12891 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12892 (Subtarget->hasAVX512() &&
12893 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12894 if (Op.getOpcode() == ISD::SHL)
12895 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12897 if (Op.getOpcode() == ISD::SRL)
12898 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12900 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12901 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12905 if (VT == MVT::v16i8) {
12906 if (Op.getOpcode() == ISD::SHL) {
12907 // Make a large shift.
12908 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12909 MVT::v8i16, R, ShiftAmt,
12911 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12912 // Zero out the rightmost bits.
12913 SmallVector<SDValue, 16> V(16,
12914 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12916 return DAG.getNode(ISD::AND, dl, VT, SHL,
12917 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12919 if (Op.getOpcode() == ISD::SRL) {
12920 // Make a large shift.
12921 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12922 MVT::v8i16, R, ShiftAmt,
12924 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12925 // Zero out the leftmost bits.
12926 SmallVector<SDValue, 16> V(16,
12927 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12929 return DAG.getNode(ISD::AND, dl, VT, SRL,
12930 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12932 if (Op.getOpcode() == ISD::SRA) {
12933 if (ShiftAmt == 7) {
12934 // R s>> 7 === R s< 0
12935 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12936 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12939 // R s>> a === ((R u>> a) ^ m) - m
12940 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12941 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12943 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12944 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12945 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12948 llvm_unreachable("Unknown shift opcode.");
12951 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12952 if (Op.getOpcode() == ISD::SHL) {
12953 // Make a large shift.
12954 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12955 MVT::v16i16, R, ShiftAmt,
12957 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12958 // Zero out the rightmost bits.
12959 SmallVector<SDValue, 32> V(32,
12960 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12962 return DAG.getNode(ISD::AND, dl, VT, SHL,
12963 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12965 if (Op.getOpcode() == ISD::SRL) {
12966 // Make a large shift.
12967 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12968 MVT::v16i16, R, ShiftAmt,
12970 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12971 // Zero out the leftmost bits.
12972 SmallVector<SDValue, 32> V(32,
12973 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12975 return DAG.getNode(ISD::AND, dl, VT, SRL,
12976 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12978 if (Op.getOpcode() == ISD::SRA) {
12979 if (ShiftAmt == 7) {
12980 // R s>> 7 === R s< 0
12981 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12982 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12985 // R s>> a === ((R u>> a) ^ m) - m
12986 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12987 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12989 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12990 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12991 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12994 llvm_unreachable("Unknown shift opcode.");
12999 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13000 if (!Subtarget->is64Bit() &&
13001 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13002 Amt.getOpcode() == ISD::BITCAST &&
13003 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13004 Amt = Amt.getOperand(0);
13005 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13006 VT.getVectorNumElements();
13007 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13008 uint64_t ShiftAmt = 0;
13009 for (unsigned i = 0; i != Ratio; ++i) {
13010 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13014 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13016 // Check remaining shift amounts.
13017 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13018 uint64_t ShAmt = 0;
13019 for (unsigned j = 0; j != Ratio; ++j) {
13020 ConstantSDNode *C =
13021 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13025 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13027 if (ShAmt != ShiftAmt)
13030 switch (Op.getOpcode()) {
13032 llvm_unreachable("Unknown shift opcode!");
13034 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13037 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13040 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13048 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13049 const X86Subtarget* Subtarget) {
13050 MVT VT = Op.getSimpleValueType();
13052 SDValue R = Op.getOperand(0);
13053 SDValue Amt = Op.getOperand(1);
13055 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13056 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13057 (Subtarget->hasInt256() &&
13058 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13059 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13060 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13062 EVT EltVT = VT.getVectorElementType();
13064 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13065 unsigned NumElts = VT.getVectorNumElements();
13067 for (i = 0; i != NumElts; ++i) {
13068 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13072 for (j = i; j != NumElts; ++j) {
13073 SDValue Arg = Amt.getOperand(j);
13074 if (Arg.getOpcode() == ISD::UNDEF) continue;
13075 if (Arg != Amt.getOperand(i))
13078 if (i != NumElts && j == NumElts)
13079 BaseShAmt = Amt.getOperand(i);
13081 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13082 Amt = Amt.getOperand(0);
13083 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13084 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13085 SDValue InVec = Amt.getOperand(0);
13086 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13087 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13089 for (; i != NumElts; ++i) {
13090 SDValue Arg = InVec.getOperand(i);
13091 if (Arg.getOpcode() == ISD::UNDEF) continue;
13095 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13096 if (ConstantSDNode *C =
13097 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13098 unsigned SplatIdx =
13099 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13100 if (C->getZExtValue() == SplatIdx)
13101 BaseShAmt = InVec.getOperand(1);
13104 if (BaseShAmt.getNode() == 0)
13105 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13106 DAG.getIntPtrConstant(0));
13110 if (BaseShAmt.getNode()) {
13111 if (EltVT.bitsGT(MVT::i32))
13112 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13113 else if (EltVT.bitsLT(MVT::i32))
13114 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13116 switch (Op.getOpcode()) {
13118 llvm_unreachable("Unknown shift opcode!");
13120 switch (VT.SimpleTy) {
13121 default: return SDValue();
13130 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13133 switch (VT.SimpleTy) {
13134 default: return SDValue();
13141 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13144 switch (VT.SimpleTy) {
13145 default: return SDValue();
13154 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13160 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13161 if (!Subtarget->is64Bit() &&
13162 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13163 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13164 Amt.getOpcode() == ISD::BITCAST &&
13165 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13166 Amt = Amt.getOperand(0);
13167 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13168 VT.getVectorNumElements();
13169 std::vector<SDValue> Vals(Ratio);
13170 for (unsigned i = 0; i != Ratio; ++i)
13171 Vals[i] = Amt.getOperand(i);
13172 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13173 for (unsigned j = 0; j != Ratio; ++j)
13174 if (Vals[j] != Amt.getOperand(i + j))
13177 switch (Op.getOpcode()) {
13179 llvm_unreachable("Unknown shift opcode!");
13181 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13183 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13185 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13192 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13193 SelectionDAG &DAG) {
13195 MVT VT = Op.getSimpleValueType();
13197 SDValue R = Op.getOperand(0);
13198 SDValue Amt = Op.getOperand(1);
13201 if (!Subtarget->hasSSE2())
13204 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13208 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13212 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13214 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13215 if (Subtarget->hasInt256()) {
13216 if (Op.getOpcode() == ISD::SRL &&
13217 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13218 VT == MVT::v4i64 || VT == MVT::v8i32))
13220 if (Op.getOpcode() == ISD::SHL &&
13221 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13222 VT == MVT::v4i64 || VT == MVT::v8i32))
13224 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13228 // If possible, lower this packed shift into a vector multiply instead of
13229 // expanding it into a sequence of scalar shifts.
13230 // Do this only if the vector shift count is a constant build_vector.
13231 if (Op.getOpcode() == ISD::SHL &&
13232 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13233 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13234 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13235 SmallVector<SDValue, 8> Elts;
13236 EVT SVT = VT.getScalarType();
13237 unsigned SVTBits = SVT.getSizeInBits();
13238 const APInt &One = APInt(SVTBits, 1);
13239 unsigned NumElems = VT.getVectorNumElements();
13241 for (unsigned i=0; i !=NumElems; ++i) {
13242 SDValue Op = Amt->getOperand(i);
13243 if (Op->getOpcode() == ISD::UNDEF) {
13244 Elts.push_back(Op);
13248 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13249 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13250 uint64_t ShAmt = C.getZExtValue();
13251 if (ShAmt >= SVTBits) {
13252 Elts.push_back(DAG.getUNDEF(SVT));
13255 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13257 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13258 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13261 // Lower SHL with variable shift amount.
13262 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13263 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13265 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13266 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13267 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13268 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13271 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13272 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13275 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13276 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13278 // Turn 'a' into a mask suitable for VSELECT
13279 SDValue VSelM = DAG.getConstant(0x80, VT);
13280 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13281 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13283 SDValue CM1 = DAG.getConstant(0x0f, VT);
13284 SDValue CM2 = DAG.getConstant(0x3f, VT);
13286 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13287 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13288 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13289 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13290 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13293 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13294 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13295 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13297 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13298 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13299 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13300 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13301 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13304 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13305 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13306 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13308 // return VSELECT(r, r+r, a);
13309 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13310 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13314 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13315 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13316 // solution better.
13317 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13318 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13320 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13321 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13322 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13323 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13324 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13327 // Decompose 256-bit shifts into smaller 128-bit shifts.
13328 if (VT.is256BitVector()) {
13329 unsigned NumElems = VT.getVectorNumElements();
13330 MVT EltVT = VT.getVectorElementType();
13331 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13333 // Extract the two vectors
13334 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13335 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13337 // Recreate the shift amount vectors
13338 SDValue Amt1, Amt2;
13339 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13340 // Constant shift amount
13341 SmallVector<SDValue, 4> Amt1Csts;
13342 SmallVector<SDValue, 4> Amt2Csts;
13343 for (unsigned i = 0; i != NumElems/2; ++i)
13344 Amt1Csts.push_back(Amt->getOperand(i));
13345 for (unsigned i = NumElems/2; i != NumElems; ++i)
13346 Amt2Csts.push_back(Amt->getOperand(i));
13348 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13349 &Amt1Csts[0], NumElems/2);
13350 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13351 &Amt2Csts[0], NumElems/2);
13353 // Variable shift amount
13354 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13355 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13358 // Issue new vector shifts for the smaller types
13359 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13360 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13362 // Concatenate the result back
13363 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13369 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13370 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13371 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13372 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13373 // has only one use.
13374 SDNode *N = Op.getNode();
13375 SDValue LHS = N->getOperand(0);
13376 SDValue RHS = N->getOperand(1);
13377 unsigned BaseOp = 0;
13380 switch (Op.getOpcode()) {
13381 default: llvm_unreachable("Unknown ovf instruction!");
13383 // A subtract of one will be selected as a INC. Note that INC doesn't
13384 // set CF, so we can't do this for UADDO.
13385 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13387 BaseOp = X86ISD::INC;
13388 Cond = X86::COND_O;
13391 BaseOp = X86ISD::ADD;
13392 Cond = X86::COND_O;
13395 BaseOp = X86ISD::ADD;
13396 Cond = X86::COND_B;
13399 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13400 // set CF, so we can't do this for USUBO.
13401 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13403 BaseOp = X86ISD::DEC;
13404 Cond = X86::COND_O;
13407 BaseOp = X86ISD::SUB;
13408 Cond = X86::COND_O;
13411 BaseOp = X86ISD::SUB;
13412 Cond = X86::COND_B;
13415 BaseOp = X86ISD::SMUL;
13416 Cond = X86::COND_O;
13418 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13419 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13421 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13424 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13425 DAG.getConstant(X86::COND_O, MVT::i32),
13426 SDValue(Sum.getNode(), 2));
13428 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13432 // Also sets EFLAGS.
13433 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13434 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13437 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13438 DAG.getConstant(Cond, MVT::i32),
13439 SDValue(Sum.getNode(), 1));
13441 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13444 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13445 SelectionDAG &DAG) const {
13447 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13448 MVT VT = Op.getSimpleValueType();
13450 if (!Subtarget->hasSSE2() || !VT.isVector())
13453 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13454 ExtraVT.getScalarType().getSizeInBits();
13456 switch (VT.SimpleTy) {
13457 default: return SDValue();
13460 if (!Subtarget->hasFp256())
13462 if (!Subtarget->hasInt256()) {
13463 // needs to be split
13464 unsigned NumElems = VT.getVectorNumElements();
13466 // Extract the LHS vectors
13467 SDValue LHS = Op.getOperand(0);
13468 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13469 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13471 MVT EltVT = VT.getVectorElementType();
13472 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13474 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13475 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13476 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13478 SDValue Extra = DAG.getValueType(ExtraVT);
13480 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13481 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13483 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13488 SDValue Op0 = Op.getOperand(0);
13489 SDValue Op00 = Op0.getOperand(0);
13491 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13492 if (Op0.getOpcode() == ISD::BITCAST &&
13493 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13494 // (sext (vzext x)) -> (vsext x)
13495 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13496 if (Tmp1.getNode()) {
13497 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13498 // This folding is only valid when the in-reg type is a vector of i8,
13500 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13501 ExtraEltVT == MVT::i32) {
13502 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13503 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13504 "This optimization is invalid without a VZEXT.");
13505 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13511 // If the above didn't work, then just use Shift-Left + Shift-Right.
13512 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13514 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13520 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13521 SelectionDAG &DAG) {
13523 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13524 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13525 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13526 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13528 // The only fence that needs an instruction is a sequentially-consistent
13529 // cross-thread fence.
13530 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13531 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13532 // no-sse2). There isn't any reason to disable it if the target processor
13534 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13535 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13537 SDValue Chain = Op.getOperand(0);
13538 SDValue Zero = DAG.getConstant(0, MVT::i32);
13540 DAG.getRegister(X86::ESP, MVT::i32), // Base
13541 DAG.getTargetConstant(1, MVT::i8), // Scale
13542 DAG.getRegister(0, MVT::i32), // Index
13543 DAG.getTargetConstant(0, MVT::i32), // Disp
13544 DAG.getRegister(0, MVT::i32), // Segment.
13548 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13549 return SDValue(Res, 0);
13552 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13553 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13556 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13557 SelectionDAG &DAG) {
13558 MVT T = Op.getSimpleValueType();
13562 switch(T.SimpleTy) {
13563 default: llvm_unreachable("Invalid value type!");
13564 case MVT::i8: Reg = X86::AL; size = 1; break;
13565 case MVT::i16: Reg = X86::AX; size = 2; break;
13566 case MVT::i32: Reg = X86::EAX; size = 4; break;
13568 assert(Subtarget->is64Bit() && "Node not type legal!");
13569 Reg = X86::RAX; size = 8;
13572 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13573 Op.getOperand(2), SDValue());
13574 SDValue Ops[] = { cpIn.getValue(0),
13577 DAG.getTargetConstant(size, MVT::i8),
13578 cpIn.getValue(1) };
13579 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13580 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13581 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13582 Ops, array_lengthof(Ops), T, MMO);
13584 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13588 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13589 SelectionDAG &DAG) {
13590 assert(Subtarget->is64Bit() && "Result not type legalized?");
13591 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13592 SDValue TheChain = Op.getOperand(0);
13594 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13595 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13596 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13598 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13599 DAG.getConstant(32, MVT::i8));
13601 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13604 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13607 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13608 SelectionDAG &DAG) {
13609 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13610 MVT DstVT = Op.getSimpleValueType();
13611 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13612 Subtarget->hasMMX() && "Unexpected custom BITCAST");
13613 assert((DstVT == MVT::i64 ||
13614 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13615 "Unexpected custom BITCAST");
13616 // i64 <=> MMX conversions are Legal.
13617 if (SrcVT==MVT::i64 && DstVT.isVector())
13619 if (DstVT==MVT::i64 && SrcVT.isVector())
13621 // MMX <=> MMX conversions are Legal.
13622 if (SrcVT.isVector() && DstVT.isVector())
13624 // All other conversions need to be expanded.
13628 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13629 SDNode *Node = Op.getNode();
13631 EVT T = Node->getValueType(0);
13632 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13633 DAG.getConstant(0, T), Node->getOperand(2));
13634 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13635 cast<AtomicSDNode>(Node)->getMemoryVT(),
13636 Node->getOperand(0),
13637 Node->getOperand(1), negOp,
13638 cast<AtomicSDNode>(Node)->getSrcValue(),
13639 cast<AtomicSDNode>(Node)->getAlignment(),
13640 cast<AtomicSDNode>(Node)->getOrdering(),
13641 cast<AtomicSDNode>(Node)->getSynchScope());
13644 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13645 SDNode *Node = Op.getNode();
13647 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13649 // Convert seq_cst store -> xchg
13650 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13651 // FIXME: On 32-bit, store -> fist or movq would be more efficient
13652 // (The only way to get a 16-byte store is cmpxchg16b)
13653 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13654 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13655 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13656 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13657 cast<AtomicSDNode>(Node)->getMemoryVT(),
13658 Node->getOperand(0),
13659 Node->getOperand(1), Node->getOperand(2),
13660 cast<AtomicSDNode>(Node)->getMemOperand(),
13661 cast<AtomicSDNode>(Node)->getOrdering(),
13662 cast<AtomicSDNode>(Node)->getSynchScope());
13663 return Swap.getValue(1);
13665 // Other atomic stores have a simple pattern.
13669 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13670 EVT VT = Op.getNode()->getSimpleValueType(0);
13672 // Let legalize expand this if it isn't a legal type yet.
13673 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13676 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13679 bool ExtraOp = false;
13680 switch (Op.getOpcode()) {
13681 default: llvm_unreachable("Invalid code");
13682 case ISD::ADDC: Opc = X86ISD::ADD; break;
13683 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13684 case ISD::SUBC: Opc = X86ISD::SUB; break;
13685 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13689 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13691 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13692 Op.getOperand(1), Op.getOperand(2));
13695 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13696 SelectionDAG &DAG) {
13697 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13699 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13700 // which returns the values as { float, float } (in XMM0) or
13701 // { double, double } (which is returned in XMM0, XMM1).
13703 SDValue Arg = Op.getOperand(0);
13704 EVT ArgVT = Arg.getValueType();
13705 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13707 TargetLowering::ArgListTy Args;
13708 TargetLowering::ArgListEntry Entry;
13712 Entry.isSExt = false;
13713 Entry.isZExt = false;
13714 Args.push_back(Entry);
13716 bool isF64 = ArgVT == MVT::f64;
13717 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13718 // the small struct {f32, f32} is returned in (eax, edx). For f64,
13719 // the results are returned via SRet in memory.
13720 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
13721 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13722 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13724 Type *RetTy = isF64
13725 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13726 : (Type*)VectorType::get(ArgTy, 4);
13728 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13729 false, false, false, false, 0,
13730 CallingConv::C, /*isTaillCall=*/false,
13731 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13732 Callee, Args, DAG, dl);
13733 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13736 // Returned in xmm0 and xmm1.
13737 return CallResult.first;
13739 // Returned in bits 0:31 and 32:64 xmm0.
13740 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13741 CallResult.first, DAG.getIntPtrConstant(0));
13742 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13743 CallResult.first, DAG.getIntPtrConstant(1));
13744 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13745 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13748 /// LowerOperation - Provide custom lowering hooks for some operations.
13750 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13751 switch (Op.getOpcode()) {
13752 default: llvm_unreachable("Should not custom lower this!");
13753 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
13754 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13755 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
13756 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
13757 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
13758 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
13759 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
13760 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
13761 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13762 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
13763 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13764 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13765 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
13766 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
13767 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
13768 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
13769 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
13770 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
13771 case ISD::SHL_PARTS:
13772 case ISD::SRA_PARTS:
13773 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
13774 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
13775 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
13776 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
13777 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
13778 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13779 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
13780 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
13781 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
13782 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
13783 case ISD::FABS: return LowerFABS(Op, DAG);
13784 case ISD::FNEG: return LowerFNEG(Op, DAG);
13785 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
13786 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
13787 case ISD::SETCC: return LowerSETCC(Op, DAG);
13788 case ISD::SELECT: return LowerSELECT(Op, DAG);
13789 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
13790 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
13791 case ISD::VASTART: return LowerVASTART(Op, DAG);
13792 case ISD::VAARG: return LowerVAARG(Op, DAG);
13793 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
13794 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13795 case ISD::INTRINSIC_VOID:
13796 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13797 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
13798 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
13799 case ISD::FRAME_TO_ARGS_OFFSET:
13800 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13801 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13802 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
13803 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
13804 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
13805 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
13806 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
13807 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
13808 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
13809 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13810 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
13811 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
13814 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
13820 case ISD::UMULO: return LowerXALUO(Op, DAG);
13821 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13822 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
13826 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13827 case ISD::ADD: return LowerADD(Op, DAG);
13828 case ISD::SUB: return LowerSUB(Op, DAG);
13829 case ISD::SDIV: return LowerSDIV(Op, DAG);
13830 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
13834 static void ReplaceATOMIC_LOAD(SDNode *Node,
13835 SmallVectorImpl<SDValue> &Results,
13836 SelectionDAG &DAG) {
13838 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13840 // Convert wide load -> cmpxchg8b/cmpxchg16b
13841 // FIXME: On 32-bit, load -> fild or movq would be more efficient
13842 // (The only way to get a 16-byte load is cmpxchg16b)
13843 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13844 SDValue Zero = DAG.getConstant(0, VT);
13845 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13846 Node->getOperand(0),
13847 Node->getOperand(1), Zero, Zero,
13848 cast<AtomicSDNode>(Node)->getMemOperand(),
13849 cast<AtomicSDNode>(Node)->getOrdering(),
13850 cast<AtomicSDNode>(Node)->getOrdering(),
13851 cast<AtomicSDNode>(Node)->getSynchScope());
13852 Results.push_back(Swap.getValue(0));
13853 Results.push_back(Swap.getValue(1));
13857 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13858 SelectionDAG &DAG, unsigned NewOp) {
13860 assert (Node->getValueType(0) == MVT::i64 &&
13861 "Only know how to expand i64 atomics");
13863 SDValue Chain = Node->getOperand(0);
13864 SDValue In1 = Node->getOperand(1);
13865 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13866 Node->getOperand(2), DAG.getIntPtrConstant(0));
13867 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13868 Node->getOperand(2), DAG.getIntPtrConstant(1));
13869 SDValue Ops[] = { Chain, In1, In2L, In2H };
13870 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13872 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13873 cast<MemSDNode>(Node)->getMemOperand());
13874 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13875 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13876 Results.push_back(Result.getValue(2));
13879 /// ReplaceNodeResults - Replace a node with an illegal result type
13880 /// with a new node built out of custom code.
13881 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13882 SmallVectorImpl<SDValue>&Results,
13883 SelectionDAG &DAG) const {
13885 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13886 switch (N->getOpcode()) {
13888 llvm_unreachable("Do not know how to custom type legalize this operation!");
13889 case ISD::SIGN_EXTEND_INREG:
13894 // We don't want to expand or promote these.
13896 case ISD::FP_TO_SINT:
13897 case ISD::FP_TO_UINT: {
13898 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13900 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13903 std::pair<SDValue,SDValue> Vals =
13904 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13905 SDValue FIST = Vals.first, StackSlot = Vals.second;
13906 if (FIST.getNode() != 0) {
13907 EVT VT = N->getValueType(0);
13908 // Return a load from the stack slot.
13909 if (StackSlot.getNode() != 0)
13910 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13911 MachinePointerInfo(),
13912 false, false, false, 0));
13914 Results.push_back(FIST);
13918 case ISD::UINT_TO_FP: {
13919 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13920 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13921 N->getValueType(0) != MVT::v2f32)
13923 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13925 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13927 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13928 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13929 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13930 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13931 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13932 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13935 case ISD::FP_ROUND: {
13936 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13938 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13939 Results.push_back(V);
13942 case ISD::READCYCLECOUNTER: {
13943 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13944 SDValue TheChain = N->getOperand(0);
13945 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13946 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13948 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13950 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13951 SDValue Ops[] = { eax, edx };
13952 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13953 array_lengthof(Ops)));
13954 Results.push_back(edx.getValue(1));
13957 case ISD::ATOMIC_CMP_SWAP: {
13958 EVT T = N->getValueType(0);
13959 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13960 bool Regs64bit = T == MVT::i128;
13961 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13962 SDValue cpInL, cpInH;
13963 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13964 DAG.getConstant(0, HalfT));
13965 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13966 DAG.getConstant(1, HalfT));
13967 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13968 Regs64bit ? X86::RAX : X86::EAX,
13970 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13971 Regs64bit ? X86::RDX : X86::EDX,
13972 cpInH, cpInL.getValue(1));
13973 SDValue swapInL, swapInH;
13974 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13975 DAG.getConstant(0, HalfT));
13976 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13977 DAG.getConstant(1, HalfT));
13978 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13979 Regs64bit ? X86::RBX : X86::EBX,
13980 swapInL, cpInH.getValue(1));
13981 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13982 Regs64bit ? X86::RCX : X86::ECX,
13983 swapInH, swapInL.getValue(1));
13984 SDValue Ops[] = { swapInH.getValue(0),
13986 swapInH.getValue(1) };
13987 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13988 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13989 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13990 X86ISD::LCMPXCHG8_DAG;
13991 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13992 Ops, array_lengthof(Ops), T, MMO);
13993 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13994 Regs64bit ? X86::RAX : X86::EAX,
13995 HalfT, Result.getValue(1));
13996 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13997 Regs64bit ? X86::RDX : X86::EDX,
13998 HalfT, cpOutL.getValue(2));
13999 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14000 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14001 Results.push_back(cpOutH.getValue(1));
14004 case ISD::ATOMIC_LOAD_ADD:
14005 case ISD::ATOMIC_LOAD_AND:
14006 case ISD::ATOMIC_LOAD_NAND:
14007 case ISD::ATOMIC_LOAD_OR:
14008 case ISD::ATOMIC_LOAD_SUB:
14009 case ISD::ATOMIC_LOAD_XOR:
14010 case ISD::ATOMIC_LOAD_MAX:
14011 case ISD::ATOMIC_LOAD_MIN:
14012 case ISD::ATOMIC_LOAD_UMAX:
14013 case ISD::ATOMIC_LOAD_UMIN:
14014 case ISD::ATOMIC_SWAP: {
14016 switch (N->getOpcode()) {
14017 default: llvm_unreachable("Unexpected opcode");
14018 case ISD::ATOMIC_LOAD_ADD:
14019 Opc = X86ISD::ATOMADD64_DAG;
14021 case ISD::ATOMIC_LOAD_AND:
14022 Opc = X86ISD::ATOMAND64_DAG;
14024 case ISD::ATOMIC_LOAD_NAND:
14025 Opc = X86ISD::ATOMNAND64_DAG;
14027 case ISD::ATOMIC_LOAD_OR:
14028 Opc = X86ISD::ATOMOR64_DAG;
14030 case ISD::ATOMIC_LOAD_SUB:
14031 Opc = X86ISD::ATOMSUB64_DAG;
14033 case ISD::ATOMIC_LOAD_XOR:
14034 Opc = X86ISD::ATOMXOR64_DAG;
14036 case ISD::ATOMIC_LOAD_MAX:
14037 Opc = X86ISD::ATOMMAX64_DAG;
14039 case ISD::ATOMIC_LOAD_MIN:
14040 Opc = X86ISD::ATOMMIN64_DAG;
14042 case ISD::ATOMIC_LOAD_UMAX:
14043 Opc = X86ISD::ATOMUMAX64_DAG;
14045 case ISD::ATOMIC_LOAD_UMIN:
14046 Opc = X86ISD::ATOMUMIN64_DAG;
14048 case ISD::ATOMIC_SWAP:
14049 Opc = X86ISD::ATOMSWAP64_DAG;
14052 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14055 case ISD::ATOMIC_LOAD:
14056 ReplaceATOMIC_LOAD(N, Results, DAG);
14060 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14062 default: return NULL;
14063 case X86ISD::BSF: return "X86ISD::BSF";
14064 case X86ISD::BSR: return "X86ISD::BSR";
14065 case X86ISD::SHLD: return "X86ISD::SHLD";
14066 case X86ISD::SHRD: return "X86ISD::SHRD";
14067 case X86ISD::FAND: return "X86ISD::FAND";
14068 case X86ISD::FANDN: return "X86ISD::FANDN";
14069 case X86ISD::FOR: return "X86ISD::FOR";
14070 case X86ISD::FXOR: return "X86ISD::FXOR";
14071 case X86ISD::FSRL: return "X86ISD::FSRL";
14072 case X86ISD::FILD: return "X86ISD::FILD";
14073 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14074 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14075 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14076 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14077 case X86ISD::FLD: return "X86ISD::FLD";
14078 case X86ISD::FST: return "X86ISD::FST";
14079 case X86ISD::CALL: return "X86ISD::CALL";
14080 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14081 case X86ISD::BT: return "X86ISD::BT";
14082 case X86ISD::CMP: return "X86ISD::CMP";
14083 case X86ISD::COMI: return "X86ISD::COMI";
14084 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14085 case X86ISD::CMPM: return "X86ISD::CMPM";
14086 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14087 case X86ISD::SETCC: return "X86ISD::SETCC";
14088 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14089 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14090 case X86ISD::CMOV: return "X86ISD::CMOV";
14091 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14092 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14093 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14094 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14095 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14096 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14097 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14098 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14099 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14100 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14101 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14102 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14103 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14104 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14105 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14106 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14107 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14108 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14109 case X86ISD::HADD: return "X86ISD::HADD";
14110 case X86ISD::HSUB: return "X86ISD::HSUB";
14111 case X86ISD::FHADD: return "X86ISD::FHADD";
14112 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14113 case X86ISD::UMAX: return "X86ISD::UMAX";
14114 case X86ISD::UMIN: return "X86ISD::UMIN";
14115 case X86ISD::SMAX: return "X86ISD::SMAX";
14116 case X86ISD::SMIN: return "X86ISD::SMIN";
14117 case X86ISD::FMAX: return "X86ISD::FMAX";
14118 case X86ISD::FMIN: return "X86ISD::FMIN";
14119 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14120 case X86ISD::FMINC: return "X86ISD::FMINC";
14121 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14122 case X86ISD::FRCP: return "X86ISD::FRCP";
14123 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14124 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14125 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14126 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14127 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14128 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14129 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14130 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14131 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14132 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14133 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14134 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14135 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14136 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14137 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14138 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14139 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14140 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14141 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14142 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14143 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14144 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14145 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14146 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14147 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14148 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14149 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14150 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14151 case X86ISD::VSHL: return "X86ISD::VSHL";
14152 case X86ISD::VSRL: return "X86ISD::VSRL";
14153 case X86ISD::VSRA: return "X86ISD::VSRA";
14154 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14155 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14156 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14157 case X86ISD::CMPP: return "X86ISD::CMPP";
14158 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14159 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14160 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14161 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14162 case X86ISD::ADD: return "X86ISD::ADD";
14163 case X86ISD::SUB: return "X86ISD::SUB";
14164 case X86ISD::ADC: return "X86ISD::ADC";
14165 case X86ISD::SBB: return "X86ISD::SBB";
14166 case X86ISD::SMUL: return "X86ISD::SMUL";
14167 case X86ISD::UMUL: return "X86ISD::UMUL";
14168 case X86ISD::INC: return "X86ISD::INC";
14169 case X86ISD::DEC: return "X86ISD::DEC";
14170 case X86ISD::OR: return "X86ISD::OR";
14171 case X86ISD::XOR: return "X86ISD::XOR";
14172 case X86ISD::AND: return "X86ISD::AND";
14173 case X86ISD::BZHI: return "X86ISD::BZHI";
14174 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14175 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14176 case X86ISD::PTEST: return "X86ISD::PTEST";
14177 case X86ISD::TESTP: return "X86ISD::TESTP";
14178 case X86ISD::TESTM: return "X86ISD::TESTM";
14179 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14180 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14181 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14182 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14183 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14184 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14185 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14186 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14187 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14188 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14189 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14190 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14191 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14192 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14193 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14194 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14195 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14196 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14197 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14198 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14199 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14200 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14201 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14202 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14203 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14204 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14205 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14206 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14207 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14208 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14209 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14210 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14211 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14212 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14213 case X86ISD::SAHF: return "X86ISD::SAHF";
14214 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14215 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14216 case X86ISD::FMADD: return "X86ISD::FMADD";
14217 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14218 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14219 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14220 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14221 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14222 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14223 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14224 case X86ISD::XTEST: return "X86ISD::XTEST";
14228 // isLegalAddressingMode - Return true if the addressing mode represented
14229 // by AM is legal for this target, for a load/store of the specified type.
14230 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14232 // X86 supports extremely general addressing modes.
14233 CodeModel::Model M = getTargetMachine().getCodeModel();
14234 Reloc::Model R = getTargetMachine().getRelocationModel();
14236 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14237 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14242 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14244 // If a reference to this global requires an extra load, we can't fold it.
14245 if (isGlobalStubReference(GVFlags))
14248 // If BaseGV requires a register for the PIC base, we cannot also have a
14249 // BaseReg specified.
14250 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14253 // If lower 4G is not available, then we must use rip-relative addressing.
14254 if ((M != CodeModel::Small || R != Reloc::Static) &&
14255 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14259 switch (AM.Scale) {
14265 // These scales always work.
14270 // These scales are formed with basereg+scalereg. Only accept if there is
14275 default: // Other stuff never works.
14282 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14283 unsigned Bits = Ty->getScalarSizeInBits();
14285 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14286 // particularly cheaper than those without.
14290 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14291 // variable shifts just as cheap as scalar ones.
14292 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14295 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14296 // fully general vector.
14300 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14301 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14303 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14304 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14305 return NumBits1 > NumBits2;
14308 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14309 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14312 if (!isTypeLegal(EVT::getEVT(Ty1)))
14315 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14317 // Assuming the caller doesn't have a zeroext or signext return parameter,
14318 // truncation all the way down to i1 is valid.
14322 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14323 return isInt<32>(Imm);
14326 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14327 // Can also use sub to handle negated immediates.
14328 return isInt<32>(Imm);
14331 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14332 if (!VT1.isInteger() || !VT2.isInteger())
14334 unsigned NumBits1 = VT1.getSizeInBits();
14335 unsigned NumBits2 = VT2.getSizeInBits();
14336 return NumBits1 > NumBits2;
14339 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14340 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14341 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14344 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14345 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14346 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14349 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14350 EVT VT1 = Val.getValueType();
14351 if (isZExtFree(VT1, VT2))
14354 if (Val.getOpcode() != ISD::LOAD)
14357 if (!VT1.isSimple() || !VT1.isInteger() ||
14358 !VT2.isSimple() || !VT2.isInteger())
14361 switch (VT1.getSimpleVT().SimpleTy) {
14366 // X86 has 8, 16, and 32-bit zero-extending loads.
14374 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14375 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14378 VT = VT.getScalarType();
14380 if (!VT.isSimple())
14383 switch (VT.getSimpleVT().SimpleTy) {
14394 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14395 // i16 instructions are longer (0x66 prefix) and potentially slower.
14396 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14399 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14400 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14401 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14402 /// are assumed to be legal.
14404 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14406 if (!VT.isSimple())
14409 MVT SVT = VT.getSimpleVT();
14411 // Very little shuffling can be done for 64-bit vectors right now.
14412 if (VT.getSizeInBits() == 64)
14415 // FIXME: pshufb, blends, shifts.
14416 return (SVT.getVectorNumElements() == 2 ||
14417 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14418 isMOVLMask(M, SVT) ||
14419 isSHUFPMask(M, SVT) ||
14420 isPSHUFDMask(M, SVT) ||
14421 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14422 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14423 isPALIGNRMask(M, SVT, Subtarget) ||
14424 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14425 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14426 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14427 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14431 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14433 if (!VT.isSimple())
14436 MVT SVT = VT.getSimpleVT();
14437 unsigned NumElts = SVT.getVectorNumElements();
14438 // FIXME: This collection of masks seems suspect.
14441 if (NumElts == 4 && SVT.is128BitVector()) {
14442 return (isMOVLMask(Mask, SVT) ||
14443 isCommutedMOVLMask(Mask, SVT, true) ||
14444 isSHUFPMask(Mask, SVT) ||
14445 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14450 //===----------------------------------------------------------------------===//
14451 // X86 Scheduler Hooks
14452 //===----------------------------------------------------------------------===//
14454 /// Utility function to emit xbegin specifying the start of an RTM region.
14455 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14456 const TargetInstrInfo *TII) {
14457 DebugLoc DL = MI->getDebugLoc();
14459 const BasicBlock *BB = MBB->getBasicBlock();
14460 MachineFunction::iterator I = MBB;
14463 // For the v = xbegin(), we generate
14474 MachineBasicBlock *thisMBB = MBB;
14475 MachineFunction *MF = MBB->getParent();
14476 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14477 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14478 MF->insert(I, mainMBB);
14479 MF->insert(I, sinkMBB);
14481 // Transfer the remainder of BB and its successor edges to sinkMBB.
14482 sinkMBB->splice(sinkMBB->begin(), MBB,
14483 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14484 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14488 // # fallthrough to mainMBB
14489 // # abortion to sinkMBB
14490 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14491 thisMBB->addSuccessor(mainMBB);
14492 thisMBB->addSuccessor(sinkMBB);
14496 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14497 mainMBB->addSuccessor(sinkMBB);
14500 // EAX is live into the sinkMBB
14501 sinkMBB->addLiveIn(X86::EAX);
14502 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14503 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14506 MI->eraseFromParent();
14510 // Get CMPXCHG opcode for the specified data type.
14511 static unsigned getCmpXChgOpcode(EVT VT) {
14512 switch (VT.getSimpleVT().SimpleTy) {
14513 case MVT::i8: return X86::LCMPXCHG8;
14514 case MVT::i16: return X86::LCMPXCHG16;
14515 case MVT::i32: return X86::LCMPXCHG32;
14516 case MVT::i64: return X86::LCMPXCHG64;
14520 llvm_unreachable("Invalid operand size!");
14523 // Get LOAD opcode for the specified data type.
14524 static unsigned getLoadOpcode(EVT VT) {
14525 switch (VT.getSimpleVT().SimpleTy) {
14526 case MVT::i8: return X86::MOV8rm;
14527 case MVT::i16: return X86::MOV16rm;
14528 case MVT::i32: return X86::MOV32rm;
14529 case MVT::i64: return X86::MOV64rm;
14533 llvm_unreachable("Invalid operand size!");
14536 // Get opcode of the non-atomic one from the specified atomic instruction.
14537 static unsigned getNonAtomicOpcode(unsigned Opc) {
14539 case X86::ATOMAND8: return X86::AND8rr;
14540 case X86::ATOMAND16: return X86::AND16rr;
14541 case X86::ATOMAND32: return X86::AND32rr;
14542 case X86::ATOMAND64: return X86::AND64rr;
14543 case X86::ATOMOR8: return X86::OR8rr;
14544 case X86::ATOMOR16: return X86::OR16rr;
14545 case X86::ATOMOR32: return X86::OR32rr;
14546 case X86::ATOMOR64: return X86::OR64rr;
14547 case X86::ATOMXOR8: return X86::XOR8rr;
14548 case X86::ATOMXOR16: return X86::XOR16rr;
14549 case X86::ATOMXOR32: return X86::XOR32rr;
14550 case X86::ATOMXOR64: return X86::XOR64rr;
14552 llvm_unreachable("Unhandled atomic-load-op opcode!");
14555 // Get opcode of the non-atomic one from the specified atomic instruction with
14557 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14558 unsigned &ExtraOpc) {
14560 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14561 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14562 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14563 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14564 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14565 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14566 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14567 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14568 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14569 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14570 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14571 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14572 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14573 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14574 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14575 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14576 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14577 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14578 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14579 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14581 llvm_unreachable("Unhandled atomic-load-op opcode!");
14584 // Get opcode of the non-atomic one from the specified atomic instruction for
14585 // 64-bit data type on 32-bit target.
14586 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14588 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14589 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14590 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14591 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14592 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14593 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14594 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14595 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14596 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14597 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14599 llvm_unreachable("Unhandled atomic-load-op opcode!");
14602 // Get opcode of the non-atomic one from the specified atomic instruction for
14603 // 64-bit data type on 32-bit target with extra opcode.
14604 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14606 unsigned &ExtraOpc) {
14608 case X86::ATOMNAND6432:
14609 ExtraOpc = X86::NOT32r;
14610 HiOpc = X86::AND32rr;
14611 return X86::AND32rr;
14613 llvm_unreachable("Unhandled atomic-load-op opcode!");
14616 // Get pseudo CMOV opcode from the specified data type.
14617 static unsigned getPseudoCMOVOpc(EVT VT) {
14618 switch (VT.getSimpleVT().SimpleTy) {
14619 case MVT::i8: return X86::CMOV_GR8;
14620 case MVT::i16: return X86::CMOV_GR16;
14621 case MVT::i32: return X86::CMOV_GR32;
14625 llvm_unreachable("Unknown CMOV opcode!");
14628 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14629 // They will be translated into a spin-loop or compare-exchange loop from
14632 // dst = atomic-fetch-op MI.addr, MI.val
14638 // t1 = LOAD MI.addr
14640 // t4 = phi(t1, t3 / loop)
14641 // t2 = OP MI.val, t4
14643 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14649 MachineBasicBlock *
14650 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14651 MachineBasicBlock *MBB) const {
14652 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14653 DebugLoc DL = MI->getDebugLoc();
14655 MachineFunction *MF = MBB->getParent();
14656 MachineRegisterInfo &MRI = MF->getRegInfo();
14658 const BasicBlock *BB = MBB->getBasicBlock();
14659 MachineFunction::iterator I = MBB;
14662 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14663 "Unexpected number of operands");
14665 assert(MI->hasOneMemOperand() &&
14666 "Expected atomic-load-op to have one memoperand");
14668 // Memory Reference
14669 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14670 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14672 unsigned DstReg, SrcReg;
14673 unsigned MemOpndSlot;
14675 unsigned CurOp = 0;
14677 DstReg = MI->getOperand(CurOp++).getReg();
14678 MemOpndSlot = CurOp;
14679 CurOp += X86::AddrNumOperands;
14680 SrcReg = MI->getOperand(CurOp++).getReg();
14682 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14683 MVT::SimpleValueType VT = *RC->vt_begin();
14684 unsigned t1 = MRI.createVirtualRegister(RC);
14685 unsigned t2 = MRI.createVirtualRegister(RC);
14686 unsigned t3 = MRI.createVirtualRegister(RC);
14687 unsigned t4 = MRI.createVirtualRegister(RC);
14688 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14690 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14691 unsigned LOADOpc = getLoadOpcode(VT);
14693 // For the atomic load-arith operator, we generate
14696 // t1 = LOAD [MI.addr]
14698 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
14699 // t1 = OP MI.val, EAX
14701 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14707 MachineBasicBlock *thisMBB = MBB;
14708 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14709 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14710 MF->insert(I, mainMBB);
14711 MF->insert(I, sinkMBB);
14713 MachineInstrBuilder MIB;
14715 // Transfer the remainder of BB and its successor edges to sinkMBB.
14716 sinkMBB->splice(sinkMBB->begin(), MBB,
14717 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14718 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14721 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14722 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14723 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14725 NewMO.setIsKill(false);
14726 MIB.addOperand(NewMO);
14728 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14729 unsigned flags = (*MMOI)->getFlags();
14730 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14731 MachineMemOperand *MMO =
14732 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14733 (*MMOI)->getSize(),
14734 (*MMOI)->getBaseAlignment(),
14735 (*MMOI)->getTBAAInfo(),
14736 (*MMOI)->getRanges());
14737 MIB.addMemOperand(MMO);
14740 thisMBB->addSuccessor(mainMBB);
14743 MachineBasicBlock *origMainMBB = mainMBB;
14746 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14747 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14749 unsigned Opc = MI->getOpcode();
14752 llvm_unreachable("Unhandled atomic-load-op opcode!");
14753 case X86::ATOMAND8:
14754 case X86::ATOMAND16:
14755 case X86::ATOMAND32:
14756 case X86::ATOMAND64:
14758 case X86::ATOMOR16:
14759 case X86::ATOMOR32:
14760 case X86::ATOMOR64:
14761 case X86::ATOMXOR8:
14762 case X86::ATOMXOR16:
14763 case X86::ATOMXOR32:
14764 case X86::ATOMXOR64: {
14765 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14766 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14770 case X86::ATOMNAND8:
14771 case X86::ATOMNAND16:
14772 case X86::ATOMNAND32:
14773 case X86::ATOMNAND64: {
14774 unsigned Tmp = MRI.createVirtualRegister(RC);
14776 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14777 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14779 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14782 case X86::ATOMMAX8:
14783 case X86::ATOMMAX16:
14784 case X86::ATOMMAX32:
14785 case X86::ATOMMAX64:
14786 case X86::ATOMMIN8:
14787 case X86::ATOMMIN16:
14788 case X86::ATOMMIN32:
14789 case X86::ATOMMIN64:
14790 case X86::ATOMUMAX8:
14791 case X86::ATOMUMAX16:
14792 case X86::ATOMUMAX32:
14793 case X86::ATOMUMAX64:
14794 case X86::ATOMUMIN8:
14795 case X86::ATOMUMIN16:
14796 case X86::ATOMUMIN32:
14797 case X86::ATOMUMIN64: {
14799 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14801 BuildMI(mainMBB, DL, TII->get(CMPOpc))
14805 if (Subtarget->hasCMov()) {
14806 if (VT != MVT::i8) {
14808 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14812 // Promote i8 to i32 to use CMOV32
14813 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14814 const TargetRegisterClass *RC32 =
14815 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14816 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14817 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14818 unsigned Tmp = MRI.createVirtualRegister(RC32);
14820 unsigned Undef = MRI.createVirtualRegister(RC32);
14821 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14823 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14826 .addImm(X86::sub_8bit);
14827 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14830 .addImm(X86::sub_8bit);
14832 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14836 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14837 .addReg(Tmp, 0, X86::sub_8bit);
14840 // Use pseudo select and lower them.
14841 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14842 "Invalid atomic-load-op transformation!");
14843 unsigned SelOpc = getPseudoCMOVOpc(VT);
14844 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14845 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14846 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14847 .addReg(SrcReg).addReg(t4)
14849 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14850 // Replace the original PHI node as mainMBB is changed after CMOV
14852 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14853 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14854 Phi->eraseFromParent();
14860 // Copy PhyReg back from virtual register.
14861 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14864 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14865 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14866 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14868 NewMO.setIsKill(false);
14869 MIB.addOperand(NewMO);
14872 MIB.setMemRefs(MMOBegin, MMOEnd);
14874 // Copy PhyReg back to virtual register.
14875 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14878 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14880 mainMBB->addSuccessor(origMainMBB);
14881 mainMBB->addSuccessor(sinkMBB);
14884 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14885 TII->get(TargetOpcode::COPY), DstReg)
14888 MI->eraseFromParent();
14892 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14893 // instructions. They will be translated into a spin-loop or compare-exchange
14897 // dst = atomic-fetch-op MI.addr, MI.val
14903 // t1L = LOAD [MI.addr + 0]
14904 // t1H = LOAD [MI.addr + 4]
14906 // t4L = phi(t1L, t3L / loop)
14907 // t4H = phi(t1H, t3H / loop)
14908 // t2L = OP MI.val.lo, t4L
14909 // t2H = OP MI.val.hi, t4H
14914 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14922 MachineBasicBlock *
14923 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14924 MachineBasicBlock *MBB) const {
14925 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14926 DebugLoc DL = MI->getDebugLoc();
14928 MachineFunction *MF = MBB->getParent();
14929 MachineRegisterInfo &MRI = MF->getRegInfo();
14931 const BasicBlock *BB = MBB->getBasicBlock();
14932 MachineFunction::iterator I = MBB;
14935 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14936 "Unexpected number of operands");
14938 assert(MI->hasOneMemOperand() &&
14939 "Expected atomic-load-op32 to have one memoperand");
14941 // Memory Reference
14942 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14943 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14945 unsigned DstLoReg, DstHiReg;
14946 unsigned SrcLoReg, SrcHiReg;
14947 unsigned MemOpndSlot;
14949 unsigned CurOp = 0;
14951 DstLoReg = MI->getOperand(CurOp++).getReg();
14952 DstHiReg = MI->getOperand(CurOp++).getReg();
14953 MemOpndSlot = CurOp;
14954 CurOp += X86::AddrNumOperands;
14955 SrcLoReg = MI->getOperand(CurOp++).getReg();
14956 SrcHiReg = MI->getOperand(CurOp++).getReg();
14958 const TargetRegisterClass *RC = &X86::GR32RegClass;
14959 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14961 unsigned t1L = MRI.createVirtualRegister(RC);
14962 unsigned t1H = MRI.createVirtualRegister(RC);
14963 unsigned t2L = MRI.createVirtualRegister(RC);
14964 unsigned t2H = MRI.createVirtualRegister(RC);
14965 unsigned t3L = MRI.createVirtualRegister(RC);
14966 unsigned t3H = MRI.createVirtualRegister(RC);
14967 unsigned t4L = MRI.createVirtualRegister(RC);
14968 unsigned t4H = MRI.createVirtualRegister(RC);
14970 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14971 unsigned LOADOpc = X86::MOV32rm;
14973 // For the atomic load-arith operator, we generate
14976 // t1L = LOAD [MI.addr + 0]
14977 // t1H = LOAD [MI.addr + 4]
14979 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
14980 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
14981 // t2L = OP MI.val.lo, t4L
14982 // t2H = OP MI.val.hi, t4H
14985 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14993 MachineBasicBlock *thisMBB = MBB;
14994 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14995 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14996 MF->insert(I, mainMBB);
14997 MF->insert(I, sinkMBB);
14999 MachineInstrBuilder MIB;
15001 // Transfer the remainder of BB and its successor edges to sinkMBB.
15002 sinkMBB->splice(sinkMBB->begin(), MBB,
15003 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15004 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15008 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15009 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15010 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15012 NewMO.setIsKill(false);
15013 MIB.addOperand(NewMO);
15015 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15016 unsigned flags = (*MMOI)->getFlags();
15017 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15018 MachineMemOperand *MMO =
15019 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15020 (*MMOI)->getSize(),
15021 (*MMOI)->getBaseAlignment(),
15022 (*MMOI)->getTBAAInfo(),
15023 (*MMOI)->getRanges());
15024 MIB.addMemOperand(MMO);
15026 MachineInstr *LowMI = MIB;
15029 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15030 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15031 if (i == X86::AddrDisp) {
15032 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15034 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15036 NewMO.setIsKill(false);
15037 MIB.addOperand(NewMO);
15040 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15042 thisMBB->addSuccessor(mainMBB);
15045 MachineBasicBlock *origMainMBB = mainMBB;
15048 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15049 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15050 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15051 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15053 unsigned Opc = MI->getOpcode();
15056 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15057 case X86::ATOMAND6432:
15058 case X86::ATOMOR6432:
15059 case X86::ATOMXOR6432:
15060 case X86::ATOMADD6432:
15061 case X86::ATOMSUB6432: {
15063 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15064 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15066 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15070 case X86::ATOMNAND6432: {
15071 unsigned HiOpc, NOTOpc;
15072 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15073 unsigned TmpL = MRI.createVirtualRegister(RC);
15074 unsigned TmpH = MRI.createVirtualRegister(RC);
15075 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15077 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15079 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15080 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15083 case X86::ATOMMAX6432:
15084 case X86::ATOMMIN6432:
15085 case X86::ATOMUMAX6432:
15086 case X86::ATOMUMIN6432: {
15088 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15089 unsigned cL = MRI.createVirtualRegister(RC8);
15090 unsigned cH = MRI.createVirtualRegister(RC8);
15091 unsigned cL32 = MRI.createVirtualRegister(RC);
15092 unsigned cH32 = MRI.createVirtualRegister(RC);
15093 unsigned cc = MRI.createVirtualRegister(RC);
15094 // cl := cmp src_lo, lo
15095 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15096 .addReg(SrcLoReg).addReg(t4L);
15097 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15098 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15099 // ch := cmp src_hi, hi
15100 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15101 .addReg(SrcHiReg).addReg(t4H);
15102 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15103 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15104 // cc := if (src_hi == hi) ? cl : ch;
15105 if (Subtarget->hasCMov()) {
15106 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15107 .addReg(cH32).addReg(cL32);
15109 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15110 .addReg(cH32).addReg(cL32)
15111 .addImm(X86::COND_E);
15112 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15114 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15115 if (Subtarget->hasCMov()) {
15116 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15117 .addReg(SrcLoReg).addReg(t4L);
15118 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15119 .addReg(SrcHiReg).addReg(t4H);
15121 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15122 .addReg(SrcLoReg).addReg(t4L)
15123 .addImm(X86::COND_NE);
15124 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15125 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15126 // 2nd CMOV lowering.
15127 mainMBB->addLiveIn(X86::EFLAGS);
15128 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15129 .addReg(SrcHiReg).addReg(t4H)
15130 .addImm(X86::COND_NE);
15131 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15132 // Replace the original PHI node as mainMBB is changed after CMOV
15134 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15135 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15136 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15137 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15138 PhiL->eraseFromParent();
15139 PhiH->eraseFromParent();
15143 case X86::ATOMSWAP6432: {
15145 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15146 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15147 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15152 // Copy EDX:EAX back from HiReg:LoReg
15153 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15154 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15155 // Copy ECX:EBX from t1H:t1L
15156 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15157 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15159 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15160 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15161 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15163 NewMO.setIsKill(false);
15164 MIB.addOperand(NewMO);
15166 MIB.setMemRefs(MMOBegin, MMOEnd);
15168 // Copy EDX:EAX back to t3H:t3L
15169 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15170 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15172 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15174 mainMBB->addSuccessor(origMainMBB);
15175 mainMBB->addSuccessor(sinkMBB);
15178 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15179 TII->get(TargetOpcode::COPY), DstLoReg)
15181 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15182 TII->get(TargetOpcode::COPY), DstHiReg)
15185 MI->eraseFromParent();
15189 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15190 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15191 // in the .td file.
15192 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15193 const TargetInstrInfo *TII) {
15195 switch (MI->getOpcode()) {
15196 default: llvm_unreachable("illegal opcode!");
15197 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15198 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15199 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15200 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15201 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15202 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15203 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15204 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15207 DebugLoc dl = MI->getDebugLoc();
15208 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15210 unsigned NumArgs = MI->getNumOperands();
15211 for (unsigned i = 1; i < NumArgs; ++i) {
15212 MachineOperand &Op = MI->getOperand(i);
15213 if (!(Op.isReg() && Op.isImplicit()))
15214 MIB.addOperand(Op);
15216 if (MI->hasOneMemOperand())
15217 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15219 BuildMI(*BB, MI, dl,
15220 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15221 .addReg(X86::XMM0);
15223 MI->eraseFromParent();
15227 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15228 // defs in an instruction pattern
15229 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15230 const TargetInstrInfo *TII) {
15232 switch (MI->getOpcode()) {
15233 default: llvm_unreachable("illegal opcode!");
15234 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15235 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15236 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15237 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15238 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15239 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15240 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15241 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15244 DebugLoc dl = MI->getDebugLoc();
15245 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15247 unsigned NumArgs = MI->getNumOperands(); // remove the results
15248 for (unsigned i = 1; i < NumArgs; ++i) {
15249 MachineOperand &Op = MI->getOperand(i);
15250 if (!(Op.isReg() && Op.isImplicit()))
15251 MIB.addOperand(Op);
15253 if (MI->hasOneMemOperand())
15254 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15256 BuildMI(*BB, MI, dl,
15257 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15260 MI->eraseFromParent();
15264 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15265 const TargetInstrInfo *TII,
15266 const X86Subtarget* Subtarget) {
15267 DebugLoc dl = MI->getDebugLoc();
15269 // Address into RAX/EAX, other two args into ECX, EDX.
15270 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15271 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15272 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15273 for (int i = 0; i < X86::AddrNumOperands; ++i)
15274 MIB.addOperand(MI->getOperand(i));
15276 unsigned ValOps = X86::AddrNumOperands;
15277 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15278 .addReg(MI->getOperand(ValOps).getReg());
15279 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15280 .addReg(MI->getOperand(ValOps+1).getReg());
15282 // The instruction doesn't actually take any operands though.
15283 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15285 MI->eraseFromParent(); // The pseudo is gone now.
15289 MachineBasicBlock *
15290 X86TargetLowering::EmitVAARG64WithCustomInserter(
15292 MachineBasicBlock *MBB) const {
15293 // Emit va_arg instruction on X86-64.
15295 // Operands to this pseudo-instruction:
15296 // 0 ) Output : destination address (reg)
15297 // 1-5) Input : va_list address (addr, i64mem)
15298 // 6 ) ArgSize : Size (in bytes) of vararg type
15299 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15300 // 8 ) Align : Alignment of type
15301 // 9 ) EFLAGS (implicit-def)
15303 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15304 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15306 unsigned DestReg = MI->getOperand(0).getReg();
15307 MachineOperand &Base = MI->getOperand(1);
15308 MachineOperand &Scale = MI->getOperand(2);
15309 MachineOperand &Index = MI->getOperand(3);
15310 MachineOperand &Disp = MI->getOperand(4);
15311 MachineOperand &Segment = MI->getOperand(5);
15312 unsigned ArgSize = MI->getOperand(6).getImm();
15313 unsigned ArgMode = MI->getOperand(7).getImm();
15314 unsigned Align = MI->getOperand(8).getImm();
15316 // Memory Reference
15317 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15318 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15319 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15321 // Machine Information
15322 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15323 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15324 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15325 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15326 DebugLoc DL = MI->getDebugLoc();
15328 // struct va_list {
15331 // i64 overflow_area (address)
15332 // i64 reg_save_area (address)
15334 // sizeof(va_list) = 24
15335 // alignment(va_list) = 8
15337 unsigned TotalNumIntRegs = 6;
15338 unsigned TotalNumXMMRegs = 8;
15339 bool UseGPOffset = (ArgMode == 1);
15340 bool UseFPOffset = (ArgMode == 2);
15341 unsigned MaxOffset = TotalNumIntRegs * 8 +
15342 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15344 /* Align ArgSize to a multiple of 8 */
15345 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15346 bool NeedsAlign = (Align > 8);
15348 MachineBasicBlock *thisMBB = MBB;
15349 MachineBasicBlock *overflowMBB;
15350 MachineBasicBlock *offsetMBB;
15351 MachineBasicBlock *endMBB;
15353 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15354 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15355 unsigned OffsetReg = 0;
15357 if (!UseGPOffset && !UseFPOffset) {
15358 // If we only pull from the overflow region, we don't create a branch.
15359 // We don't need to alter control flow.
15360 OffsetDestReg = 0; // unused
15361 OverflowDestReg = DestReg;
15364 overflowMBB = thisMBB;
15367 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15368 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15369 // If not, pull from overflow_area. (branch to overflowMBB)
15374 // offsetMBB overflowMBB
15379 // Registers for the PHI in endMBB
15380 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15381 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15383 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15384 MachineFunction *MF = MBB->getParent();
15385 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15386 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15387 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15389 MachineFunction::iterator MBBIter = MBB;
15392 // Insert the new basic blocks
15393 MF->insert(MBBIter, offsetMBB);
15394 MF->insert(MBBIter, overflowMBB);
15395 MF->insert(MBBIter, endMBB);
15397 // Transfer the remainder of MBB and its successor edges to endMBB.
15398 endMBB->splice(endMBB->begin(), thisMBB,
15399 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15400 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15402 // Make offsetMBB and overflowMBB successors of thisMBB
15403 thisMBB->addSuccessor(offsetMBB);
15404 thisMBB->addSuccessor(overflowMBB);
15406 // endMBB is a successor of both offsetMBB and overflowMBB
15407 offsetMBB->addSuccessor(endMBB);
15408 overflowMBB->addSuccessor(endMBB);
15410 // Load the offset value into a register
15411 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15412 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15416 .addDisp(Disp, UseFPOffset ? 4 : 0)
15417 .addOperand(Segment)
15418 .setMemRefs(MMOBegin, MMOEnd);
15420 // Check if there is enough room left to pull this argument.
15421 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15423 .addImm(MaxOffset + 8 - ArgSizeA8);
15425 // Branch to "overflowMBB" if offset >= max
15426 // Fall through to "offsetMBB" otherwise
15427 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15428 .addMBB(overflowMBB);
15431 // In offsetMBB, emit code to use the reg_save_area.
15433 assert(OffsetReg != 0);
15435 // Read the reg_save_area address.
15436 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15437 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15442 .addOperand(Segment)
15443 .setMemRefs(MMOBegin, MMOEnd);
15445 // Zero-extend the offset
15446 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15447 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15450 .addImm(X86::sub_32bit);
15452 // Add the offset to the reg_save_area to get the final address.
15453 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15454 .addReg(OffsetReg64)
15455 .addReg(RegSaveReg);
15457 // Compute the offset for the next argument
15458 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15459 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15461 .addImm(UseFPOffset ? 16 : 8);
15463 // Store it back into the va_list.
15464 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15468 .addDisp(Disp, UseFPOffset ? 4 : 0)
15469 .addOperand(Segment)
15470 .addReg(NextOffsetReg)
15471 .setMemRefs(MMOBegin, MMOEnd);
15474 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15479 // Emit code to use overflow area
15482 // Load the overflow_area address into a register.
15483 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15484 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15489 .addOperand(Segment)
15490 .setMemRefs(MMOBegin, MMOEnd);
15492 // If we need to align it, do so. Otherwise, just copy the address
15493 // to OverflowDestReg.
15495 // Align the overflow address
15496 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15497 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15499 // aligned_addr = (addr + (align-1)) & ~(align-1)
15500 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15501 .addReg(OverflowAddrReg)
15504 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15506 .addImm(~(uint64_t)(Align-1));
15508 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15509 .addReg(OverflowAddrReg);
15512 // Compute the next overflow address after this argument.
15513 // (the overflow address should be kept 8-byte aligned)
15514 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15515 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15516 .addReg(OverflowDestReg)
15517 .addImm(ArgSizeA8);
15519 // Store the new overflow address.
15520 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15525 .addOperand(Segment)
15526 .addReg(NextAddrReg)
15527 .setMemRefs(MMOBegin, MMOEnd);
15529 // If we branched, emit the PHI to the front of endMBB.
15531 BuildMI(*endMBB, endMBB->begin(), DL,
15532 TII->get(X86::PHI), DestReg)
15533 .addReg(OffsetDestReg).addMBB(offsetMBB)
15534 .addReg(OverflowDestReg).addMBB(overflowMBB);
15537 // Erase the pseudo instruction
15538 MI->eraseFromParent();
15543 MachineBasicBlock *
15544 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15546 MachineBasicBlock *MBB) const {
15547 // Emit code to save XMM registers to the stack. The ABI says that the
15548 // number of registers to save is given in %al, so it's theoretically
15549 // possible to do an indirect jump trick to avoid saving all of them,
15550 // however this code takes a simpler approach and just executes all
15551 // of the stores if %al is non-zero. It's less code, and it's probably
15552 // easier on the hardware branch predictor, and stores aren't all that
15553 // expensive anyway.
15555 // Create the new basic blocks. One block contains all the XMM stores,
15556 // and one block is the final destination regardless of whether any
15557 // stores were performed.
15558 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15559 MachineFunction *F = MBB->getParent();
15560 MachineFunction::iterator MBBIter = MBB;
15562 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15563 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15564 F->insert(MBBIter, XMMSaveMBB);
15565 F->insert(MBBIter, EndMBB);
15567 // Transfer the remainder of MBB and its successor edges to EndMBB.
15568 EndMBB->splice(EndMBB->begin(), MBB,
15569 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15570 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15572 // The original block will now fall through to the XMM save block.
15573 MBB->addSuccessor(XMMSaveMBB);
15574 // The XMMSaveMBB will fall through to the end block.
15575 XMMSaveMBB->addSuccessor(EndMBB);
15577 // Now add the instructions.
15578 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15579 DebugLoc DL = MI->getDebugLoc();
15581 unsigned CountReg = MI->getOperand(0).getReg();
15582 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15583 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15585 if (!Subtarget->isTargetWin64()) {
15586 // If %al is 0, branch around the XMM save block.
15587 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15588 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15589 MBB->addSuccessor(EndMBB);
15592 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15593 // that was just emitted, but clearly shouldn't be "saved".
15594 assert((MI->getNumOperands() <= 3 ||
15595 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15596 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15597 && "Expected last argument to be EFLAGS");
15598 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15599 // In the XMM save block, save all the XMM argument registers.
15600 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15601 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15602 MachineMemOperand *MMO =
15603 F->getMachineMemOperand(
15604 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15605 MachineMemOperand::MOStore,
15606 /*Size=*/16, /*Align=*/16);
15607 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15608 .addFrameIndex(RegSaveFrameIndex)
15609 .addImm(/*Scale=*/1)
15610 .addReg(/*IndexReg=*/0)
15611 .addImm(/*Disp=*/Offset)
15612 .addReg(/*Segment=*/0)
15613 .addReg(MI->getOperand(i).getReg())
15614 .addMemOperand(MMO);
15617 MI->eraseFromParent(); // The pseudo instruction is gone now.
15622 // The EFLAGS operand of SelectItr might be missing a kill marker
15623 // because there were multiple uses of EFLAGS, and ISel didn't know
15624 // which to mark. Figure out whether SelectItr should have had a
15625 // kill marker, and set it if it should. Returns the correct kill
15627 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15628 MachineBasicBlock* BB,
15629 const TargetRegisterInfo* TRI) {
15630 // Scan forward through BB for a use/def of EFLAGS.
15631 MachineBasicBlock::iterator miI(std::next(SelectItr));
15632 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15633 const MachineInstr& mi = *miI;
15634 if (mi.readsRegister(X86::EFLAGS))
15636 if (mi.definesRegister(X86::EFLAGS))
15637 break; // Should have kill-flag - update below.
15640 // If we hit the end of the block, check whether EFLAGS is live into a
15642 if (miI == BB->end()) {
15643 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15644 sEnd = BB->succ_end();
15645 sItr != sEnd; ++sItr) {
15646 MachineBasicBlock* succ = *sItr;
15647 if (succ->isLiveIn(X86::EFLAGS))
15652 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15653 // out. SelectMI should have a kill flag on EFLAGS.
15654 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15658 MachineBasicBlock *
15659 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15660 MachineBasicBlock *BB) const {
15661 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15662 DebugLoc DL = MI->getDebugLoc();
15664 // To "insert" a SELECT_CC instruction, we actually have to insert the
15665 // diamond control-flow pattern. The incoming instruction knows the
15666 // destination vreg to set, the condition code register to branch on, the
15667 // true/false values to select between, and a branch opcode to use.
15668 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15669 MachineFunction::iterator It = BB;
15675 // cmpTY ccX, r1, r2
15677 // fallthrough --> copy0MBB
15678 MachineBasicBlock *thisMBB = BB;
15679 MachineFunction *F = BB->getParent();
15680 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15681 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15682 F->insert(It, copy0MBB);
15683 F->insert(It, sinkMBB);
15685 // If the EFLAGS register isn't dead in the terminator, then claim that it's
15686 // live into the sink and copy blocks.
15687 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15688 if (!MI->killsRegister(X86::EFLAGS) &&
15689 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15690 copy0MBB->addLiveIn(X86::EFLAGS);
15691 sinkMBB->addLiveIn(X86::EFLAGS);
15694 // Transfer the remainder of BB and its successor edges to sinkMBB.
15695 sinkMBB->splice(sinkMBB->begin(), BB,
15696 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15697 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15699 // Add the true and fallthrough blocks as its successors.
15700 BB->addSuccessor(copy0MBB);
15701 BB->addSuccessor(sinkMBB);
15703 // Create the conditional branch instruction.
15705 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15706 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15709 // %FalseValue = ...
15710 // # fallthrough to sinkMBB
15711 copy0MBB->addSuccessor(sinkMBB);
15714 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15716 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15717 TII->get(X86::PHI), MI->getOperand(0).getReg())
15718 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15719 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15721 MI->eraseFromParent(); // The pseudo instruction is gone now.
15725 MachineBasicBlock *
15726 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15727 bool Is64Bit) const {
15728 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15729 DebugLoc DL = MI->getDebugLoc();
15730 MachineFunction *MF = BB->getParent();
15731 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15733 assert(getTargetMachine().Options.EnableSegmentedStacks);
15735 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15736 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15739 // ... [Till the alloca]
15740 // If stacklet is not large enough, jump to mallocMBB
15743 // Allocate by subtracting from RSP
15744 // Jump to continueMBB
15747 // Allocate by call to runtime
15751 // [rest of original BB]
15754 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15755 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15756 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15758 MachineRegisterInfo &MRI = MF->getRegInfo();
15759 const TargetRegisterClass *AddrRegClass =
15760 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15762 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15763 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15764 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15765 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15766 sizeVReg = MI->getOperand(1).getReg(),
15767 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15769 MachineFunction::iterator MBBIter = BB;
15772 MF->insert(MBBIter, bumpMBB);
15773 MF->insert(MBBIter, mallocMBB);
15774 MF->insert(MBBIter, continueMBB);
15776 continueMBB->splice(continueMBB->begin(), BB,
15777 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15778 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15780 // Add code to the main basic block to check if the stack limit has been hit,
15781 // and if so, jump to mallocMBB otherwise to bumpMBB.
15782 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15783 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15784 .addReg(tmpSPVReg).addReg(sizeVReg);
15785 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15786 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15787 .addReg(SPLimitVReg);
15788 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15790 // bumpMBB simply decreases the stack pointer, since we know the current
15791 // stacklet has enough space.
15792 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15793 .addReg(SPLimitVReg);
15794 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15795 .addReg(SPLimitVReg);
15796 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15798 // Calls into a routine in libgcc to allocate more space from the heap.
15799 const uint32_t *RegMask =
15800 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15802 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15804 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15805 .addExternalSymbol("__morestack_allocate_stack_space")
15806 .addRegMask(RegMask)
15807 .addReg(X86::RDI, RegState::Implicit)
15808 .addReg(X86::RAX, RegState::ImplicitDefine);
15810 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15812 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15813 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15814 .addExternalSymbol("__morestack_allocate_stack_space")
15815 .addRegMask(RegMask)
15816 .addReg(X86::EAX, RegState::ImplicitDefine);
15820 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15823 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15824 .addReg(Is64Bit ? X86::RAX : X86::EAX);
15825 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15827 // Set up the CFG correctly.
15828 BB->addSuccessor(bumpMBB);
15829 BB->addSuccessor(mallocMBB);
15830 mallocMBB->addSuccessor(continueMBB);
15831 bumpMBB->addSuccessor(continueMBB);
15833 // Take care of the PHI nodes.
15834 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15835 MI->getOperand(0).getReg())
15836 .addReg(mallocPtrVReg).addMBB(mallocMBB)
15837 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15839 // Delete the original pseudo instruction.
15840 MI->eraseFromParent();
15843 return continueMBB;
15846 MachineBasicBlock *
15847 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15848 MachineBasicBlock *BB) const {
15849 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15850 DebugLoc DL = MI->getDebugLoc();
15852 assert(!Subtarget->isTargetMacho());
15854 // The lowering is pretty easy: we're just emitting the call to _alloca. The
15855 // non-trivial part is impdef of ESP.
15857 if (Subtarget->isTargetWin64()) {
15858 if (Subtarget->isTargetCygMing()) {
15859 // ___chkstk(Mingw64):
15860 // Clobbers R10, R11, RAX and EFLAGS.
15862 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15863 .addExternalSymbol("___chkstk")
15864 .addReg(X86::RAX, RegState::Implicit)
15865 .addReg(X86::RSP, RegState::Implicit)
15866 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15867 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15868 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15870 // __chkstk(MSVCRT): does not update stack pointer.
15871 // Clobbers R10, R11 and EFLAGS.
15872 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15873 .addExternalSymbol("__chkstk")
15874 .addReg(X86::RAX, RegState::Implicit)
15875 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15876 // RAX has the offset to be subtracted from RSP.
15877 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15882 const char *StackProbeSymbol =
15883 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15885 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15886 .addExternalSymbol(StackProbeSymbol)
15887 .addReg(X86::EAX, RegState::Implicit)
15888 .addReg(X86::ESP, RegState::Implicit)
15889 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15890 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15891 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15894 MI->eraseFromParent(); // The pseudo instruction is gone now.
15898 MachineBasicBlock *
15899 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15900 MachineBasicBlock *BB) const {
15901 // This is pretty easy. We're taking the value that we received from
15902 // our load from the relocation, sticking it in either RDI (x86-64)
15903 // or EAX and doing an indirect call. The return value will then
15904 // be in the normal return register.
15905 const X86InstrInfo *TII
15906 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15907 DebugLoc DL = MI->getDebugLoc();
15908 MachineFunction *F = BB->getParent();
15910 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15911 assert(MI->getOperand(3).isGlobal() && "This should be a global");
15913 // Get a register mask for the lowered call.
15914 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15915 // proper register mask.
15916 const uint32_t *RegMask =
15917 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15918 if (Subtarget->is64Bit()) {
15919 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15920 TII->get(X86::MOV64rm), X86::RDI)
15922 .addImm(0).addReg(0)
15923 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15924 MI->getOperand(3).getTargetFlags())
15926 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15927 addDirectMem(MIB, X86::RDI);
15928 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15929 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15930 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15931 TII->get(X86::MOV32rm), X86::EAX)
15933 .addImm(0).addReg(0)
15934 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15935 MI->getOperand(3).getTargetFlags())
15937 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15938 addDirectMem(MIB, X86::EAX);
15939 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15941 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15942 TII->get(X86::MOV32rm), X86::EAX)
15943 .addReg(TII->getGlobalBaseReg(F))
15944 .addImm(0).addReg(0)
15945 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15946 MI->getOperand(3).getTargetFlags())
15948 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15949 addDirectMem(MIB, X86::EAX);
15950 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15953 MI->eraseFromParent(); // The pseudo instruction is gone now.
15957 MachineBasicBlock *
15958 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15959 MachineBasicBlock *MBB) const {
15960 DebugLoc DL = MI->getDebugLoc();
15961 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15963 MachineFunction *MF = MBB->getParent();
15964 MachineRegisterInfo &MRI = MF->getRegInfo();
15966 const BasicBlock *BB = MBB->getBasicBlock();
15967 MachineFunction::iterator I = MBB;
15970 // Memory Reference
15971 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15972 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15975 unsigned MemOpndSlot = 0;
15977 unsigned CurOp = 0;
15979 DstReg = MI->getOperand(CurOp++).getReg();
15980 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15981 assert(RC->hasType(MVT::i32) && "Invalid destination!");
15982 unsigned mainDstReg = MRI.createVirtualRegister(RC);
15983 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15985 MemOpndSlot = CurOp;
15987 MVT PVT = getPointerTy();
15988 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15989 "Invalid Pointer Size!");
15991 // For v = setjmp(buf), we generate
15994 // buf[LabelOffset] = restoreMBB
15995 // SjLjSetup restoreMBB
16001 // v = phi(main, restore)
16006 MachineBasicBlock *thisMBB = MBB;
16007 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16008 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16009 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16010 MF->insert(I, mainMBB);
16011 MF->insert(I, sinkMBB);
16012 MF->push_back(restoreMBB);
16014 MachineInstrBuilder MIB;
16016 // Transfer the remainder of BB and its successor edges to sinkMBB.
16017 sinkMBB->splice(sinkMBB->begin(), MBB,
16018 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16019 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16022 unsigned PtrStoreOpc = 0;
16023 unsigned LabelReg = 0;
16024 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16025 Reloc::Model RM = getTargetMachine().getRelocationModel();
16026 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16027 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16029 // Prepare IP either in reg or imm.
16030 if (!UseImmLabel) {
16031 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16032 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16033 LabelReg = MRI.createVirtualRegister(PtrRC);
16034 if (Subtarget->is64Bit()) {
16035 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16039 .addMBB(restoreMBB)
16042 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16043 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16044 .addReg(XII->getGlobalBaseReg(MF))
16047 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16051 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16053 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16054 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16055 if (i == X86::AddrDisp)
16056 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16058 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16061 MIB.addReg(LabelReg);
16063 MIB.addMBB(restoreMBB);
16064 MIB.setMemRefs(MMOBegin, MMOEnd);
16066 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16067 .addMBB(restoreMBB);
16069 const X86RegisterInfo *RegInfo =
16070 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16071 MIB.addRegMask(RegInfo->getNoPreservedMask());
16072 thisMBB->addSuccessor(mainMBB);
16073 thisMBB->addSuccessor(restoreMBB);
16077 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16078 mainMBB->addSuccessor(sinkMBB);
16081 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16082 TII->get(X86::PHI), DstReg)
16083 .addReg(mainDstReg).addMBB(mainMBB)
16084 .addReg(restoreDstReg).addMBB(restoreMBB);
16087 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16088 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16089 restoreMBB->addSuccessor(sinkMBB);
16091 MI->eraseFromParent();
16095 MachineBasicBlock *
16096 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16097 MachineBasicBlock *MBB) const {
16098 DebugLoc DL = MI->getDebugLoc();
16099 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16101 MachineFunction *MF = MBB->getParent();
16102 MachineRegisterInfo &MRI = MF->getRegInfo();
16104 // Memory Reference
16105 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16106 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16108 MVT PVT = getPointerTy();
16109 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16110 "Invalid Pointer Size!");
16112 const TargetRegisterClass *RC =
16113 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16114 unsigned Tmp = MRI.createVirtualRegister(RC);
16115 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16116 const X86RegisterInfo *RegInfo =
16117 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16118 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16119 unsigned SP = RegInfo->getStackRegister();
16121 MachineInstrBuilder MIB;
16123 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16124 const int64_t SPOffset = 2 * PVT.getStoreSize();
16126 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16127 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16130 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16131 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16132 MIB.addOperand(MI->getOperand(i));
16133 MIB.setMemRefs(MMOBegin, MMOEnd);
16135 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16136 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16137 if (i == X86::AddrDisp)
16138 MIB.addDisp(MI->getOperand(i), LabelOffset);
16140 MIB.addOperand(MI->getOperand(i));
16142 MIB.setMemRefs(MMOBegin, MMOEnd);
16144 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16145 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16146 if (i == X86::AddrDisp)
16147 MIB.addDisp(MI->getOperand(i), SPOffset);
16149 MIB.addOperand(MI->getOperand(i));
16151 MIB.setMemRefs(MMOBegin, MMOEnd);
16153 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16155 MI->eraseFromParent();
16159 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16160 // accumulator loops. Writing back to the accumulator allows the coalescer
16161 // to remove extra copies in the loop.
16162 MachineBasicBlock *
16163 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16164 MachineBasicBlock *MBB) const {
16165 MachineOperand &AddendOp = MI->getOperand(3);
16167 // Bail out early if the addend isn't a register - we can't switch these.
16168 if (!AddendOp.isReg())
16171 MachineFunction &MF = *MBB->getParent();
16172 MachineRegisterInfo &MRI = MF.getRegInfo();
16174 // Check whether the addend is defined by a PHI:
16175 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16176 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16177 if (!AddendDef.isPHI())
16180 // Look for the following pattern:
16182 // %addend = phi [%entry, 0], [%loop, %result]
16184 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16188 // %addend = phi [%entry, 0], [%loop, %result]
16190 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16192 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16193 assert(AddendDef.getOperand(i).isReg());
16194 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16195 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16196 if (&PHISrcInst == MI) {
16197 // Found a matching instruction.
16198 unsigned NewFMAOpc = 0;
16199 switch (MI->getOpcode()) {
16200 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16201 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16202 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16203 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16204 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16205 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16206 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16207 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16208 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16209 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16210 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16211 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16212 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16213 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16214 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16215 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16216 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16217 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16218 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16219 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16220 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16221 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16222 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16223 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16224 default: llvm_unreachable("Unrecognized FMA variant.");
16227 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16228 MachineInstrBuilder MIB =
16229 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16230 .addOperand(MI->getOperand(0))
16231 .addOperand(MI->getOperand(3))
16232 .addOperand(MI->getOperand(2))
16233 .addOperand(MI->getOperand(1));
16234 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16235 MI->eraseFromParent();
16242 MachineBasicBlock *
16243 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16244 MachineBasicBlock *BB) const {
16245 switch (MI->getOpcode()) {
16246 default: llvm_unreachable("Unexpected instr type to insert");
16247 case X86::TAILJMPd64:
16248 case X86::TAILJMPr64:
16249 case X86::TAILJMPm64:
16250 llvm_unreachable("TAILJMP64 would not be touched here.");
16251 case X86::TCRETURNdi64:
16252 case X86::TCRETURNri64:
16253 case X86::TCRETURNmi64:
16255 case X86::WIN_ALLOCA:
16256 return EmitLoweredWinAlloca(MI, BB);
16257 case X86::SEG_ALLOCA_32:
16258 return EmitLoweredSegAlloca(MI, BB, false);
16259 case X86::SEG_ALLOCA_64:
16260 return EmitLoweredSegAlloca(MI, BB, true);
16261 case X86::TLSCall_32:
16262 case X86::TLSCall_64:
16263 return EmitLoweredTLSCall(MI, BB);
16264 case X86::CMOV_GR8:
16265 case X86::CMOV_FR32:
16266 case X86::CMOV_FR64:
16267 case X86::CMOV_V4F32:
16268 case X86::CMOV_V2F64:
16269 case X86::CMOV_V2I64:
16270 case X86::CMOV_V8F32:
16271 case X86::CMOV_V4F64:
16272 case X86::CMOV_V4I64:
16273 case X86::CMOV_V16F32:
16274 case X86::CMOV_V8F64:
16275 case X86::CMOV_V8I64:
16276 case X86::CMOV_GR16:
16277 case X86::CMOV_GR32:
16278 case X86::CMOV_RFP32:
16279 case X86::CMOV_RFP64:
16280 case X86::CMOV_RFP80:
16281 return EmitLoweredSelect(MI, BB);
16283 case X86::FP32_TO_INT16_IN_MEM:
16284 case X86::FP32_TO_INT32_IN_MEM:
16285 case X86::FP32_TO_INT64_IN_MEM:
16286 case X86::FP64_TO_INT16_IN_MEM:
16287 case X86::FP64_TO_INT32_IN_MEM:
16288 case X86::FP64_TO_INT64_IN_MEM:
16289 case X86::FP80_TO_INT16_IN_MEM:
16290 case X86::FP80_TO_INT32_IN_MEM:
16291 case X86::FP80_TO_INT64_IN_MEM: {
16292 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16293 DebugLoc DL = MI->getDebugLoc();
16295 // Change the floating point control register to use "round towards zero"
16296 // mode when truncating to an integer value.
16297 MachineFunction *F = BB->getParent();
16298 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16299 addFrameReference(BuildMI(*BB, MI, DL,
16300 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16302 // Load the old value of the high byte of the control word...
16304 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16305 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16308 // Set the high part to be round to zero...
16309 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16312 // Reload the modified control word now...
16313 addFrameReference(BuildMI(*BB, MI, DL,
16314 TII->get(X86::FLDCW16m)), CWFrameIdx);
16316 // Restore the memory image of control word to original value
16317 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16320 // Get the X86 opcode to use.
16322 switch (MI->getOpcode()) {
16323 default: llvm_unreachable("illegal opcode!");
16324 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16325 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16326 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16327 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16328 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16329 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16330 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16331 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16332 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16336 MachineOperand &Op = MI->getOperand(0);
16338 AM.BaseType = X86AddressMode::RegBase;
16339 AM.Base.Reg = Op.getReg();
16341 AM.BaseType = X86AddressMode::FrameIndexBase;
16342 AM.Base.FrameIndex = Op.getIndex();
16344 Op = MI->getOperand(1);
16346 AM.Scale = Op.getImm();
16347 Op = MI->getOperand(2);
16349 AM.IndexReg = Op.getImm();
16350 Op = MI->getOperand(3);
16351 if (Op.isGlobal()) {
16352 AM.GV = Op.getGlobal();
16354 AM.Disp = Op.getImm();
16356 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16357 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16359 // Reload the original control word now.
16360 addFrameReference(BuildMI(*BB, MI, DL,
16361 TII->get(X86::FLDCW16m)), CWFrameIdx);
16363 MI->eraseFromParent(); // The pseudo instruction is gone now.
16366 // String/text processing lowering.
16367 case X86::PCMPISTRM128REG:
16368 case X86::VPCMPISTRM128REG:
16369 case X86::PCMPISTRM128MEM:
16370 case X86::VPCMPISTRM128MEM:
16371 case X86::PCMPESTRM128REG:
16372 case X86::VPCMPESTRM128REG:
16373 case X86::PCMPESTRM128MEM:
16374 case X86::VPCMPESTRM128MEM:
16375 assert(Subtarget->hasSSE42() &&
16376 "Target must have SSE4.2 or AVX features enabled");
16377 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16379 // String/text processing lowering.
16380 case X86::PCMPISTRIREG:
16381 case X86::VPCMPISTRIREG:
16382 case X86::PCMPISTRIMEM:
16383 case X86::VPCMPISTRIMEM:
16384 case X86::PCMPESTRIREG:
16385 case X86::VPCMPESTRIREG:
16386 case X86::PCMPESTRIMEM:
16387 case X86::VPCMPESTRIMEM:
16388 assert(Subtarget->hasSSE42() &&
16389 "Target must have SSE4.2 or AVX features enabled");
16390 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16392 // Thread synchronization.
16394 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16398 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16400 // Atomic Lowering.
16401 case X86::ATOMAND8:
16402 case X86::ATOMAND16:
16403 case X86::ATOMAND32:
16404 case X86::ATOMAND64:
16407 case X86::ATOMOR16:
16408 case X86::ATOMOR32:
16409 case X86::ATOMOR64:
16411 case X86::ATOMXOR16:
16412 case X86::ATOMXOR8:
16413 case X86::ATOMXOR32:
16414 case X86::ATOMXOR64:
16416 case X86::ATOMNAND8:
16417 case X86::ATOMNAND16:
16418 case X86::ATOMNAND32:
16419 case X86::ATOMNAND64:
16421 case X86::ATOMMAX8:
16422 case X86::ATOMMAX16:
16423 case X86::ATOMMAX32:
16424 case X86::ATOMMAX64:
16426 case X86::ATOMMIN8:
16427 case X86::ATOMMIN16:
16428 case X86::ATOMMIN32:
16429 case X86::ATOMMIN64:
16431 case X86::ATOMUMAX8:
16432 case X86::ATOMUMAX16:
16433 case X86::ATOMUMAX32:
16434 case X86::ATOMUMAX64:
16436 case X86::ATOMUMIN8:
16437 case X86::ATOMUMIN16:
16438 case X86::ATOMUMIN32:
16439 case X86::ATOMUMIN64:
16440 return EmitAtomicLoadArith(MI, BB);
16442 // This group does 64-bit operations on a 32-bit host.
16443 case X86::ATOMAND6432:
16444 case X86::ATOMOR6432:
16445 case X86::ATOMXOR6432:
16446 case X86::ATOMNAND6432:
16447 case X86::ATOMADD6432:
16448 case X86::ATOMSUB6432:
16449 case X86::ATOMMAX6432:
16450 case X86::ATOMMIN6432:
16451 case X86::ATOMUMAX6432:
16452 case X86::ATOMUMIN6432:
16453 case X86::ATOMSWAP6432:
16454 return EmitAtomicLoadArith6432(MI, BB);
16456 case X86::VASTART_SAVE_XMM_REGS:
16457 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16459 case X86::VAARG_64:
16460 return EmitVAARG64WithCustomInserter(MI, BB);
16462 case X86::EH_SjLj_SetJmp32:
16463 case X86::EH_SjLj_SetJmp64:
16464 return emitEHSjLjSetJmp(MI, BB);
16466 case X86::EH_SjLj_LongJmp32:
16467 case X86::EH_SjLj_LongJmp64:
16468 return emitEHSjLjLongJmp(MI, BB);
16470 case TargetOpcode::STACKMAP:
16471 case TargetOpcode::PATCHPOINT:
16472 return emitPatchPoint(MI, BB);
16474 case X86::VFMADDPDr213r:
16475 case X86::VFMADDPSr213r:
16476 case X86::VFMADDSDr213r:
16477 case X86::VFMADDSSr213r:
16478 case X86::VFMSUBPDr213r:
16479 case X86::VFMSUBPSr213r:
16480 case X86::VFMSUBSDr213r:
16481 case X86::VFMSUBSSr213r:
16482 case X86::VFNMADDPDr213r:
16483 case X86::VFNMADDPSr213r:
16484 case X86::VFNMADDSDr213r:
16485 case X86::VFNMADDSSr213r:
16486 case X86::VFNMSUBPDr213r:
16487 case X86::VFNMSUBPSr213r:
16488 case X86::VFNMSUBSDr213r:
16489 case X86::VFNMSUBSSr213r:
16490 case X86::VFMADDPDr213rY:
16491 case X86::VFMADDPSr213rY:
16492 case X86::VFMSUBPDr213rY:
16493 case X86::VFMSUBPSr213rY:
16494 case X86::VFNMADDPDr213rY:
16495 case X86::VFNMADDPSr213rY:
16496 case X86::VFNMSUBPDr213rY:
16497 case X86::VFNMSUBPSr213rY:
16498 return emitFMA3Instr(MI, BB);
16502 //===----------------------------------------------------------------------===//
16503 // X86 Optimization Hooks
16504 //===----------------------------------------------------------------------===//
16506 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16509 const SelectionDAG &DAG,
16510 unsigned Depth) const {
16511 unsigned BitWidth = KnownZero.getBitWidth();
16512 unsigned Opc = Op.getOpcode();
16513 assert((Opc >= ISD::BUILTIN_OP_END ||
16514 Opc == ISD::INTRINSIC_WO_CHAIN ||
16515 Opc == ISD::INTRINSIC_W_CHAIN ||
16516 Opc == ISD::INTRINSIC_VOID) &&
16517 "Should use MaskedValueIsZero if you don't know whether Op"
16518 " is a target node!");
16520 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16534 // These nodes' second result is a boolean.
16535 if (Op.getResNo() == 0)
16538 case X86ISD::SETCC:
16539 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16541 case ISD::INTRINSIC_WO_CHAIN: {
16542 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16543 unsigned NumLoBits = 0;
16546 case Intrinsic::x86_sse_movmsk_ps:
16547 case Intrinsic::x86_avx_movmsk_ps_256:
16548 case Intrinsic::x86_sse2_movmsk_pd:
16549 case Intrinsic::x86_avx_movmsk_pd_256:
16550 case Intrinsic::x86_mmx_pmovmskb:
16551 case Intrinsic::x86_sse2_pmovmskb_128:
16552 case Intrinsic::x86_avx2_pmovmskb: {
16553 // High bits of movmskp{s|d}, pmovmskb are known zero.
16555 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16556 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16557 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16558 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16559 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16560 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16561 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16562 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16564 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16573 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16574 unsigned Depth) const {
16575 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16576 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16577 return Op.getValueType().getScalarType().getSizeInBits();
16583 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16584 /// node is a GlobalAddress + offset.
16585 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16586 const GlobalValue* &GA,
16587 int64_t &Offset) const {
16588 if (N->getOpcode() == X86ISD::Wrapper) {
16589 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16590 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16591 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16595 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16598 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16599 /// same as extracting the high 128-bit part of 256-bit vector and then
16600 /// inserting the result into the low part of a new 256-bit vector
16601 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16602 EVT VT = SVOp->getValueType(0);
16603 unsigned NumElems = VT.getVectorNumElements();
16605 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16606 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16607 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16608 SVOp->getMaskElt(j) >= 0)
16614 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16615 /// same as extracting the low 128-bit part of 256-bit vector and then
16616 /// inserting the result into the high part of a new 256-bit vector
16617 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16618 EVT VT = SVOp->getValueType(0);
16619 unsigned NumElems = VT.getVectorNumElements();
16621 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16622 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16623 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16624 SVOp->getMaskElt(j) >= 0)
16630 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16631 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16632 TargetLowering::DAGCombinerInfo &DCI,
16633 const X86Subtarget* Subtarget) {
16635 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16636 SDValue V1 = SVOp->getOperand(0);
16637 SDValue V2 = SVOp->getOperand(1);
16638 EVT VT = SVOp->getValueType(0);
16639 unsigned NumElems = VT.getVectorNumElements();
16641 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16642 V2.getOpcode() == ISD::CONCAT_VECTORS) {
16646 // V UNDEF BUILD_VECTOR UNDEF
16648 // CONCAT_VECTOR CONCAT_VECTOR
16651 // RESULT: V + zero extended
16653 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16654 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16655 V1.getOperand(1).getOpcode() != ISD::UNDEF)
16658 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16661 // To match the shuffle mask, the first half of the mask should
16662 // be exactly the first vector, and all the rest a splat with the
16663 // first element of the second one.
16664 for (unsigned i = 0; i != NumElems/2; ++i)
16665 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16666 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16669 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16670 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16671 if (Ld->hasNUsesOfValue(1, 0)) {
16672 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16673 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16675 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16676 array_lengthof(Ops),
16678 Ld->getPointerInfo(),
16679 Ld->getAlignment(),
16680 false/*isVolatile*/, true/*ReadMem*/,
16681 false/*WriteMem*/);
16683 // Make sure the newly-created LOAD is in the same position as Ld in
16684 // terms of dependency. We create a TokenFactor for Ld and ResNode,
16685 // and update uses of Ld's output chain to use the TokenFactor.
16686 if (Ld->hasAnyUseOfValue(1)) {
16687 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16688 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16689 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16690 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16691 SDValue(ResNode.getNode(), 1));
16694 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16698 // Emit a zeroed vector and insert the desired subvector on its
16700 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16701 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16702 return DCI.CombineTo(N, InsV);
16705 //===--------------------------------------------------------------------===//
16706 // Combine some shuffles into subvector extracts and inserts:
16709 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16710 if (isShuffleHigh128VectorInsertLow(SVOp)) {
16711 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16712 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16713 return DCI.CombineTo(N, InsV);
16716 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16717 if (isShuffleLow128VectorInsertHigh(SVOp)) {
16718 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16719 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16720 return DCI.CombineTo(N, InsV);
16726 /// PerformShuffleCombine - Performs several different shuffle combines.
16727 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16728 TargetLowering::DAGCombinerInfo &DCI,
16729 const X86Subtarget *Subtarget) {
16731 EVT VT = N->getValueType(0);
16733 // Don't create instructions with illegal types after legalize types has run.
16734 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16735 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16738 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16739 if (Subtarget->hasFp256() && VT.is256BitVector() &&
16740 N->getOpcode() == ISD::VECTOR_SHUFFLE)
16741 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16743 // Only handle 128 wide vector from here on.
16744 if (!VT.is128BitVector())
16747 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16748 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16749 // consecutive, non-overlapping, and in the right order.
16750 SmallVector<SDValue, 16> Elts;
16751 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16752 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16754 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16757 /// PerformTruncateCombine - Converts truncate operation to
16758 /// a sequence of vector shuffle operations.
16759 /// It is possible when we truncate 256-bit vector to 128-bit vector
16760 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16761 TargetLowering::DAGCombinerInfo &DCI,
16762 const X86Subtarget *Subtarget) {
16766 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16767 /// specific shuffle of a load can be folded into a single element load.
16768 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16769 /// shuffles have been customed lowered so we need to handle those here.
16770 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16771 TargetLowering::DAGCombinerInfo &DCI) {
16772 if (DCI.isBeforeLegalizeOps())
16775 SDValue InVec = N->getOperand(0);
16776 SDValue EltNo = N->getOperand(1);
16778 if (!isa<ConstantSDNode>(EltNo))
16781 EVT VT = InVec.getValueType();
16783 bool HasShuffleIntoBitcast = false;
16784 if (InVec.getOpcode() == ISD::BITCAST) {
16785 // Don't duplicate a load with other uses.
16786 if (!InVec.hasOneUse())
16788 EVT BCVT = InVec.getOperand(0).getValueType();
16789 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16791 InVec = InVec.getOperand(0);
16792 HasShuffleIntoBitcast = true;
16795 if (!isTargetShuffle(InVec.getOpcode()))
16798 // Don't duplicate a load with other uses.
16799 if (!InVec.hasOneUse())
16802 SmallVector<int, 16> ShuffleMask;
16804 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16808 // Select the input vector, guarding against out of range extract vector.
16809 unsigned NumElems = VT.getVectorNumElements();
16810 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16811 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16812 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16813 : InVec.getOperand(1);
16815 // If inputs to shuffle are the same for both ops, then allow 2 uses
16816 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16818 if (LdNode.getOpcode() == ISD::BITCAST) {
16819 // Don't duplicate a load with other uses.
16820 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16823 AllowedUses = 1; // only allow 1 load use if we have a bitcast
16824 LdNode = LdNode.getOperand(0);
16827 if (!ISD::isNormalLoad(LdNode.getNode()))
16830 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16832 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16835 if (HasShuffleIntoBitcast) {
16836 // If there's a bitcast before the shuffle, check if the load type and
16837 // alignment is valid.
16838 unsigned Align = LN0->getAlignment();
16839 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16840 unsigned NewAlign = TLI.getDataLayout()->
16841 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16843 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16847 // All checks match so transform back to vector_shuffle so that DAG combiner
16848 // can finish the job
16851 // Create shuffle node taking into account the case that its a unary shuffle
16852 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16853 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16854 InVec.getOperand(0), Shuffle,
16856 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16857 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16861 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16862 /// generation and convert it from being a bunch of shuffles and extracts
16863 /// to a simple store and scalar loads to extract the elements.
16864 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16865 TargetLowering::DAGCombinerInfo &DCI) {
16866 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16867 if (NewOp.getNode())
16870 SDValue InputVector = N->getOperand(0);
16872 // Detect whether we are trying to convert from mmx to i32 and the bitcast
16873 // from mmx to v2i32 has a single usage.
16874 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16875 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16876 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16877 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16878 N->getValueType(0),
16879 InputVector.getNode()->getOperand(0));
16881 // Only operate on vectors of 4 elements, where the alternative shuffling
16882 // gets to be more expensive.
16883 if (InputVector.getValueType() != MVT::v4i32)
16886 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16887 // single use which is a sign-extend or zero-extend, and all elements are
16889 SmallVector<SDNode *, 4> Uses;
16890 unsigned ExtractedElements = 0;
16891 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16892 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16893 if (UI.getUse().getResNo() != InputVector.getResNo())
16896 SDNode *Extract = *UI;
16897 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16900 if (Extract->getValueType(0) != MVT::i32)
16902 if (!Extract->hasOneUse())
16904 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16905 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16907 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16910 // Record which element was extracted.
16911 ExtractedElements |=
16912 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16914 Uses.push_back(Extract);
16917 // If not all the elements were used, this may not be worthwhile.
16918 if (ExtractedElements != 15)
16921 // Ok, we've now decided to do the transformation.
16922 SDLoc dl(InputVector);
16924 // Store the value to a temporary stack slot.
16925 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16926 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16927 MachinePointerInfo(), false, false, 0);
16929 // Replace each use (extract) with a load of the appropriate element.
16930 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16931 UE = Uses.end(); UI != UE; ++UI) {
16932 SDNode *Extract = *UI;
16934 // cOMpute the element's address.
16935 SDValue Idx = Extract->getOperand(1);
16937 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16938 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16939 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16940 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16942 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16943 StackPtr, OffsetVal);
16945 // Load the scalar.
16946 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16947 ScalarAddr, MachinePointerInfo(),
16948 false, false, false, 0);
16950 // Replace the exact with the load.
16951 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16954 // The replacement was made in place; don't return anything.
16958 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16959 static std::pair<unsigned, bool>
16960 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16961 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16962 if (!VT.isVector())
16963 return std::make_pair(0, false);
16965 bool NeedSplit = false;
16966 switch (VT.getSimpleVT().SimpleTy) {
16967 default: return std::make_pair(0, false);
16971 if (!Subtarget->hasAVX2())
16973 if (!Subtarget->hasAVX())
16974 return std::make_pair(0, false);
16979 if (!Subtarget->hasSSE2())
16980 return std::make_pair(0, false);
16983 // SSE2 has only a small subset of the operations.
16984 bool hasUnsigned = Subtarget->hasSSE41() ||
16985 (Subtarget->hasSSE2() && VT == MVT::v16i8);
16986 bool hasSigned = Subtarget->hasSSE41() ||
16987 (Subtarget->hasSSE2() && VT == MVT::v8i16);
16989 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16992 // Check for x CC y ? x : y.
16993 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16994 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16999 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17002 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17005 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17008 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17010 // Check for x CC y ? y : x -- a min/max with reversed arms.
17011 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17012 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17017 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17020 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17023 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17026 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17030 return std::make_pair(Opc, NeedSplit);
17033 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17035 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17036 TargetLowering::DAGCombinerInfo &DCI,
17037 const X86Subtarget *Subtarget) {
17039 SDValue Cond = N->getOperand(0);
17040 // Get the LHS/RHS of the select.
17041 SDValue LHS = N->getOperand(1);
17042 SDValue RHS = N->getOperand(2);
17043 EVT VT = LHS.getValueType();
17044 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17046 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17047 // instructions match the semantics of the common C idiom x<y?x:y but not
17048 // x<=y?x:y, because of how they handle negative zero (which can be
17049 // ignored in unsafe-math mode).
17050 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17051 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17052 (Subtarget->hasSSE2() ||
17053 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17054 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17056 unsigned Opcode = 0;
17057 // Check for x CC y ? x : y.
17058 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17059 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17063 // Converting this to a min would handle NaNs incorrectly, and swapping
17064 // the operands would cause it to handle comparisons between positive
17065 // and negative zero incorrectly.
17066 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17067 if (!DAG.getTarget().Options.UnsafeFPMath &&
17068 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17070 std::swap(LHS, RHS);
17072 Opcode = X86ISD::FMIN;
17075 // Converting this to a min would handle comparisons between positive
17076 // and negative zero incorrectly.
17077 if (!DAG.getTarget().Options.UnsafeFPMath &&
17078 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17080 Opcode = X86ISD::FMIN;
17083 // Converting this to a min would handle both negative zeros and NaNs
17084 // incorrectly, but we can swap the operands to fix both.
17085 std::swap(LHS, RHS);
17089 Opcode = X86ISD::FMIN;
17093 // Converting this to a max would handle comparisons between positive
17094 // and negative zero incorrectly.
17095 if (!DAG.getTarget().Options.UnsafeFPMath &&
17096 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17098 Opcode = X86ISD::FMAX;
17101 // Converting this to a max would handle NaNs incorrectly, and swapping
17102 // the operands would cause it to handle comparisons between positive
17103 // and negative zero incorrectly.
17104 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17105 if (!DAG.getTarget().Options.UnsafeFPMath &&
17106 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17108 std::swap(LHS, RHS);
17110 Opcode = X86ISD::FMAX;
17113 // Converting this to a max would handle both negative zeros and NaNs
17114 // incorrectly, but we can swap the operands to fix both.
17115 std::swap(LHS, RHS);
17119 Opcode = X86ISD::FMAX;
17122 // Check for x CC y ? y : x -- a min/max with reversed arms.
17123 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17124 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17128 // Converting this to a min would handle comparisons between positive
17129 // and negative zero incorrectly, and swapping the operands would
17130 // cause it to handle NaNs incorrectly.
17131 if (!DAG.getTarget().Options.UnsafeFPMath &&
17132 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17133 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17135 std::swap(LHS, RHS);
17137 Opcode = X86ISD::FMIN;
17140 // Converting this to a min would handle NaNs incorrectly.
17141 if (!DAG.getTarget().Options.UnsafeFPMath &&
17142 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17144 Opcode = X86ISD::FMIN;
17147 // Converting this to a min would handle both negative zeros and NaNs
17148 // incorrectly, but we can swap the operands to fix both.
17149 std::swap(LHS, RHS);
17153 Opcode = X86ISD::FMIN;
17157 // Converting this to a max would handle NaNs incorrectly.
17158 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17160 Opcode = X86ISD::FMAX;
17163 // Converting this to a max would handle comparisons between positive
17164 // and negative zero incorrectly, and swapping the operands would
17165 // cause it to handle NaNs incorrectly.
17166 if (!DAG.getTarget().Options.UnsafeFPMath &&
17167 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17168 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17170 std::swap(LHS, RHS);
17172 Opcode = X86ISD::FMAX;
17175 // Converting this to a max would handle both negative zeros and NaNs
17176 // incorrectly, but we can swap the operands to fix both.
17177 std::swap(LHS, RHS);
17181 Opcode = X86ISD::FMAX;
17187 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17190 EVT CondVT = Cond.getValueType();
17191 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17192 CondVT.getVectorElementType() == MVT::i1) {
17193 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17194 // lowering on AVX-512. In this case we convert it to
17195 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17196 // The same situation for all 128 and 256-bit vectors of i8 and i16
17197 EVT OpVT = LHS.getValueType();
17198 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17199 (OpVT.getVectorElementType() == MVT::i8 ||
17200 OpVT.getVectorElementType() == MVT::i16)) {
17201 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17202 DCI.AddToWorklist(Cond.getNode());
17203 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17206 // If this is a select between two integer constants, try to do some
17208 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17209 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17210 // Don't do this for crazy integer types.
17211 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17212 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17213 // so that TrueC (the true value) is larger than FalseC.
17214 bool NeedsCondInvert = false;
17216 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17217 // Efficiently invertible.
17218 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17219 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17220 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17221 NeedsCondInvert = true;
17222 std::swap(TrueC, FalseC);
17225 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17226 if (FalseC->getAPIntValue() == 0 &&
17227 TrueC->getAPIntValue().isPowerOf2()) {
17228 if (NeedsCondInvert) // Invert the condition if needed.
17229 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17230 DAG.getConstant(1, Cond.getValueType()));
17232 // Zero extend the condition if needed.
17233 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17235 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17236 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17237 DAG.getConstant(ShAmt, MVT::i8));
17240 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17241 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17242 if (NeedsCondInvert) // Invert the condition if needed.
17243 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17244 DAG.getConstant(1, Cond.getValueType()));
17246 // Zero extend the condition if needed.
17247 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17248 FalseC->getValueType(0), Cond);
17249 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17250 SDValue(FalseC, 0));
17253 // Optimize cases that will turn into an LEA instruction. This requires
17254 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17255 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17256 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17257 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17259 bool isFastMultiplier = false;
17261 switch ((unsigned char)Diff) {
17263 case 1: // result = add base, cond
17264 case 2: // result = lea base( , cond*2)
17265 case 3: // result = lea base(cond, cond*2)
17266 case 4: // result = lea base( , cond*4)
17267 case 5: // result = lea base(cond, cond*4)
17268 case 8: // result = lea base( , cond*8)
17269 case 9: // result = lea base(cond, cond*8)
17270 isFastMultiplier = true;
17275 if (isFastMultiplier) {
17276 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17277 if (NeedsCondInvert) // Invert the condition if needed.
17278 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17279 DAG.getConstant(1, Cond.getValueType()));
17281 // Zero extend the condition if needed.
17282 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17284 // Scale the condition by the difference.
17286 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17287 DAG.getConstant(Diff, Cond.getValueType()));
17289 // Add the base if non-zero.
17290 if (FalseC->getAPIntValue() != 0)
17291 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17292 SDValue(FalseC, 0));
17299 // Canonicalize max and min:
17300 // (x > y) ? x : y -> (x >= y) ? x : y
17301 // (x < y) ? x : y -> (x <= y) ? x : y
17302 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17303 // the need for an extra compare
17304 // against zero. e.g.
17305 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17307 // testl %edi, %edi
17309 // cmovgl %edi, %eax
17313 // cmovsl %eax, %edi
17314 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17315 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17316 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17317 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17322 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17323 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17324 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17325 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17330 // Early exit check
17331 if (!TLI.isTypeLegal(VT))
17334 // Match VSELECTs into subs with unsigned saturation.
17335 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17336 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17337 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17338 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17339 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17341 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17342 // left side invert the predicate to simplify logic below.
17344 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17346 CC = ISD::getSetCCInverse(CC, true);
17347 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17351 if (Other.getNode() && Other->getNumOperands() == 2 &&
17352 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17353 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17354 SDValue CondRHS = Cond->getOperand(1);
17356 // Look for a general sub with unsigned saturation first.
17357 // x >= y ? x-y : 0 --> subus x, y
17358 // x > y ? x-y : 0 --> subus x, y
17359 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17360 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17361 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17363 // If the RHS is a constant we have to reverse the const canonicalization.
17364 // x > C-1 ? x+-C : 0 --> subus x, C
17365 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17366 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17367 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17368 if (CondRHS.getConstantOperandVal(0) == -A-1)
17369 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17370 DAG.getConstant(-A, VT));
17373 // Another special case: If C was a sign bit, the sub has been
17374 // canonicalized into a xor.
17375 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17376 // it's safe to decanonicalize the xor?
17377 // x s< 0 ? x^C : 0 --> subus x, C
17378 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17379 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17380 isSplatVector(OpRHS.getNode())) {
17381 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17383 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17388 // Try to match a min/max vector operation.
17389 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17390 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17391 unsigned Opc = ret.first;
17392 bool NeedSplit = ret.second;
17394 if (Opc && NeedSplit) {
17395 unsigned NumElems = VT.getVectorNumElements();
17396 // Extract the LHS vectors
17397 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17398 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17400 // Extract the RHS vectors
17401 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17402 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17404 // Create min/max for each subvector
17405 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17406 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17408 // Merge the result
17409 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17411 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17414 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17415 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17416 // Check if SETCC has already been promoted
17417 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17418 // Check that condition value type matches vselect operand type
17421 assert(Cond.getValueType().isVector() &&
17422 "vector select expects a vector selector!");
17424 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17425 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17427 if (!TValIsAllOnes && !FValIsAllZeros) {
17428 // Try invert the condition if true value is not all 1s and false value
17430 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17431 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17433 if (TValIsAllZeros || FValIsAllOnes) {
17434 SDValue CC = Cond.getOperand(2);
17435 ISD::CondCode NewCC =
17436 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17437 Cond.getOperand(0).getValueType().isInteger());
17438 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17439 std::swap(LHS, RHS);
17440 TValIsAllOnes = FValIsAllOnes;
17441 FValIsAllZeros = TValIsAllZeros;
17445 if (TValIsAllOnes || FValIsAllZeros) {
17448 if (TValIsAllOnes && FValIsAllZeros)
17450 else if (TValIsAllOnes)
17451 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17452 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17453 else if (FValIsAllZeros)
17454 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17455 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17457 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17461 // Try to fold this VSELECT into a MOVSS/MOVSD
17462 if (N->getOpcode() == ISD::VSELECT &&
17463 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17464 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17465 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17466 bool CanFold = false;
17467 unsigned NumElems = Cond.getNumOperands();
17471 if (isZero(Cond.getOperand(0))) {
17474 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17475 // fold (vselect <0,-1> -> (movsd A, B)
17476 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17477 CanFold = isAllOnes(Cond.getOperand(i));
17478 } else if (isAllOnes(Cond.getOperand(0))) {
17482 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17483 // fold (vselect <-1,0> -> (movsd B, A)
17484 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17485 CanFold = isZero(Cond.getOperand(i));
17489 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17490 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17491 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17494 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17495 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17496 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17497 // (v2i64 (bitcast B)))))
17499 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17500 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17501 // (v2f64 (bitcast B)))))
17503 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17504 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17505 // (v2i64 (bitcast A)))))
17507 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17508 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17509 // (v2f64 (bitcast A)))))
17511 CanFold = (isZero(Cond.getOperand(0)) &&
17512 isZero(Cond.getOperand(1)) &&
17513 isAllOnes(Cond.getOperand(2)) &&
17514 isAllOnes(Cond.getOperand(3)));
17516 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17517 isAllOnes(Cond.getOperand(1)) &&
17518 isZero(Cond.getOperand(2)) &&
17519 isZero(Cond.getOperand(3))) {
17521 std::swap(LHS, RHS);
17525 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17526 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17527 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17528 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17530 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17536 // If we know that this node is legal then we know that it is going to be
17537 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17538 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17539 // to simplify previous instructions.
17540 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17541 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17542 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17544 // Don't optimize vector selects that map to mask-registers.
17548 // Check all uses of that condition operand to check whether it will be
17549 // consumed by non-BLEND instructions, which may depend on all bits are set
17551 for (SDNode::use_iterator I = Cond->use_begin(),
17552 E = Cond->use_end(); I != E; ++I)
17553 if (I->getOpcode() != ISD::VSELECT)
17554 // TODO: Add other opcodes eventually lowered into BLEND.
17557 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17558 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17560 APInt KnownZero, KnownOne;
17561 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17562 DCI.isBeforeLegalizeOps());
17563 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17564 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17565 DCI.CommitTargetLoweringOpt(TLO);
17571 // Check whether a boolean test is testing a boolean value generated by
17572 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17575 // Simplify the following patterns:
17576 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17577 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17578 // to (Op EFLAGS Cond)
17580 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17581 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17582 // to (Op EFLAGS !Cond)
17584 // where Op could be BRCOND or CMOV.
17586 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17587 // Quit if not CMP and SUB with its value result used.
17588 if (Cmp.getOpcode() != X86ISD::CMP &&
17589 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17592 // Quit if not used as a boolean value.
17593 if (CC != X86::COND_E && CC != X86::COND_NE)
17596 // Check CMP operands. One of them should be 0 or 1 and the other should be
17597 // an SetCC or extended from it.
17598 SDValue Op1 = Cmp.getOperand(0);
17599 SDValue Op2 = Cmp.getOperand(1);
17602 const ConstantSDNode* C = 0;
17603 bool needOppositeCond = (CC == X86::COND_E);
17604 bool checkAgainstTrue = false; // Is it a comparison against 1?
17606 if ((C = dyn_cast<ConstantSDNode>(Op1)))
17608 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17610 else // Quit if all operands are not constants.
17613 if (C->getZExtValue() == 1) {
17614 needOppositeCond = !needOppositeCond;
17615 checkAgainstTrue = true;
17616 } else if (C->getZExtValue() != 0)
17617 // Quit if the constant is neither 0 or 1.
17620 bool truncatedToBoolWithAnd = false;
17621 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17622 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17623 SetCC.getOpcode() == ISD::TRUNCATE ||
17624 SetCC.getOpcode() == ISD::AND) {
17625 if (SetCC.getOpcode() == ISD::AND) {
17627 ConstantSDNode *CS;
17628 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17629 CS->getZExtValue() == 1)
17631 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17632 CS->getZExtValue() == 1)
17636 SetCC = SetCC.getOperand(OpIdx);
17637 truncatedToBoolWithAnd = true;
17639 SetCC = SetCC.getOperand(0);
17642 switch (SetCC.getOpcode()) {
17643 case X86ISD::SETCC_CARRY:
17644 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17645 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17646 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17647 // truncated to i1 using 'and'.
17648 if (checkAgainstTrue && !truncatedToBoolWithAnd)
17650 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17651 "Invalid use of SETCC_CARRY!");
17653 case X86ISD::SETCC:
17654 // Set the condition code or opposite one if necessary.
17655 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17656 if (needOppositeCond)
17657 CC = X86::GetOppositeBranchCondition(CC);
17658 return SetCC.getOperand(1);
17659 case X86ISD::CMOV: {
17660 // Check whether false/true value has canonical one, i.e. 0 or 1.
17661 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17662 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17663 // Quit if true value is not a constant.
17666 // Quit if false value is not a constant.
17668 SDValue Op = SetCC.getOperand(0);
17669 // Skip 'zext' or 'trunc' node.
17670 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17671 Op.getOpcode() == ISD::TRUNCATE)
17672 Op = Op.getOperand(0);
17673 // A special case for rdrand/rdseed, where 0 is set if false cond is
17675 if ((Op.getOpcode() != X86ISD::RDRAND &&
17676 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17679 // Quit if false value is not the constant 0 or 1.
17680 bool FValIsFalse = true;
17681 if (FVal && FVal->getZExtValue() != 0) {
17682 if (FVal->getZExtValue() != 1)
17684 // If FVal is 1, opposite cond is needed.
17685 needOppositeCond = !needOppositeCond;
17686 FValIsFalse = false;
17688 // Quit if TVal is not the constant opposite of FVal.
17689 if (FValIsFalse && TVal->getZExtValue() != 1)
17691 if (!FValIsFalse && TVal->getZExtValue() != 0)
17693 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17694 if (needOppositeCond)
17695 CC = X86::GetOppositeBranchCondition(CC);
17696 return SetCC.getOperand(3);
17703 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17704 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17705 TargetLowering::DAGCombinerInfo &DCI,
17706 const X86Subtarget *Subtarget) {
17709 // If the flag operand isn't dead, don't touch this CMOV.
17710 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17713 SDValue FalseOp = N->getOperand(0);
17714 SDValue TrueOp = N->getOperand(1);
17715 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17716 SDValue Cond = N->getOperand(3);
17718 if (CC == X86::COND_E || CC == X86::COND_NE) {
17719 switch (Cond.getOpcode()) {
17723 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17724 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17725 return (CC == X86::COND_E) ? FalseOp : TrueOp;
17731 Flags = checkBoolTestSetCCCombine(Cond, CC);
17732 if (Flags.getNode() &&
17733 // Extra check as FCMOV only supports a subset of X86 cond.
17734 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17735 SDValue Ops[] = { FalseOp, TrueOp,
17736 DAG.getConstant(CC, MVT::i8), Flags };
17737 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17738 Ops, array_lengthof(Ops));
17741 // If this is a select between two integer constants, try to do some
17742 // optimizations. Note that the operands are ordered the opposite of SELECT
17744 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17745 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17746 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17747 // larger than FalseC (the false value).
17748 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17749 CC = X86::GetOppositeBranchCondition(CC);
17750 std::swap(TrueC, FalseC);
17751 std::swap(TrueOp, FalseOp);
17754 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
17755 // This is efficient for any integer data type (including i8/i16) and
17757 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17758 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17759 DAG.getConstant(CC, MVT::i8), Cond);
17761 // Zero extend the condition if needed.
17762 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17764 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17765 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17766 DAG.getConstant(ShAmt, MVT::i8));
17767 if (N->getNumValues() == 2) // Dead flag value?
17768 return DCI.CombineTo(N, Cond, SDValue());
17772 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
17773 // for any integer data type, including i8/i16.
17774 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17775 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17776 DAG.getConstant(CC, MVT::i8), Cond);
17778 // Zero extend the condition if needed.
17779 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17780 FalseC->getValueType(0), Cond);
17781 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17782 SDValue(FalseC, 0));
17784 if (N->getNumValues() == 2) // Dead flag value?
17785 return DCI.CombineTo(N, Cond, SDValue());
17789 // Optimize cases that will turn into an LEA instruction. This requires
17790 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17791 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17792 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17793 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17795 bool isFastMultiplier = false;
17797 switch ((unsigned char)Diff) {
17799 case 1: // result = add base, cond
17800 case 2: // result = lea base( , cond*2)
17801 case 3: // result = lea base(cond, cond*2)
17802 case 4: // result = lea base( , cond*4)
17803 case 5: // result = lea base(cond, cond*4)
17804 case 8: // result = lea base( , cond*8)
17805 case 9: // result = lea base(cond, cond*8)
17806 isFastMultiplier = true;
17811 if (isFastMultiplier) {
17812 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17813 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17814 DAG.getConstant(CC, MVT::i8), Cond);
17815 // Zero extend the condition if needed.
17816 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17818 // Scale the condition by the difference.
17820 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17821 DAG.getConstant(Diff, Cond.getValueType()));
17823 // Add the base if non-zero.
17824 if (FalseC->getAPIntValue() != 0)
17825 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17826 SDValue(FalseC, 0));
17827 if (N->getNumValues() == 2) // Dead flag value?
17828 return DCI.CombineTo(N, Cond, SDValue());
17835 // Handle these cases:
17836 // (select (x != c), e, c) -> select (x != c), e, x),
17837 // (select (x == c), c, e) -> select (x == c), x, e)
17838 // where the c is an integer constant, and the "select" is the combination
17839 // of CMOV and CMP.
17841 // The rationale for this change is that the conditional-move from a constant
17842 // needs two instructions, however, conditional-move from a register needs
17843 // only one instruction.
17845 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17846 // some instruction-combining opportunities. This opt needs to be
17847 // postponed as late as possible.
17849 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17850 // the DCI.xxxx conditions are provided to postpone the optimization as
17851 // late as possible.
17853 ConstantSDNode *CmpAgainst = 0;
17854 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17855 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17856 !isa<ConstantSDNode>(Cond.getOperand(0))) {
17858 if (CC == X86::COND_NE &&
17859 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17860 CC = X86::GetOppositeBranchCondition(CC);
17861 std::swap(TrueOp, FalseOp);
17864 if (CC == X86::COND_E &&
17865 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17866 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17867 DAG.getConstant(CC, MVT::i8), Cond };
17868 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17869 array_lengthof(Ops));
17877 /// PerformMulCombine - Optimize a single multiply with constant into two
17878 /// in order to implement it with two cheaper instructions, e.g.
17879 /// LEA + SHL, LEA + LEA.
17880 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17881 TargetLowering::DAGCombinerInfo &DCI) {
17882 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17885 EVT VT = N->getValueType(0);
17886 if (VT != MVT::i64)
17889 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17892 uint64_t MulAmt = C->getZExtValue();
17893 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17896 uint64_t MulAmt1 = 0;
17897 uint64_t MulAmt2 = 0;
17898 if ((MulAmt % 9) == 0) {
17900 MulAmt2 = MulAmt / 9;
17901 } else if ((MulAmt % 5) == 0) {
17903 MulAmt2 = MulAmt / 5;
17904 } else if ((MulAmt % 3) == 0) {
17906 MulAmt2 = MulAmt / 3;
17909 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17912 if (isPowerOf2_64(MulAmt2) &&
17913 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17914 // If second multiplifer is pow2, issue it first. We want the multiply by
17915 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17917 std::swap(MulAmt1, MulAmt2);
17920 if (isPowerOf2_64(MulAmt1))
17921 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17922 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17924 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17925 DAG.getConstant(MulAmt1, VT));
17927 if (isPowerOf2_64(MulAmt2))
17928 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17929 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17931 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17932 DAG.getConstant(MulAmt2, VT));
17934 // Do not add new nodes to DAG combiner worklist.
17935 DCI.CombineTo(N, NewMul, false);
17940 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17941 SDValue N0 = N->getOperand(0);
17942 SDValue N1 = N->getOperand(1);
17943 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17944 EVT VT = N0.getValueType();
17946 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17947 // since the result of setcc_c is all zero's or all ones.
17948 if (VT.isInteger() && !VT.isVector() &&
17949 N1C && N0.getOpcode() == ISD::AND &&
17950 N0.getOperand(1).getOpcode() == ISD::Constant) {
17951 SDValue N00 = N0.getOperand(0);
17952 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17953 ((N00.getOpcode() == ISD::ANY_EXTEND ||
17954 N00.getOpcode() == ISD::ZERO_EXTEND) &&
17955 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17956 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17957 APInt ShAmt = N1C->getAPIntValue();
17958 Mask = Mask.shl(ShAmt);
17960 return DAG.getNode(ISD::AND, SDLoc(N), VT,
17961 N00, DAG.getConstant(Mask, VT));
17965 // Hardware support for vector shifts is sparse which makes us scalarize the
17966 // vector operations in many cases. Also, on sandybridge ADD is faster than
17968 // (shl V, 1) -> add V,V
17969 if (isSplatVector(N1.getNode())) {
17970 assert(N0.getValueType().isVector() && "Invalid vector shift type");
17971 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17972 // We shift all of the values by one. In many cases we do not have
17973 // hardware support for this operation. This is better expressed as an ADD
17975 if (N1C && (1 == N1C->getZExtValue())) {
17976 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17983 /// \brief Returns a vector of 0s if the node in input is a vector logical
17984 /// shift by a constant amount which is known to be bigger than or equal
17985 /// to the vector element size in bits.
17986 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17987 const X86Subtarget *Subtarget) {
17988 EVT VT = N->getValueType(0);
17990 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17991 (!Subtarget->hasInt256() ||
17992 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17995 SDValue Amt = N->getOperand(1);
17997 if (isSplatVector(Amt.getNode())) {
17998 SDValue SclrAmt = Amt->getOperand(0);
17999 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18000 APInt ShiftAmt = C->getAPIntValue();
18001 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18003 // SSE2/AVX2 logical shifts always return a vector of 0s
18004 // if the shift amount is bigger than or equal to
18005 // the element size. The constant shift amount will be
18006 // encoded as a 8-bit immediate.
18007 if (ShiftAmt.trunc(8).uge(MaxAmount))
18008 return getZeroVector(VT, Subtarget, DAG, DL);
18015 /// PerformShiftCombine - Combine shifts.
18016 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18017 TargetLowering::DAGCombinerInfo &DCI,
18018 const X86Subtarget *Subtarget) {
18019 if (N->getOpcode() == ISD::SHL) {
18020 SDValue V = PerformSHLCombine(N, DAG);
18021 if (V.getNode()) return V;
18024 if (N->getOpcode() != ISD::SRA) {
18025 // Try to fold this logical shift into a zero vector.
18026 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18027 if (V.getNode()) return V;
18033 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18034 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18035 // and friends. Likewise for OR -> CMPNEQSS.
18036 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18037 TargetLowering::DAGCombinerInfo &DCI,
18038 const X86Subtarget *Subtarget) {
18041 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18042 // we're requiring SSE2 for both.
18043 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18044 SDValue N0 = N->getOperand(0);
18045 SDValue N1 = N->getOperand(1);
18046 SDValue CMP0 = N0->getOperand(1);
18047 SDValue CMP1 = N1->getOperand(1);
18050 // The SETCCs should both refer to the same CMP.
18051 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18054 SDValue CMP00 = CMP0->getOperand(0);
18055 SDValue CMP01 = CMP0->getOperand(1);
18056 EVT VT = CMP00.getValueType();
18058 if (VT == MVT::f32 || VT == MVT::f64) {
18059 bool ExpectingFlags = false;
18060 // Check for any users that want flags:
18061 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18062 !ExpectingFlags && UI != UE; ++UI)
18063 switch (UI->getOpcode()) {
18068 ExpectingFlags = true;
18070 case ISD::CopyToReg:
18071 case ISD::SIGN_EXTEND:
18072 case ISD::ZERO_EXTEND:
18073 case ISD::ANY_EXTEND:
18077 if (!ExpectingFlags) {
18078 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18079 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18081 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18082 X86::CondCode tmp = cc0;
18087 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18088 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18089 // FIXME: need symbolic constants for these magic numbers.
18090 // See X86ATTInstPrinter.cpp:printSSECC().
18091 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18092 if (Subtarget->hasAVX512()) {
18093 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18094 CMP01, DAG.getConstant(x86cc, MVT::i8));
18095 if (N->getValueType(0) != MVT::i1)
18096 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18100 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18101 CMP00.getValueType(), CMP00, CMP01,
18102 DAG.getConstant(x86cc, MVT::i8));
18104 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18105 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18107 if (is64BitFP && !Subtarget->is64Bit()) {
18108 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18109 // 64-bit integer, since that's not a legal type. Since
18110 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18111 // bits, but can do this little dance to extract the lowest 32 bits
18112 // and work with those going forward.
18113 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18115 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18117 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18118 Vector32, DAG.getIntPtrConstant(0));
18122 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18123 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18124 DAG.getConstant(1, IntVT));
18125 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18126 return OneBitOfTruth;
18134 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18135 /// so it can be folded inside ANDNP.
18136 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18137 EVT VT = N->getValueType(0);
18139 // Match direct AllOnes for 128 and 256-bit vectors
18140 if (ISD::isBuildVectorAllOnes(N))
18143 // Look through a bit convert.
18144 if (N->getOpcode() == ISD::BITCAST)
18145 N = N->getOperand(0).getNode();
18147 // Sometimes the operand may come from a insert_subvector building a 256-bit
18149 if (VT.is256BitVector() &&
18150 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18151 SDValue V1 = N->getOperand(0);
18152 SDValue V2 = N->getOperand(1);
18154 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18155 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18156 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18157 ISD::isBuildVectorAllOnes(V2.getNode()))
18164 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18165 // register. In most cases we actually compare or select YMM-sized registers
18166 // and mixing the two types creates horrible code. This method optimizes
18167 // some of the transition sequences.
18168 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18169 TargetLowering::DAGCombinerInfo &DCI,
18170 const X86Subtarget *Subtarget) {
18171 EVT VT = N->getValueType(0);
18172 if (!VT.is256BitVector())
18175 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18176 N->getOpcode() == ISD::ZERO_EXTEND ||
18177 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18179 SDValue Narrow = N->getOperand(0);
18180 EVT NarrowVT = Narrow->getValueType(0);
18181 if (!NarrowVT.is128BitVector())
18184 if (Narrow->getOpcode() != ISD::XOR &&
18185 Narrow->getOpcode() != ISD::AND &&
18186 Narrow->getOpcode() != ISD::OR)
18189 SDValue N0 = Narrow->getOperand(0);
18190 SDValue N1 = Narrow->getOperand(1);
18193 // The Left side has to be a trunc.
18194 if (N0.getOpcode() != ISD::TRUNCATE)
18197 // The type of the truncated inputs.
18198 EVT WideVT = N0->getOperand(0)->getValueType(0);
18202 // The right side has to be a 'trunc' or a constant vector.
18203 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18204 bool RHSConst = (isSplatVector(N1.getNode()) &&
18205 isa<ConstantSDNode>(N1->getOperand(0)));
18206 if (!RHSTrunc && !RHSConst)
18209 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18211 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18214 // Set N0 and N1 to hold the inputs to the new wide operation.
18215 N0 = N0->getOperand(0);
18217 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18218 N1->getOperand(0));
18219 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18220 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18221 } else if (RHSTrunc) {
18222 N1 = N1->getOperand(0);
18225 // Generate the wide operation.
18226 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18227 unsigned Opcode = N->getOpcode();
18229 case ISD::ANY_EXTEND:
18231 case ISD::ZERO_EXTEND: {
18232 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18233 APInt Mask = APInt::getAllOnesValue(InBits);
18234 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18235 return DAG.getNode(ISD::AND, DL, VT,
18236 Op, DAG.getConstant(Mask, VT));
18238 case ISD::SIGN_EXTEND:
18239 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18240 Op, DAG.getValueType(NarrowVT));
18242 llvm_unreachable("Unexpected opcode");
18246 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18247 TargetLowering::DAGCombinerInfo &DCI,
18248 const X86Subtarget *Subtarget) {
18249 EVT VT = N->getValueType(0);
18250 if (DCI.isBeforeLegalizeOps())
18253 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18257 // Create BEXTR and BZHI instructions
18258 // BZHI is X & ((1 << Y) - 1)
18259 // BEXTR is ((X >> imm) & (2**size-1))
18260 if (VT == MVT::i32 || VT == MVT::i64) {
18261 SDValue N0 = N->getOperand(0);
18262 SDValue N1 = N->getOperand(1);
18265 if (Subtarget->hasBMI2()) {
18266 // Check for (and (add (shl 1, Y), -1), X)
18267 if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
18268 SDValue N00 = N0.getOperand(0);
18269 if (N00.getOpcode() == ISD::SHL) {
18270 SDValue N001 = N00.getOperand(1);
18271 assert(N001.getValueType() == MVT::i8 && "unexpected type");
18272 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
18273 if (C && C->getZExtValue() == 1)
18274 return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
18278 // Check for (and X, (add (shl 1, Y), -1))
18279 if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
18280 SDValue N10 = N1.getOperand(0);
18281 if (N10.getOpcode() == ISD::SHL) {
18282 SDValue N101 = N10.getOperand(1);
18283 assert(N101.getValueType() == MVT::i8 && "unexpected type");
18284 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
18285 if (C && C->getZExtValue() == 1)
18286 return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
18291 // Check for BEXTR.
18292 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18293 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18294 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18295 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18296 if (MaskNode && ShiftNode) {
18297 uint64_t Mask = MaskNode->getZExtValue();
18298 uint64_t Shift = ShiftNode->getZExtValue();
18299 if (isMask_64(Mask)) {
18300 uint64_t MaskSize = CountPopulation_64(Mask);
18301 if (Shift + MaskSize <= VT.getSizeInBits())
18302 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18303 DAG.getConstant(Shift | (MaskSize << 8), VT));
18311 // Want to form ANDNP nodes:
18312 // 1) In the hopes of then easily combining them with OR and AND nodes
18313 // to form PBLEND/PSIGN.
18314 // 2) To match ANDN packed intrinsics
18315 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18318 SDValue N0 = N->getOperand(0);
18319 SDValue N1 = N->getOperand(1);
18322 // Check LHS for vnot
18323 if (N0.getOpcode() == ISD::XOR &&
18324 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18325 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18326 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18328 // Check RHS for vnot
18329 if (N1.getOpcode() == ISD::XOR &&
18330 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18331 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18332 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18337 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18338 TargetLowering::DAGCombinerInfo &DCI,
18339 const X86Subtarget *Subtarget) {
18340 if (DCI.isBeforeLegalizeOps())
18343 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18347 SDValue N0 = N->getOperand(0);
18348 SDValue N1 = N->getOperand(1);
18349 EVT VT = N->getValueType(0);
18351 // look for psign/blend
18352 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18353 if (!Subtarget->hasSSSE3() ||
18354 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18357 // Canonicalize pandn to RHS
18358 if (N0.getOpcode() == X86ISD::ANDNP)
18360 // or (and (m, y), (pandn m, x))
18361 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18362 SDValue Mask = N1.getOperand(0);
18363 SDValue X = N1.getOperand(1);
18365 if (N0.getOperand(0) == Mask)
18366 Y = N0.getOperand(1);
18367 if (N0.getOperand(1) == Mask)
18368 Y = N0.getOperand(0);
18370 // Check to see if the mask appeared in both the AND and ANDNP and
18374 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18375 // Look through mask bitcast.
18376 if (Mask.getOpcode() == ISD::BITCAST)
18377 Mask = Mask.getOperand(0);
18378 if (X.getOpcode() == ISD::BITCAST)
18379 X = X.getOperand(0);
18380 if (Y.getOpcode() == ISD::BITCAST)
18381 Y = Y.getOperand(0);
18383 EVT MaskVT = Mask.getValueType();
18385 // Validate that the Mask operand is a vector sra node.
18386 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18387 // there is no psrai.b
18388 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18389 unsigned SraAmt = ~0;
18390 if (Mask.getOpcode() == ISD::SRA) {
18391 SDValue Amt = Mask.getOperand(1);
18392 if (isSplatVector(Amt.getNode())) {
18393 SDValue SclrAmt = Amt->getOperand(0);
18394 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18395 SraAmt = C->getZExtValue();
18397 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18398 SDValue SraC = Mask.getOperand(1);
18399 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18401 if ((SraAmt + 1) != EltBits)
18406 // Now we know we at least have a plendvb with the mask val. See if
18407 // we can form a psignb/w/d.
18408 // psign = x.type == y.type == mask.type && y = sub(0, x);
18409 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18410 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18411 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18412 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18413 "Unsupported VT for PSIGN");
18414 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18415 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18417 // PBLENDVB only available on SSE 4.1
18418 if (!Subtarget->hasSSE41())
18421 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18423 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18424 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18425 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18426 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18427 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18431 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18434 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18435 MachineFunction &MF = DAG.getMachineFunction();
18436 bool OptForSize = MF.getFunction()->getAttributes().
18437 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18439 // SHLD/SHRD instructions have lower register pressure, but on some
18440 // platforms they have higher latency than the equivalent
18441 // series of shifts/or that would otherwise be generated.
18442 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18443 // have higher latencies and we are not optimizing for size.
18444 if (!OptForSize && Subtarget->isSHLDSlow())
18447 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18449 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18451 if (!N0.hasOneUse() || !N1.hasOneUse())
18454 SDValue ShAmt0 = N0.getOperand(1);
18455 if (ShAmt0.getValueType() != MVT::i8)
18457 SDValue ShAmt1 = N1.getOperand(1);
18458 if (ShAmt1.getValueType() != MVT::i8)
18460 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18461 ShAmt0 = ShAmt0.getOperand(0);
18462 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18463 ShAmt1 = ShAmt1.getOperand(0);
18466 unsigned Opc = X86ISD::SHLD;
18467 SDValue Op0 = N0.getOperand(0);
18468 SDValue Op1 = N1.getOperand(0);
18469 if (ShAmt0.getOpcode() == ISD::SUB) {
18470 Opc = X86ISD::SHRD;
18471 std::swap(Op0, Op1);
18472 std::swap(ShAmt0, ShAmt1);
18475 unsigned Bits = VT.getSizeInBits();
18476 if (ShAmt1.getOpcode() == ISD::SUB) {
18477 SDValue Sum = ShAmt1.getOperand(0);
18478 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18479 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18480 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18481 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18482 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18483 return DAG.getNode(Opc, DL, VT,
18485 DAG.getNode(ISD::TRUNCATE, DL,
18488 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18489 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18491 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18492 return DAG.getNode(Opc, DL, VT,
18493 N0.getOperand(0), N1.getOperand(0),
18494 DAG.getNode(ISD::TRUNCATE, DL,
18501 // Generate NEG and CMOV for integer abs.
18502 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18503 EVT VT = N->getValueType(0);
18505 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18506 // 8-bit integer abs to NEG and CMOV.
18507 if (VT.isInteger() && VT.getSizeInBits() == 8)
18510 SDValue N0 = N->getOperand(0);
18511 SDValue N1 = N->getOperand(1);
18514 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18515 // and change it to SUB and CMOV.
18516 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18517 N0.getOpcode() == ISD::ADD &&
18518 N0.getOperand(1) == N1 &&
18519 N1.getOpcode() == ISD::SRA &&
18520 N1.getOperand(0) == N0.getOperand(0))
18521 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18522 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18523 // Generate SUB & CMOV.
18524 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18525 DAG.getConstant(0, VT), N0.getOperand(0));
18527 SDValue Ops[] = { N0.getOperand(0), Neg,
18528 DAG.getConstant(X86::COND_GE, MVT::i8),
18529 SDValue(Neg.getNode(), 1) };
18530 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18531 Ops, array_lengthof(Ops));
18536 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18537 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18538 TargetLowering::DAGCombinerInfo &DCI,
18539 const X86Subtarget *Subtarget) {
18540 if (DCI.isBeforeLegalizeOps())
18543 if (Subtarget->hasCMov()) {
18544 SDValue RV = performIntegerAbsCombine(N, DAG);
18552 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18553 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18554 TargetLowering::DAGCombinerInfo &DCI,
18555 const X86Subtarget *Subtarget) {
18556 LoadSDNode *Ld = cast<LoadSDNode>(N);
18557 EVT RegVT = Ld->getValueType(0);
18558 EVT MemVT = Ld->getMemoryVT();
18560 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18561 unsigned RegSz = RegVT.getSizeInBits();
18563 // On Sandybridge unaligned 256bit loads are inefficient.
18564 ISD::LoadExtType Ext = Ld->getExtensionType();
18565 unsigned Alignment = Ld->getAlignment();
18566 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18567 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18568 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18569 unsigned NumElems = RegVT.getVectorNumElements();
18573 SDValue Ptr = Ld->getBasePtr();
18574 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18576 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18578 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18579 Ld->getPointerInfo(), Ld->isVolatile(),
18580 Ld->isNonTemporal(), Ld->isInvariant(),
18582 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18583 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18584 Ld->getPointerInfo(), Ld->isVolatile(),
18585 Ld->isNonTemporal(), Ld->isInvariant(),
18586 std::min(16U, Alignment));
18587 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18589 Load2.getValue(1));
18591 SDValue NewVec = DAG.getUNDEF(RegVT);
18592 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18593 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18594 return DCI.CombineTo(N, NewVec, TF, true);
18597 // If this is a vector EXT Load then attempt to optimize it using a
18598 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18599 // expansion is still better than scalar code.
18600 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18601 // emit a shuffle and a arithmetic shift.
18602 // TODO: It is possible to support ZExt by zeroing the undef values
18603 // during the shuffle phase or after the shuffle.
18604 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18605 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18606 assert(MemVT != RegVT && "Cannot extend to the same type");
18607 assert(MemVT.isVector() && "Must load a vector from memory");
18609 unsigned NumElems = RegVT.getVectorNumElements();
18610 unsigned MemSz = MemVT.getSizeInBits();
18611 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18613 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18616 // All sizes must be a power of two.
18617 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18620 // Attempt to load the original value using scalar loads.
18621 // Find the largest scalar type that divides the total loaded size.
18622 MVT SclrLoadTy = MVT::i8;
18623 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18624 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18625 MVT Tp = (MVT::SimpleValueType)tp;
18626 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18631 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18632 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18634 SclrLoadTy = MVT::f64;
18636 // Calculate the number of scalar loads that we need to perform
18637 // in order to load our vector from memory.
18638 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18639 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18642 unsigned loadRegZize = RegSz;
18643 if (Ext == ISD::SEXTLOAD && RegSz == 256)
18646 // Represent our vector as a sequence of elements which are the
18647 // largest scalar that we can load.
18648 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18649 loadRegZize/SclrLoadTy.getSizeInBits());
18651 // Represent the data using the same element type that is stored in
18652 // memory. In practice, we ''widen'' MemVT.
18654 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18655 loadRegZize/MemVT.getScalarType().getSizeInBits());
18657 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18658 "Invalid vector type");
18660 // We can't shuffle using an illegal type.
18661 if (!TLI.isTypeLegal(WideVecVT))
18664 SmallVector<SDValue, 8> Chains;
18665 SDValue Ptr = Ld->getBasePtr();
18666 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18667 TLI.getPointerTy());
18668 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18670 for (unsigned i = 0; i < NumLoads; ++i) {
18671 // Perform a single load.
18672 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18673 Ptr, Ld->getPointerInfo(),
18674 Ld->isVolatile(), Ld->isNonTemporal(),
18675 Ld->isInvariant(), Ld->getAlignment());
18676 Chains.push_back(ScalarLoad.getValue(1));
18677 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18678 // another round of DAGCombining.
18680 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18682 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18683 ScalarLoad, DAG.getIntPtrConstant(i));
18685 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18688 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18691 // Bitcast the loaded value to a vector of the original element type, in
18692 // the size of the target vector type.
18693 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18694 unsigned SizeRatio = RegSz/MemSz;
18696 if (Ext == ISD::SEXTLOAD) {
18697 // If we have SSE4.1 we can directly emit a VSEXT node.
18698 if (Subtarget->hasSSE41()) {
18699 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18700 return DCI.CombineTo(N, Sext, TF, true);
18703 // Otherwise we'll shuffle the small elements in the high bits of the
18704 // larger type and perform an arithmetic shift. If the shift is not legal
18705 // it's better to scalarize.
18706 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18709 // Redistribute the loaded elements into the different locations.
18710 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18711 for (unsigned i = 0; i != NumElems; ++i)
18712 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18714 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18715 DAG.getUNDEF(WideVecVT),
18718 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18720 // Build the arithmetic shift.
18721 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18722 MemVT.getVectorElementType().getSizeInBits();
18723 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18724 DAG.getConstant(Amt, RegVT));
18726 return DCI.CombineTo(N, Shuff, TF, true);
18729 // Redistribute the loaded elements into the different locations.
18730 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18731 for (unsigned i = 0; i != NumElems; ++i)
18732 ShuffleVec[i*SizeRatio] = i;
18734 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18735 DAG.getUNDEF(WideVecVT),
18738 // Bitcast to the requested type.
18739 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18740 // Replace the original load with the new sequence
18741 // and return the new chain.
18742 return DCI.CombineTo(N, Shuff, TF, true);
18748 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18749 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18750 const X86Subtarget *Subtarget) {
18751 StoreSDNode *St = cast<StoreSDNode>(N);
18752 EVT VT = St->getValue().getValueType();
18753 EVT StVT = St->getMemoryVT();
18755 SDValue StoredVal = St->getOperand(1);
18756 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18758 // If we are saving a concatenation of two XMM registers, perform two stores.
18759 // On Sandy Bridge, 256-bit memory operations are executed by two
18760 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18761 // memory operation.
18762 unsigned Alignment = St->getAlignment();
18763 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18764 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18765 StVT == VT && !IsAligned) {
18766 unsigned NumElems = VT.getVectorNumElements();
18770 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18771 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18773 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18774 SDValue Ptr0 = St->getBasePtr();
18775 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18777 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18778 St->getPointerInfo(), St->isVolatile(),
18779 St->isNonTemporal(), Alignment);
18780 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18781 St->getPointerInfo(), St->isVolatile(),
18782 St->isNonTemporal(),
18783 std::min(16U, Alignment));
18784 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18787 // Optimize trunc store (of multiple scalars) to shuffle and store.
18788 // First, pack all of the elements in one place. Next, store to memory
18789 // in fewer chunks.
18790 if (St->isTruncatingStore() && VT.isVector()) {
18791 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18792 unsigned NumElems = VT.getVectorNumElements();
18793 assert(StVT != VT && "Cannot truncate to the same type");
18794 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18795 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18797 // From, To sizes and ElemCount must be pow of two
18798 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18799 // We are going to use the original vector elt for storing.
18800 // Accumulated smaller vector elements must be a multiple of the store size.
18801 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18803 unsigned SizeRatio = FromSz / ToSz;
18805 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18807 // Create a type on which we perform the shuffle
18808 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18809 StVT.getScalarType(), NumElems*SizeRatio);
18811 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18813 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18814 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18815 for (unsigned i = 0; i != NumElems; ++i)
18816 ShuffleVec[i] = i * SizeRatio;
18818 // Can't shuffle using an illegal type.
18819 if (!TLI.isTypeLegal(WideVecVT))
18822 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18823 DAG.getUNDEF(WideVecVT),
18825 // At this point all of the data is stored at the bottom of the
18826 // register. We now need to save it to mem.
18828 // Find the largest store unit
18829 MVT StoreType = MVT::i8;
18830 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18831 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18832 MVT Tp = (MVT::SimpleValueType)tp;
18833 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18837 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18838 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18839 (64 <= NumElems * ToSz))
18840 StoreType = MVT::f64;
18842 // Bitcast the original vector into a vector of store-size units
18843 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18844 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18845 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18846 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18847 SmallVector<SDValue, 8> Chains;
18848 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18849 TLI.getPointerTy());
18850 SDValue Ptr = St->getBasePtr();
18852 // Perform one or more big stores into memory.
18853 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18854 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18855 StoreType, ShuffWide,
18856 DAG.getIntPtrConstant(i));
18857 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18858 St->getPointerInfo(), St->isVolatile(),
18859 St->isNonTemporal(), St->getAlignment());
18860 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18861 Chains.push_back(Ch);
18864 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18868 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
18869 // the FP state in cases where an emms may be missing.
18870 // A preferable solution to the general problem is to figure out the right
18871 // places to insert EMMS. This qualifies as a quick hack.
18873 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18874 if (VT.getSizeInBits() != 64)
18877 const Function *F = DAG.getMachineFunction().getFunction();
18878 bool NoImplicitFloatOps = F->getAttributes().
18879 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18880 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18881 && Subtarget->hasSSE2();
18882 if ((VT.isVector() ||
18883 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18884 isa<LoadSDNode>(St->getValue()) &&
18885 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18886 St->getChain().hasOneUse() && !St->isVolatile()) {
18887 SDNode* LdVal = St->getValue().getNode();
18888 LoadSDNode *Ld = 0;
18889 int TokenFactorIndex = -1;
18890 SmallVector<SDValue, 8> Ops;
18891 SDNode* ChainVal = St->getChain().getNode();
18892 // Must be a store of a load. We currently handle two cases: the load
18893 // is a direct child, and it's under an intervening TokenFactor. It is
18894 // possible to dig deeper under nested TokenFactors.
18895 if (ChainVal == LdVal)
18896 Ld = cast<LoadSDNode>(St->getChain());
18897 else if (St->getValue().hasOneUse() &&
18898 ChainVal->getOpcode() == ISD::TokenFactor) {
18899 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18900 if (ChainVal->getOperand(i).getNode() == LdVal) {
18901 TokenFactorIndex = i;
18902 Ld = cast<LoadSDNode>(St->getValue());
18904 Ops.push_back(ChainVal->getOperand(i));
18908 if (!Ld || !ISD::isNormalLoad(Ld))
18911 // If this is not the MMX case, i.e. we are just turning i64 load/store
18912 // into f64 load/store, avoid the transformation if there are multiple
18913 // uses of the loaded value.
18914 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18919 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18920 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18922 if (Subtarget->is64Bit() || F64IsLegal) {
18923 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18924 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18925 Ld->getPointerInfo(), Ld->isVolatile(),
18926 Ld->isNonTemporal(), Ld->isInvariant(),
18927 Ld->getAlignment());
18928 SDValue NewChain = NewLd.getValue(1);
18929 if (TokenFactorIndex != -1) {
18930 Ops.push_back(NewChain);
18931 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18934 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18935 St->getPointerInfo(),
18936 St->isVolatile(), St->isNonTemporal(),
18937 St->getAlignment());
18940 // Otherwise, lower to two pairs of 32-bit loads / stores.
18941 SDValue LoAddr = Ld->getBasePtr();
18942 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18943 DAG.getConstant(4, MVT::i32));
18945 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18946 Ld->getPointerInfo(),
18947 Ld->isVolatile(), Ld->isNonTemporal(),
18948 Ld->isInvariant(), Ld->getAlignment());
18949 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18950 Ld->getPointerInfo().getWithOffset(4),
18951 Ld->isVolatile(), Ld->isNonTemporal(),
18953 MinAlign(Ld->getAlignment(), 4));
18955 SDValue NewChain = LoLd.getValue(1);
18956 if (TokenFactorIndex != -1) {
18957 Ops.push_back(LoLd);
18958 Ops.push_back(HiLd);
18959 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18963 LoAddr = St->getBasePtr();
18964 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18965 DAG.getConstant(4, MVT::i32));
18967 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18968 St->getPointerInfo(),
18969 St->isVolatile(), St->isNonTemporal(),
18970 St->getAlignment());
18971 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18972 St->getPointerInfo().getWithOffset(4),
18974 St->isNonTemporal(),
18975 MinAlign(St->getAlignment(), 4));
18976 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18981 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18982 /// and return the operands for the horizontal operation in LHS and RHS. A
18983 /// horizontal operation performs the binary operation on successive elements
18984 /// of its first operand, then on successive elements of its second operand,
18985 /// returning the resulting values in a vector. For example, if
18986 /// A = < float a0, float a1, float a2, float a3 >
18988 /// B = < float b0, float b1, float b2, float b3 >
18989 /// then the result of doing a horizontal operation on A and B is
18990 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18991 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18992 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18993 /// set to A, RHS to B, and the routine returns 'true'.
18994 /// Note that the binary operation should have the property that if one of the
18995 /// operands is UNDEF then the result is UNDEF.
18996 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18997 // Look for the following pattern: if
18998 // A = < float a0, float a1, float a2, float a3 >
18999 // B = < float b0, float b1, float b2, float b3 >
19001 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19002 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19003 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19004 // which is A horizontal-op B.
19006 // At least one of the operands should be a vector shuffle.
19007 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19008 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19011 MVT VT = LHS.getSimpleValueType();
19013 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19014 "Unsupported vector type for horizontal add/sub");
19016 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19017 // operate independently on 128-bit lanes.
19018 unsigned NumElts = VT.getVectorNumElements();
19019 unsigned NumLanes = VT.getSizeInBits()/128;
19020 unsigned NumLaneElts = NumElts / NumLanes;
19021 assert((NumLaneElts % 2 == 0) &&
19022 "Vector type should have an even number of elements in each lane");
19023 unsigned HalfLaneElts = NumLaneElts/2;
19025 // View LHS in the form
19026 // LHS = VECTOR_SHUFFLE A, B, LMask
19027 // If LHS is not a shuffle then pretend it is the shuffle
19028 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19029 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19032 SmallVector<int, 16> LMask(NumElts);
19033 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19034 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19035 A = LHS.getOperand(0);
19036 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19037 B = LHS.getOperand(1);
19038 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19039 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19041 if (LHS.getOpcode() != ISD::UNDEF)
19043 for (unsigned i = 0; i != NumElts; ++i)
19047 // Likewise, view RHS in the form
19048 // RHS = VECTOR_SHUFFLE C, D, RMask
19050 SmallVector<int, 16> RMask(NumElts);
19051 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19052 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19053 C = RHS.getOperand(0);
19054 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19055 D = RHS.getOperand(1);
19056 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19057 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19059 if (RHS.getOpcode() != ISD::UNDEF)
19061 for (unsigned i = 0; i != NumElts; ++i)
19065 // Check that the shuffles are both shuffling the same vectors.
19066 if (!(A == C && B == D) && !(A == D && B == C))
19069 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19070 if (!A.getNode() && !B.getNode())
19073 // If A and B occur in reverse order in RHS, then "swap" them (which means
19074 // rewriting the mask).
19076 CommuteVectorShuffleMask(RMask, NumElts);
19078 // At this point LHS and RHS are equivalent to
19079 // LHS = VECTOR_SHUFFLE A, B, LMask
19080 // RHS = VECTOR_SHUFFLE A, B, RMask
19081 // Check that the masks correspond to performing a horizontal operation.
19082 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19083 for (unsigned i = 0; i != NumLaneElts; ++i) {
19084 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19086 // Ignore any UNDEF components.
19087 if (LIdx < 0 || RIdx < 0 ||
19088 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19089 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19092 // Check that successive elements are being operated on. If not, this is
19093 // not a horizontal operation.
19094 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19095 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19096 if (!(LIdx == Index && RIdx == Index + 1) &&
19097 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19102 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19103 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19107 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19108 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19109 const X86Subtarget *Subtarget) {
19110 EVT VT = N->getValueType(0);
19111 SDValue LHS = N->getOperand(0);
19112 SDValue RHS = N->getOperand(1);
19114 // Try to synthesize horizontal adds from adds of shuffles.
19115 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19116 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19117 isHorizontalBinOp(LHS, RHS, true))
19118 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19122 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19123 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19124 const X86Subtarget *Subtarget) {
19125 EVT VT = N->getValueType(0);
19126 SDValue LHS = N->getOperand(0);
19127 SDValue RHS = N->getOperand(1);
19129 // Try to synthesize horizontal subs from subs of shuffles.
19130 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19131 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19132 isHorizontalBinOp(LHS, RHS, false))
19133 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19137 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19138 /// X86ISD::FXOR nodes.
19139 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19140 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19141 // F[X]OR(0.0, x) -> x
19142 // F[X]OR(x, 0.0) -> x
19143 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19144 if (C->getValueAPF().isPosZero())
19145 return N->getOperand(1);
19146 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19147 if (C->getValueAPF().isPosZero())
19148 return N->getOperand(0);
19152 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19153 /// X86ISD::FMAX nodes.
19154 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19155 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19157 // Only perform optimizations if UnsafeMath is used.
19158 if (!DAG.getTarget().Options.UnsafeFPMath)
19161 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19162 // into FMINC and FMAXC, which are Commutative operations.
19163 unsigned NewOp = 0;
19164 switch (N->getOpcode()) {
19165 default: llvm_unreachable("unknown opcode");
19166 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19167 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19170 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19171 N->getOperand(0), N->getOperand(1));
19174 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19175 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19176 // FAND(0.0, x) -> 0.0
19177 // FAND(x, 0.0) -> 0.0
19178 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19179 if (C->getValueAPF().isPosZero())
19180 return N->getOperand(0);
19181 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19182 if (C->getValueAPF().isPosZero())
19183 return N->getOperand(1);
19187 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19188 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19189 // FANDN(x, 0.0) -> 0.0
19190 // FANDN(0.0, x) -> x
19191 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19192 if (C->getValueAPF().isPosZero())
19193 return N->getOperand(1);
19194 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19195 if (C->getValueAPF().isPosZero())
19196 return N->getOperand(1);
19200 static SDValue PerformBTCombine(SDNode *N,
19202 TargetLowering::DAGCombinerInfo &DCI) {
19203 // BT ignores high bits in the bit index operand.
19204 SDValue Op1 = N->getOperand(1);
19205 if (Op1.hasOneUse()) {
19206 unsigned BitWidth = Op1.getValueSizeInBits();
19207 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19208 APInt KnownZero, KnownOne;
19209 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19210 !DCI.isBeforeLegalizeOps());
19211 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19212 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19213 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19214 DCI.CommitTargetLoweringOpt(TLO);
19219 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19220 SDValue Op = N->getOperand(0);
19221 if (Op.getOpcode() == ISD::BITCAST)
19222 Op = Op.getOperand(0);
19223 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19224 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19225 VT.getVectorElementType().getSizeInBits() ==
19226 OpVT.getVectorElementType().getSizeInBits()) {
19227 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19232 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19233 const X86Subtarget *Subtarget) {
19234 EVT VT = N->getValueType(0);
19235 if (!VT.isVector())
19238 SDValue N0 = N->getOperand(0);
19239 SDValue N1 = N->getOperand(1);
19240 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19243 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19244 // both SSE and AVX2 since there is no sign-extended shift right
19245 // operation on a vector with 64-bit elements.
19246 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19247 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19248 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19249 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19250 SDValue N00 = N0.getOperand(0);
19252 // EXTLOAD has a better solution on AVX2,
19253 // it may be replaced with X86ISD::VSEXT node.
19254 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19255 if (!ISD::isNormalLoad(N00.getNode()))
19258 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19259 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19261 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19267 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19268 TargetLowering::DAGCombinerInfo &DCI,
19269 const X86Subtarget *Subtarget) {
19270 if (!DCI.isBeforeLegalizeOps())
19273 if (!Subtarget->hasFp256())
19276 EVT VT = N->getValueType(0);
19277 if (VT.isVector() && VT.getSizeInBits() == 256) {
19278 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19286 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19287 const X86Subtarget* Subtarget) {
19289 EVT VT = N->getValueType(0);
19291 // Let legalize expand this if it isn't a legal type yet.
19292 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19295 EVT ScalarVT = VT.getScalarType();
19296 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19297 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19300 SDValue A = N->getOperand(0);
19301 SDValue B = N->getOperand(1);
19302 SDValue C = N->getOperand(2);
19304 bool NegA = (A.getOpcode() == ISD::FNEG);
19305 bool NegB = (B.getOpcode() == ISD::FNEG);
19306 bool NegC = (C.getOpcode() == ISD::FNEG);
19308 // Negative multiplication when NegA xor NegB
19309 bool NegMul = (NegA != NegB);
19311 A = A.getOperand(0);
19313 B = B.getOperand(0);
19315 C = C.getOperand(0);
19319 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19321 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19323 return DAG.getNode(Opcode, dl, VT, A, B, C);
19326 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19327 TargetLowering::DAGCombinerInfo &DCI,
19328 const X86Subtarget *Subtarget) {
19329 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19330 // (and (i32 x86isd::setcc_carry), 1)
19331 // This eliminates the zext. This transformation is necessary because
19332 // ISD::SETCC is always legalized to i8.
19334 SDValue N0 = N->getOperand(0);
19335 EVT VT = N->getValueType(0);
19337 if (N0.getOpcode() == ISD::AND &&
19339 N0.getOperand(0).hasOneUse()) {
19340 SDValue N00 = N0.getOperand(0);
19341 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19342 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19343 if (!C || C->getZExtValue() != 1)
19345 return DAG.getNode(ISD::AND, dl, VT,
19346 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19347 N00.getOperand(0), N00.getOperand(1)),
19348 DAG.getConstant(1, VT));
19352 if (N0.getOpcode() == ISD::TRUNCATE &&
19354 N0.getOperand(0).hasOneUse()) {
19355 SDValue N00 = N0.getOperand(0);
19356 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19357 return DAG.getNode(ISD::AND, dl, VT,
19358 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19359 N00.getOperand(0), N00.getOperand(1)),
19360 DAG.getConstant(1, VT));
19363 if (VT.is256BitVector()) {
19364 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19372 // Optimize x == -y --> x+y == 0
19373 // x != -y --> x+y != 0
19374 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19375 const X86Subtarget* Subtarget) {
19376 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19377 SDValue LHS = N->getOperand(0);
19378 SDValue RHS = N->getOperand(1);
19379 EVT VT = N->getValueType(0);
19382 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19383 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19384 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19385 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19386 LHS.getValueType(), RHS, LHS.getOperand(1));
19387 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19388 addV, DAG.getConstant(0, addV.getValueType()), CC);
19390 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19391 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19392 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19393 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19394 RHS.getValueType(), LHS, RHS.getOperand(1));
19395 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19396 addV, DAG.getConstant(0, addV.getValueType()), CC);
19399 if (VT.getScalarType() == MVT::i1) {
19400 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19401 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19402 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19403 if (!IsSEXT0 && !IsVZero0)
19405 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19406 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19407 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19409 if (!IsSEXT1 && !IsVZero1)
19412 if (IsSEXT0 && IsVZero1) {
19413 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19414 if (CC == ISD::SETEQ)
19415 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19416 return LHS.getOperand(0);
19418 if (IsSEXT1 && IsVZero0) {
19419 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19420 if (CC == ISD::SETEQ)
19421 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19422 return RHS.getOperand(0);
19429 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19430 // as "sbb reg,reg", since it can be extended without zext and produces
19431 // an all-ones bit which is more useful than 0/1 in some cases.
19432 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19435 return DAG.getNode(ISD::AND, DL, VT,
19436 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19437 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19438 DAG.getConstant(1, VT));
19439 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19440 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19441 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19442 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19445 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19446 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19447 TargetLowering::DAGCombinerInfo &DCI,
19448 const X86Subtarget *Subtarget) {
19450 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19451 SDValue EFLAGS = N->getOperand(1);
19453 if (CC == X86::COND_A) {
19454 // Try to convert COND_A into COND_B in an attempt to facilitate
19455 // materializing "setb reg".
19457 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19458 // cannot take an immediate as its first operand.
19460 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19461 EFLAGS.getValueType().isInteger() &&
19462 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19463 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19464 EFLAGS.getNode()->getVTList(),
19465 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19466 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19467 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19471 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19472 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19474 if (CC == X86::COND_B)
19475 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19479 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19480 if (Flags.getNode()) {
19481 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19482 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19488 // Optimize branch condition evaluation.
19490 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19491 TargetLowering::DAGCombinerInfo &DCI,
19492 const X86Subtarget *Subtarget) {
19494 SDValue Chain = N->getOperand(0);
19495 SDValue Dest = N->getOperand(1);
19496 SDValue EFLAGS = N->getOperand(3);
19497 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19501 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19502 if (Flags.getNode()) {
19503 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19504 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19511 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19512 const X86TargetLowering *XTLI) {
19513 SDValue Op0 = N->getOperand(0);
19514 EVT InVT = Op0->getValueType(0);
19516 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19517 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19519 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19520 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19521 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19524 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19525 // a 32-bit target where SSE doesn't support i64->FP operations.
19526 if (Op0.getOpcode() == ISD::LOAD) {
19527 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19528 EVT VT = Ld->getValueType(0);
19529 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19530 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19531 !XTLI->getSubtarget()->is64Bit() &&
19533 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19534 Ld->getChain(), Op0, DAG);
19535 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19542 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19543 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19544 X86TargetLowering::DAGCombinerInfo &DCI) {
19545 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19546 // the result is either zero or one (depending on the input carry bit).
19547 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19548 if (X86::isZeroNode(N->getOperand(0)) &&
19549 X86::isZeroNode(N->getOperand(1)) &&
19550 // We don't have a good way to replace an EFLAGS use, so only do this when
19552 SDValue(N, 1).use_empty()) {
19554 EVT VT = N->getValueType(0);
19555 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19556 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19557 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19558 DAG.getConstant(X86::COND_B,MVT::i8),
19560 DAG.getConstant(1, VT));
19561 return DCI.CombineTo(N, Res1, CarryOut);
19567 // fold (add Y, (sete X, 0)) -> adc 0, Y
19568 // (add Y, (setne X, 0)) -> sbb -1, Y
19569 // (sub (sete X, 0), Y) -> sbb 0, Y
19570 // (sub (setne X, 0), Y) -> adc -1, Y
19571 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19574 // Look through ZExts.
19575 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19576 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19579 SDValue SetCC = Ext.getOperand(0);
19580 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19583 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19584 if (CC != X86::COND_E && CC != X86::COND_NE)
19587 SDValue Cmp = SetCC.getOperand(1);
19588 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19589 !X86::isZeroNode(Cmp.getOperand(1)) ||
19590 !Cmp.getOperand(0).getValueType().isInteger())
19593 SDValue CmpOp0 = Cmp.getOperand(0);
19594 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19595 DAG.getConstant(1, CmpOp0.getValueType()));
19597 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19598 if (CC == X86::COND_NE)
19599 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19600 DL, OtherVal.getValueType(), OtherVal,
19601 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19602 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19603 DL, OtherVal.getValueType(), OtherVal,
19604 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19607 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19608 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19609 const X86Subtarget *Subtarget) {
19610 EVT VT = N->getValueType(0);
19611 SDValue Op0 = N->getOperand(0);
19612 SDValue Op1 = N->getOperand(1);
19614 // Try to synthesize horizontal adds from adds of shuffles.
19615 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19616 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19617 isHorizontalBinOp(Op0, Op1, true))
19618 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19620 return OptimizeConditionalInDecrement(N, DAG);
19623 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19624 const X86Subtarget *Subtarget) {
19625 SDValue Op0 = N->getOperand(0);
19626 SDValue Op1 = N->getOperand(1);
19628 // X86 can't encode an immediate LHS of a sub. See if we can push the
19629 // negation into a preceding instruction.
19630 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19631 // If the RHS of the sub is a XOR with one use and a constant, invert the
19632 // immediate. Then add one to the LHS of the sub so we can turn
19633 // X-Y -> X+~Y+1, saving one register.
19634 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19635 isa<ConstantSDNode>(Op1.getOperand(1))) {
19636 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19637 EVT VT = Op0.getValueType();
19638 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19640 DAG.getConstant(~XorC, VT));
19641 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19642 DAG.getConstant(C->getAPIntValue()+1, VT));
19646 // Try to synthesize horizontal adds from adds of shuffles.
19647 EVT VT = N->getValueType(0);
19648 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19649 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19650 isHorizontalBinOp(Op0, Op1, true))
19651 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19653 return OptimizeConditionalInDecrement(N, DAG);
19656 /// performVZEXTCombine - Performs build vector combines
19657 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19658 TargetLowering::DAGCombinerInfo &DCI,
19659 const X86Subtarget *Subtarget) {
19660 // (vzext (bitcast (vzext (x)) -> (vzext x)
19661 SDValue In = N->getOperand(0);
19662 while (In.getOpcode() == ISD::BITCAST)
19663 In = In.getOperand(0);
19665 if (In.getOpcode() != X86ISD::VZEXT)
19668 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19672 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19673 DAGCombinerInfo &DCI) const {
19674 SelectionDAG &DAG = DCI.DAG;
19675 switch (N->getOpcode()) {
19677 case ISD::EXTRACT_VECTOR_ELT:
19678 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19680 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19681 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19682 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
19683 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
19684 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
19685 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
19688 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
19689 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
19690 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
19691 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
19692 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
19693 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
19694 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
19695 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
19696 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
19698 case X86ISD::FOR: return PerformFORCombine(N, DAG);
19700 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
19701 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
19702 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
19703 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
19704 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
19705 case ISD::ANY_EXTEND:
19706 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
19707 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
19708 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19709 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19710 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
19711 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19712 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19713 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
19714 case X86ISD::SHUFP: // Handle all target specific shuffles
19715 case X86ISD::PALIGNR:
19716 case X86ISD::UNPCKH:
19717 case X86ISD::UNPCKL:
19718 case X86ISD::MOVHLPS:
19719 case X86ISD::MOVLHPS:
19720 case X86ISD::PSHUFD:
19721 case X86ISD::PSHUFHW:
19722 case X86ISD::PSHUFLW:
19723 case X86ISD::MOVSS:
19724 case X86ISD::MOVSD:
19725 case X86ISD::VPERMILP:
19726 case X86ISD::VPERM2X128:
19727 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19728 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
19734 /// isTypeDesirableForOp - Return true if the target has native support for
19735 /// the specified value type and it is 'desirable' to use the type for the
19736 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19737 /// instruction encodings are longer and some i16 instructions are slow.
19738 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19739 if (!isTypeLegal(VT))
19741 if (VT != MVT::i16)
19748 case ISD::SIGN_EXTEND:
19749 case ISD::ZERO_EXTEND:
19750 case ISD::ANY_EXTEND:
19763 /// IsDesirableToPromoteOp - This method query the target whether it is
19764 /// beneficial for dag combiner to promote the specified node. If true, it
19765 /// should return the desired promotion type by reference.
19766 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19767 EVT VT = Op.getValueType();
19768 if (VT != MVT::i16)
19771 bool Promote = false;
19772 bool Commute = false;
19773 switch (Op.getOpcode()) {
19776 LoadSDNode *LD = cast<LoadSDNode>(Op);
19777 // If the non-extending load has a single use and it's not live out, then it
19778 // might be folded.
19779 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19780 Op.hasOneUse()*/) {
19781 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19782 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19783 // The only case where we'd want to promote LOAD (rather then it being
19784 // promoted as an operand is when it's only use is liveout.
19785 if (UI->getOpcode() != ISD::CopyToReg)
19792 case ISD::SIGN_EXTEND:
19793 case ISD::ZERO_EXTEND:
19794 case ISD::ANY_EXTEND:
19799 SDValue N0 = Op.getOperand(0);
19800 // Look out for (store (shl (load), x)).
19801 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19814 SDValue N0 = Op.getOperand(0);
19815 SDValue N1 = Op.getOperand(1);
19816 if (!Commute && MayFoldLoad(N1))
19818 // Avoid disabling potential load folding opportunities.
19819 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19821 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19831 //===----------------------------------------------------------------------===//
19832 // X86 Inline Assembly Support
19833 //===----------------------------------------------------------------------===//
19836 // Helper to match a string separated by whitespace.
19837 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19838 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19840 for (unsigned i = 0, e = args.size(); i != e; ++i) {
19841 StringRef piece(*args[i]);
19842 if (!s.startswith(piece)) // Check if the piece matches.
19845 s = s.substr(piece.size());
19846 StringRef::size_type pos = s.find_first_not_of(" \t");
19847 if (pos == 0) // We matched a prefix.
19855 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19858 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19860 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19861 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19862 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19863 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19865 if (AsmPieces.size() == 3)
19867 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19874 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19875 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19877 std::string AsmStr = IA->getAsmString();
19879 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19880 if (!Ty || Ty->getBitWidth() % 16 != 0)
19883 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19884 SmallVector<StringRef, 4> AsmPieces;
19885 SplitString(AsmStr, AsmPieces, ";\n");
19887 switch (AsmPieces.size()) {
19888 default: return false;
19890 // FIXME: this should verify that we are targeting a 486 or better. If not,
19891 // we will turn this bswap into something that will be lowered to logical
19892 // ops instead of emitting the bswap asm. For now, we don't support 486 or
19893 // lower so don't worry about this.
19895 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19896 matchAsm(AsmPieces[0], "bswapl", "$0") ||
19897 matchAsm(AsmPieces[0], "bswapq", "$0") ||
19898 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19899 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19900 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19901 // No need to check constraints, nothing other than the equivalent of
19902 // "=r,0" would be valid here.
19903 return IntrinsicLowering::LowerToByteSwap(CI);
19906 // rorw $$8, ${0:w} --> llvm.bswap.i16
19907 if (CI->getType()->isIntegerTy(16) &&
19908 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19909 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19910 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19912 const std::string &ConstraintsStr = IA->getConstraintString();
19913 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19914 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19915 if (clobbersFlagRegisters(AsmPieces))
19916 return IntrinsicLowering::LowerToByteSwap(CI);
19920 if (CI->getType()->isIntegerTy(32) &&
19921 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19922 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19923 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19924 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19926 const std::string &ConstraintsStr = IA->getConstraintString();
19927 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19928 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19929 if (clobbersFlagRegisters(AsmPieces))
19930 return IntrinsicLowering::LowerToByteSwap(CI);
19933 if (CI->getType()->isIntegerTy(64)) {
19934 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19935 if (Constraints.size() >= 2 &&
19936 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19937 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19938 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
19939 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19940 matchAsm(AsmPieces[1], "bswap", "%edx") &&
19941 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19942 return IntrinsicLowering::LowerToByteSwap(CI);
19950 /// getConstraintType - Given a constraint letter, return the type of
19951 /// constraint it is for this target.
19952 X86TargetLowering::ConstraintType
19953 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19954 if (Constraint.size() == 1) {
19955 switch (Constraint[0]) {
19966 return C_RegisterClass;
19990 return TargetLowering::getConstraintType(Constraint);
19993 /// Examine constraint type and operand type and determine a weight value.
19994 /// This object must already have been set up with the operand type
19995 /// and the current alternative constraint selected.
19996 TargetLowering::ConstraintWeight
19997 X86TargetLowering::getSingleConstraintMatchWeight(
19998 AsmOperandInfo &info, const char *constraint) const {
19999 ConstraintWeight weight = CW_Invalid;
20000 Value *CallOperandVal = info.CallOperandVal;
20001 // If we don't have a value, we can't do a match,
20002 // but allow it at the lowest weight.
20003 if (CallOperandVal == NULL)
20005 Type *type = CallOperandVal->getType();
20006 // Look at the constraint type.
20007 switch (*constraint) {
20009 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20020 if (CallOperandVal->getType()->isIntegerTy())
20021 weight = CW_SpecificReg;
20026 if (type->isFloatingPointTy())
20027 weight = CW_SpecificReg;
20030 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20031 weight = CW_SpecificReg;
20035 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20036 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20037 weight = CW_Register;
20040 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20041 if (C->getZExtValue() <= 31)
20042 weight = CW_Constant;
20046 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20047 if (C->getZExtValue() <= 63)
20048 weight = CW_Constant;
20052 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20053 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20054 weight = CW_Constant;
20058 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20059 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20060 weight = CW_Constant;
20064 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20065 if (C->getZExtValue() <= 3)
20066 weight = CW_Constant;
20070 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20071 if (C->getZExtValue() <= 0xff)
20072 weight = CW_Constant;
20077 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20078 weight = CW_Constant;
20082 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20083 if ((C->getSExtValue() >= -0x80000000LL) &&
20084 (C->getSExtValue() <= 0x7fffffffLL))
20085 weight = CW_Constant;
20089 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20090 if (C->getZExtValue() <= 0xffffffff)
20091 weight = CW_Constant;
20098 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20099 /// with another that has more specific requirements based on the type of the
20100 /// corresponding operand.
20101 const char *X86TargetLowering::
20102 LowerXConstraint(EVT ConstraintVT) const {
20103 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20104 // 'f' like normal targets.
20105 if (ConstraintVT.isFloatingPoint()) {
20106 if (Subtarget->hasSSE2())
20108 if (Subtarget->hasSSE1())
20112 return TargetLowering::LowerXConstraint(ConstraintVT);
20115 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20116 /// vector. If it is invalid, don't add anything to Ops.
20117 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20118 std::string &Constraint,
20119 std::vector<SDValue>&Ops,
20120 SelectionDAG &DAG) const {
20121 SDValue Result(0, 0);
20123 // Only support length 1 constraints for now.
20124 if (Constraint.length() > 1) return;
20126 char ConstraintLetter = Constraint[0];
20127 switch (ConstraintLetter) {
20130 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20131 if (C->getZExtValue() <= 31) {
20132 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20138 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20139 if (C->getZExtValue() <= 63) {
20140 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20146 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20147 if (isInt<8>(C->getSExtValue())) {
20148 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20154 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20155 if (C->getZExtValue() <= 255) {
20156 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20162 // 32-bit signed value
20163 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20164 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20165 C->getSExtValue())) {
20166 // Widen to 64 bits here to get it sign extended.
20167 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20170 // FIXME gcc accepts some relocatable values here too, but only in certain
20171 // memory models; it's complicated.
20176 // 32-bit unsigned value
20177 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20178 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20179 C->getZExtValue())) {
20180 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20184 // FIXME gcc accepts some relocatable values here too, but only in certain
20185 // memory models; it's complicated.
20189 // Literal immediates are always ok.
20190 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20191 // Widen to 64 bits here to get it sign extended.
20192 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20196 // In any sort of PIC mode addresses need to be computed at runtime by
20197 // adding in a register or some sort of table lookup. These can't
20198 // be used as immediates.
20199 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20202 // If we are in non-pic codegen mode, we allow the address of a global (with
20203 // an optional displacement) to be used with 'i'.
20204 GlobalAddressSDNode *GA = 0;
20205 int64_t Offset = 0;
20207 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20209 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20210 Offset += GA->getOffset();
20212 } else if (Op.getOpcode() == ISD::ADD) {
20213 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20214 Offset += C->getZExtValue();
20215 Op = Op.getOperand(0);
20218 } else if (Op.getOpcode() == ISD::SUB) {
20219 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20220 Offset += -C->getZExtValue();
20221 Op = Op.getOperand(0);
20226 // Otherwise, this isn't something we can handle, reject it.
20230 const GlobalValue *GV = GA->getGlobal();
20231 // If we require an extra load to get this address, as in PIC mode, we
20232 // can't accept it.
20233 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20234 getTargetMachine())))
20237 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20238 GA->getValueType(0), Offset);
20243 if (Result.getNode()) {
20244 Ops.push_back(Result);
20247 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20250 std::pair<unsigned, const TargetRegisterClass*>
20251 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20253 // First, see if this is a constraint that directly corresponds to an LLVM
20255 if (Constraint.size() == 1) {
20256 // GCC Constraint Letters
20257 switch (Constraint[0]) {
20259 // TODO: Slight differences here in allocation order and leaving
20260 // RIP in the class. Do they matter any more here than they do
20261 // in the normal allocation?
20262 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20263 if (Subtarget->is64Bit()) {
20264 if (VT == MVT::i32 || VT == MVT::f32)
20265 return std::make_pair(0U, &X86::GR32RegClass);
20266 if (VT == MVT::i16)
20267 return std::make_pair(0U, &X86::GR16RegClass);
20268 if (VT == MVT::i8 || VT == MVT::i1)
20269 return std::make_pair(0U, &X86::GR8RegClass);
20270 if (VT == MVT::i64 || VT == MVT::f64)
20271 return std::make_pair(0U, &X86::GR64RegClass);
20274 // 32-bit fallthrough
20275 case 'Q': // Q_REGS
20276 if (VT == MVT::i32 || VT == MVT::f32)
20277 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20278 if (VT == MVT::i16)
20279 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20280 if (VT == MVT::i8 || VT == MVT::i1)
20281 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20282 if (VT == MVT::i64)
20283 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20285 case 'r': // GENERAL_REGS
20286 case 'l': // INDEX_REGS
20287 if (VT == MVT::i8 || VT == MVT::i1)
20288 return std::make_pair(0U, &X86::GR8RegClass);
20289 if (VT == MVT::i16)
20290 return std::make_pair(0U, &X86::GR16RegClass);
20291 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20292 return std::make_pair(0U, &X86::GR32RegClass);
20293 return std::make_pair(0U, &X86::GR64RegClass);
20294 case 'R': // LEGACY_REGS
20295 if (VT == MVT::i8 || VT == MVT::i1)
20296 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20297 if (VT == MVT::i16)
20298 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20299 if (VT == MVT::i32 || !Subtarget->is64Bit())
20300 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20301 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20302 case 'f': // FP Stack registers.
20303 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20304 // value to the correct fpstack register class.
20305 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20306 return std::make_pair(0U, &X86::RFP32RegClass);
20307 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20308 return std::make_pair(0U, &X86::RFP64RegClass);
20309 return std::make_pair(0U, &X86::RFP80RegClass);
20310 case 'y': // MMX_REGS if MMX allowed.
20311 if (!Subtarget->hasMMX()) break;
20312 return std::make_pair(0U, &X86::VR64RegClass);
20313 case 'Y': // SSE_REGS if SSE2 allowed
20314 if (!Subtarget->hasSSE2()) break;
20316 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20317 if (!Subtarget->hasSSE1()) break;
20319 switch (VT.SimpleTy) {
20321 // Scalar SSE types.
20324 return std::make_pair(0U, &X86::FR32RegClass);
20327 return std::make_pair(0U, &X86::FR64RegClass);
20335 return std::make_pair(0U, &X86::VR128RegClass);
20343 return std::make_pair(0U, &X86::VR256RegClass);
20348 return std::make_pair(0U, &X86::VR512RegClass);
20354 // Use the default implementation in TargetLowering to convert the register
20355 // constraint into a member of a register class.
20356 std::pair<unsigned, const TargetRegisterClass*> Res;
20357 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20359 // Not found as a standard register?
20360 if (Res.second == 0) {
20361 // Map st(0) -> st(7) -> ST0
20362 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20363 tolower(Constraint[1]) == 's' &&
20364 tolower(Constraint[2]) == 't' &&
20365 Constraint[3] == '(' &&
20366 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20367 Constraint[5] == ')' &&
20368 Constraint[6] == '}') {
20370 Res.first = X86::ST0+Constraint[4]-'0';
20371 Res.second = &X86::RFP80RegClass;
20375 // GCC allows "st(0)" to be called just plain "st".
20376 if (StringRef("{st}").equals_lower(Constraint)) {
20377 Res.first = X86::ST0;
20378 Res.second = &X86::RFP80RegClass;
20383 if (StringRef("{flags}").equals_lower(Constraint)) {
20384 Res.first = X86::EFLAGS;
20385 Res.second = &X86::CCRRegClass;
20389 // 'A' means EAX + EDX.
20390 if (Constraint == "A") {
20391 Res.first = X86::EAX;
20392 Res.second = &X86::GR32_ADRegClass;
20398 // Otherwise, check to see if this is a register class of the wrong value
20399 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20400 // turn into {ax},{dx}.
20401 if (Res.second->hasType(VT))
20402 return Res; // Correct type already, nothing to do.
20404 // All of the single-register GCC register classes map their values onto
20405 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20406 // really want an 8-bit or 32-bit register, map to the appropriate register
20407 // class and return the appropriate register.
20408 if (Res.second == &X86::GR16RegClass) {
20409 if (VT == MVT::i8 || VT == MVT::i1) {
20410 unsigned DestReg = 0;
20411 switch (Res.first) {
20413 case X86::AX: DestReg = X86::AL; break;
20414 case X86::DX: DestReg = X86::DL; break;
20415 case X86::CX: DestReg = X86::CL; break;
20416 case X86::BX: DestReg = X86::BL; break;
20419 Res.first = DestReg;
20420 Res.second = &X86::GR8RegClass;
20422 } else if (VT == MVT::i32 || VT == MVT::f32) {
20423 unsigned DestReg = 0;
20424 switch (Res.first) {
20426 case X86::AX: DestReg = X86::EAX; break;
20427 case X86::DX: DestReg = X86::EDX; break;
20428 case X86::CX: DestReg = X86::ECX; break;
20429 case X86::BX: DestReg = X86::EBX; break;
20430 case X86::SI: DestReg = X86::ESI; break;
20431 case X86::DI: DestReg = X86::EDI; break;
20432 case X86::BP: DestReg = X86::EBP; break;
20433 case X86::SP: DestReg = X86::ESP; break;
20436 Res.first = DestReg;
20437 Res.second = &X86::GR32RegClass;
20439 } else if (VT == MVT::i64 || VT == MVT::f64) {
20440 unsigned DestReg = 0;
20441 switch (Res.first) {
20443 case X86::AX: DestReg = X86::RAX; break;
20444 case X86::DX: DestReg = X86::RDX; break;
20445 case X86::CX: DestReg = X86::RCX; break;
20446 case X86::BX: DestReg = X86::RBX; break;
20447 case X86::SI: DestReg = X86::RSI; break;
20448 case X86::DI: DestReg = X86::RDI; break;
20449 case X86::BP: DestReg = X86::RBP; break;
20450 case X86::SP: DestReg = X86::RSP; break;
20453 Res.first = DestReg;
20454 Res.second = &X86::GR64RegClass;
20457 } else if (Res.second == &X86::FR32RegClass ||
20458 Res.second == &X86::FR64RegClass ||
20459 Res.second == &X86::VR128RegClass ||
20460 Res.second == &X86::VR256RegClass ||
20461 Res.second == &X86::FR32XRegClass ||
20462 Res.second == &X86::FR64XRegClass ||
20463 Res.second == &X86::VR128XRegClass ||
20464 Res.second == &X86::VR256XRegClass ||
20465 Res.second == &X86::VR512RegClass) {
20466 // Handle references to XMM physical registers that got mapped into the
20467 // wrong class. This can happen with constraints like {xmm0} where the
20468 // target independent register mapper will just pick the first match it can
20469 // find, ignoring the required type.
20471 if (VT == MVT::f32 || VT == MVT::i32)
20472 Res.second = &X86::FR32RegClass;
20473 else if (VT == MVT::f64 || VT == MVT::i64)
20474 Res.second = &X86::FR64RegClass;
20475 else if (X86::VR128RegClass.hasType(VT))
20476 Res.second = &X86::VR128RegClass;
20477 else if (X86::VR256RegClass.hasType(VT))
20478 Res.second = &X86::VR256RegClass;
20479 else if (X86::VR512RegClass.hasType(VT))
20480 Res.second = &X86::VR512RegClass;