1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
54 #define DEBUG_TYPE "x86-isel"
56 STATISTIC(NumTailCalls, "Number of tail calls");
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
62 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
63 SelectionDAG &DAG, SDLoc dl,
64 unsigned vectorWidth) {
65 assert((vectorWidth == 128 || vectorWidth == 256) &&
66 "Unsupported vector width");
67 EVT VT = Vec.getValueType();
68 EVT ElVT = VT.getVectorElementType();
69 unsigned Factor = VT.getSizeInBits()/vectorWidth;
70 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
71 VT.getVectorNumElements()/Factor);
73 // Extract from UNDEF is UNDEF.
74 if (Vec.getOpcode() == ISD::UNDEF)
75 return DAG.getUNDEF(ResultVT);
77 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
78 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80 // This is the index of the first element of the vectorWidth-bit chunk
82 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
85 // If the input is a buildvector just emit a smaller one.
86 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
87 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
88 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
90 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
91 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
97 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
98 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
99 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
100 /// instructions or a simple subregister reference. Idx is an index in the
101 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
102 /// lowering EXTRACT_VECTOR_ELT operations easier.
103 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
104 SelectionDAG &DAG, SDLoc dl) {
105 assert((Vec.getValueType().is256BitVector() ||
106 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
107 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 /// Generate a DAG to grab 256-bits from a 512-bit vector.
111 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
112 SelectionDAG &DAG, SDLoc dl) {
113 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
114 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
118 unsigned IdxVal, SelectionDAG &DAG,
119 SDLoc dl, unsigned vectorWidth) {
120 assert((vectorWidth == 128 || vectorWidth == 256) &&
121 "Unsupported vector width");
122 // Inserting UNDEF is Result
123 if (Vec.getOpcode() == ISD::UNDEF)
125 EVT VT = Vec.getValueType();
126 EVT ElVT = VT.getVectorElementType();
127 EVT ResultVT = Result.getValueType();
129 // Insert the relevant vectorWidth bits.
130 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
132 // This is the index of the first element of the vectorWidth-bit chunk
134 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
138 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
142 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
143 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
144 /// simple superregister reference. Idx is an index in the 128 bits
145 /// we want. It need not be aligned to a 128-bit bounday. That makes
146 /// lowering INSERT_VECTOR_ELT operations easier.
147 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
148 unsigned IdxVal, SelectionDAG &DAG,
150 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
151 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
155 unsigned IdxVal, SelectionDAG &DAG,
157 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
158 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
162 /// instructions. This is used because creating CONCAT_VECTOR nodes of
163 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
164 /// large BUILD_VECTORS.
165 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
166 unsigned NumElems, SelectionDAG &DAG,
168 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
169 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
173 unsigned NumElems, SelectionDAG &DAG,
175 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
176 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
180 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
181 bool is64Bit = Subtarget->is64Bit();
183 if (Subtarget->isTargetMacho()) {
185 return new X86_64MachoTargetObjectFile();
186 return new TargetLoweringObjectFileMachO();
189 if (Subtarget->isTargetLinux())
190 return new X86LinuxTargetObjectFile();
191 if (Subtarget->isTargetELF())
192 return new TargetLoweringObjectFileELF();
193 if (Subtarget->isTargetKnownWindowsMSVC())
194 return new X86WindowsTargetObjectFile();
195 if (Subtarget->isTargetCOFF())
196 return new TargetLoweringObjectFileCOFF();
197 llvm_unreachable("unknown subtarget type");
200 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
201 : TargetLowering(TM, createTLOF(TM)) {
202 Subtarget = &TM.getSubtarget<X86Subtarget>();
203 X86ScalarSSEf64 = Subtarget->hasSSE2();
204 X86ScalarSSEf32 = Subtarget->hasSSE1();
205 TD = getDataLayout();
207 resetOperationActions();
210 void X86TargetLowering::resetOperationActions() {
211 const TargetMachine &TM = getTargetMachine();
212 static bool FirstTimeThrough = true;
214 // If none of the target options have changed, then we don't need to reset the
215 // operation actions.
216 if (!FirstTimeThrough && TO == TM.Options) return;
218 if (!FirstTimeThrough) {
219 // Reinitialize the actions.
221 FirstTimeThrough = false;
226 // Set up the TargetLowering object.
227 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
229 // X86 is weird, it always uses i8 for shift amounts and setcc results.
230 setBooleanContents(ZeroOrOneBooleanContent);
231 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
232 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
234 // For 64-bit since we have so many registers use the ILP scheduler, for
235 // 32-bit code use the register pressure specific scheduling.
236 // For Atom, always use ILP scheduling.
237 if (Subtarget->isAtom())
238 setSchedulingPreference(Sched::ILP);
239 else if (Subtarget->is64Bit())
240 setSchedulingPreference(Sched::ILP);
242 setSchedulingPreference(Sched::RegPressure);
243 const X86RegisterInfo *RegInfo =
244 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
245 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
247 // Bypass expensive divides on Atom when compiling with O2
248 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
249 addBypassSlowDiv(32, 8);
250 if (Subtarget->is64Bit())
251 addBypassSlowDiv(64, 16);
254 if (Subtarget->isTargetKnownWindowsMSVC()) {
255 // Setup Windows compiler runtime calls.
256 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258 setLibcallName(RTLIB::SREM_I64, "_allrem");
259 setLibcallName(RTLIB::UREM_I64, "_aullrem");
260 setLibcallName(RTLIB::MUL_I64, "_allmul");
261 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
267 // The _ftol2 runtime function has an unusual calling conv, which
268 // is modeled by a special pseudo-instruction.
269 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
270 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
271 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
275 if (Subtarget->isTargetDarwin()) {
276 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277 setUseUnderscoreSetJmp(false);
278 setUseUnderscoreLongJmp(false);
279 } else if (Subtarget->isTargetWindowsGNU()) {
280 // MS runtime is weird: it exports _setjmp, but longjmp!
281 setUseUnderscoreSetJmp(true);
282 setUseUnderscoreLongJmp(false);
284 setUseUnderscoreSetJmp(true);
285 setUseUnderscoreLongJmp(true);
288 // Set up the register classes.
289 addRegisterClass(MVT::i8, &X86::GR8RegClass);
290 addRegisterClass(MVT::i16, &X86::GR16RegClass);
291 addRegisterClass(MVT::i32, &X86::GR32RegClass);
292 if (Subtarget->is64Bit())
293 addRegisterClass(MVT::i64, &X86::GR64RegClass);
295 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
297 // We don't accept any truncstore of integer registers.
298 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
305 // SETOEQ and SETUNE require checking two conditions.
306 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
307 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
308 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
309 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
313 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
315 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
316 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
317 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
319 if (Subtarget->is64Bit()) {
320 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
321 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
322 } else if (!TM.Options.UseSoftFloat) {
323 // We have an algorithm for SSE2->double, and we turn this into a
324 // 64-bit FILD followed by conditional FADD for other targets.
325 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
326 // We have an algorithm for SSE2, and we turn this into a 64-bit
327 // FILD for other targets.
328 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
331 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
333 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
334 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
336 if (!TM.Options.UseSoftFloat) {
337 // SSE has no i16 to fp conversion, only i32
338 if (X86ScalarSSEf32) {
339 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
340 // f32 and f64 cases are Legal, f80 case is not
341 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
343 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
344 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
347 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
351 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
352 // are Legal, f80 is custom lowered.
353 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
354 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
356 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
358 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
359 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
361 if (X86ScalarSSEf32) {
362 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
363 // f32 and f64 cases are Legal, f80 case is not
364 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
366 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
367 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
370 // Handle FP_TO_UINT by promoting the destination to a larger signed
372 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
373 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
374 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
376 if (Subtarget->is64Bit()) {
377 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
378 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
379 } else if (!TM.Options.UseSoftFloat) {
380 // Since AVX is a superset of SSE3, only check for SSE here.
381 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
382 // Expand FP_TO_UINT into a select.
383 // FIXME: We would like to use a Custom expander here eventually to do
384 // the optimal thing for SSE vs. the default expansion in the legalizer.
385 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
387 // With SSE3 we can use fisttpll to convert to a signed i64; without
388 // SSE, we're stuck with a fistpll.
389 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
392 if (isTargetFTOL()) {
393 // Use the _ftol2 runtime function, which has a pseudo-instruction
394 // to handle its weird calling convention.
395 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
398 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
399 if (!X86ScalarSSEf64) {
400 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
401 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
402 if (Subtarget->is64Bit()) {
403 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
404 // Without SSE, i64->f64 goes through memory.
405 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
409 // Scalar integer divide and remainder are lowered to use operations that
410 // produce two results, to match the available instructions. This exposes
411 // the two-result form to trivial CSE, which is able to combine x/y and x%y
412 // into a single instruction.
414 // Scalar integer multiply-high is also lowered to use two-result
415 // operations, to match the available instructions. However, plain multiply
416 // (low) operations are left as Legal, as there are single-result
417 // instructions for this in x86. Using the two-result multiply instructions
418 // when both high and low results are needed must be arranged by dagcombine.
419 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
421 setOperationAction(ISD::MULHS, VT, Expand);
422 setOperationAction(ISD::MULHU, VT, Expand);
423 setOperationAction(ISD::SDIV, VT, Expand);
424 setOperationAction(ISD::UDIV, VT, Expand);
425 setOperationAction(ISD::SREM, VT, Expand);
426 setOperationAction(ISD::UREM, VT, Expand);
428 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
429 setOperationAction(ISD::ADDC, VT, Custom);
430 setOperationAction(ISD::ADDE, VT, Custom);
431 setOperationAction(ISD::SUBC, VT, Custom);
432 setOperationAction(ISD::SUBE, VT, Custom);
435 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
436 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
437 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
438 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
439 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
444 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
445 if (Subtarget->is64Bit())
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
449 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
450 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
451 setOperationAction(ISD::FREM , MVT::f32 , Expand);
452 setOperationAction(ISD::FREM , MVT::f64 , Expand);
453 setOperationAction(ISD::FREM , MVT::f80 , Expand);
454 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
456 // Promote the i8 variants and force them on up to i32 which has a shorter
458 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
459 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
460 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
461 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
462 if (Subtarget->hasBMI()) {
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
464 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
468 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
469 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
470 if (Subtarget->is64Bit())
471 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
474 if (Subtarget->hasLZCNT()) {
475 // When promoting the i8 variants, force them to i32 for a shorter
477 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
478 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
479 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
480 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
482 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
483 if (Subtarget->is64Bit())
484 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
486 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
487 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
488 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
492 if (Subtarget->is64Bit()) {
493 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
494 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
498 if (Subtarget->hasPOPCNT()) {
499 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
501 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
502 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
503 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
504 if (Subtarget->is64Bit())
505 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
508 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
510 if (!Subtarget->hasMOVBE())
511 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
513 // These should be promoted to a larger select which is supported.
514 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
515 // X86 wants to expand cmov itself.
516 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
517 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
518 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
519 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
521 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
522 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
524 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
525 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
527 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
528 if (Subtarget->is64Bit()) {
529 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
530 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
532 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
533 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
534 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
535 // support continuation, user-level threading, and etc.. As a result, no
536 // other SjLj exception interfaces are implemented and please don't build
537 // your own exception handling based on them.
538 // LLVM/Clang supports zero-cost DWARF exception handling.
539 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
540 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
543 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
544 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
545 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
546 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
547 if (Subtarget->is64Bit())
548 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
549 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
550 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
551 if (Subtarget->is64Bit()) {
552 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
553 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
554 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
555 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
556 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
558 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
559 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
560 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
561 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
562 if (Subtarget->is64Bit()) {
563 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
564 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
565 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
568 if (Subtarget->hasSSE1())
569 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
571 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
573 // Expand certain atomics
574 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
576 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
577 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
578 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
581 if (!Subtarget->is64Bit()) {
582 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
596 if (Subtarget->hasCmpxchg16b()) {
597 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
600 // FIXME - use subtarget debug flags
601 if (!Subtarget->isTargetDarwin() &&
602 !Subtarget->isTargetELF() &&
603 !Subtarget->isTargetCygMing()) {
604 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
607 if (Subtarget->is64Bit()) {
608 setExceptionPointerRegister(X86::RAX);
609 setExceptionSelectorRegister(X86::RDX);
611 setExceptionPointerRegister(X86::EAX);
612 setExceptionSelectorRegister(X86::EDX);
614 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
615 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
617 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
618 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
620 setOperationAction(ISD::TRAP, MVT::Other, Legal);
621 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
623 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
624 setOperationAction(ISD::VASTART , MVT::Other, Custom);
625 setOperationAction(ISD::VAEND , MVT::Other, Expand);
626 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
627 // TargetInfo::X86_64ABIBuiltinVaList
628 setOperationAction(ISD::VAARG , MVT::Other, Custom);
629 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
631 // TargetInfo::CharPtrBuiltinVaList
632 setOperationAction(ISD::VAARG , MVT::Other, Expand);
633 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
636 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
637 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
639 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640 MVT::i64 : MVT::i32, Custom);
642 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
643 // f32 and f64 use SSE.
644 // Set up the FP register classes.
645 addRegisterClass(MVT::f32, &X86::FR32RegClass);
646 addRegisterClass(MVT::f64, &X86::FR64RegClass);
648 // Use ANDPD to simulate FABS.
649 setOperationAction(ISD::FABS , MVT::f64, Custom);
650 setOperationAction(ISD::FABS , MVT::f32, Custom);
652 // Use XORP to simulate FNEG.
653 setOperationAction(ISD::FNEG , MVT::f64, Custom);
654 setOperationAction(ISD::FNEG , MVT::f32, Custom);
656 // Use ANDPD and ORPD to simulate FCOPYSIGN.
657 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
658 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
660 // Lower this to FGETSIGNx86 plus an AND.
661 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
662 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
664 // We don't support sin/cos/fmod
665 setOperationAction(ISD::FSIN , MVT::f64, Expand);
666 setOperationAction(ISD::FCOS , MVT::f64, Expand);
667 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
668 setOperationAction(ISD::FSIN , MVT::f32, Expand);
669 setOperationAction(ISD::FCOS , MVT::f32, Expand);
670 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
672 // Expand FP immediates into loads from the stack, except for the special
674 addLegalFPImmediate(APFloat(+0.0)); // xorpd
675 addLegalFPImmediate(APFloat(+0.0f)); // xorps
676 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
677 // Use SSE for f32, x87 for f64.
678 // Set up the FP register classes.
679 addRegisterClass(MVT::f32, &X86::FR32RegClass);
680 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
682 // Use ANDPS to simulate FABS.
683 setOperationAction(ISD::FABS , MVT::f32, Custom);
685 // Use XORP to simulate FNEG.
686 setOperationAction(ISD::FNEG , MVT::f32, Custom);
688 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
690 // Use ANDPS and ORPS to simulate FCOPYSIGN.
691 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
692 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
694 // We don't support sin/cos/fmod
695 setOperationAction(ISD::FSIN , MVT::f32, Expand);
696 setOperationAction(ISD::FCOS , MVT::f32, Expand);
697 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
699 // Special cases we handle for FP constants.
700 addLegalFPImmediate(APFloat(+0.0f)); // xorps
701 addLegalFPImmediate(APFloat(+0.0)); // FLD0
702 addLegalFPImmediate(APFloat(+1.0)); // FLD1
703 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
704 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
706 if (!TM.Options.UnsafeFPMath) {
707 setOperationAction(ISD::FSIN , MVT::f64, Expand);
708 setOperationAction(ISD::FCOS , MVT::f64, Expand);
709 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
711 } else if (!TM.Options.UseSoftFloat) {
712 // f32 and f64 in x87.
713 // Set up the FP register classes.
714 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
715 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
717 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
718 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
719 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
720 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
722 if (!TM.Options.UnsafeFPMath) {
723 setOperationAction(ISD::FSIN , MVT::f64, Expand);
724 setOperationAction(ISD::FSIN , MVT::f32, Expand);
725 setOperationAction(ISD::FCOS , MVT::f64, Expand);
726 setOperationAction(ISD::FCOS , MVT::f32, Expand);
727 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
728 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
730 addLegalFPImmediate(APFloat(+0.0)); // FLD0
731 addLegalFPImmediate(APFloat(+1.0)); // FLD1
732 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
733 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
734 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
735 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
736 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
737 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
740 // We don't support FMA.
741 setOperationAction(ISD::FMA, MVT::f64, Expand);
742 setOperationAction(ISD::FMA, MVT::f32, Expand);
744 // Long double always uses X87.
745 if (!TM.Options.UseSoftFloat) {
746 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
747 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
748 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
750 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
751 addLegalFPImmediate(TmpFlt); // FLD0
753 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
756 APFloat TmpFlt2(+1.0);
757 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
759 addLegalFPImmediate(TmpFlt2); // FLD1
760 TmpFlt2.changeSign();
761 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
764 if (!TM.Options.UnsafeFPMath) {
765 setOperationAction(ISD::FSIN , MVT::f80, Expand);
766 setOperationAction(ISD::FCOS , MVT::f80, Expand);
767 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
770 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
771 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
772 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
773 setOperationAction(ISD::FRINT, MVT::f80, Expand);
774 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
775 setOperationAction(ISD::FMA, MVT::f80, Expand);
778 // Always use a library call for pow.
779 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
780 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
781 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
783 setOperationAction(ISD::FLOG, MVT::f80, Expand);
784 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
785 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
786 setOperationAction(ISD::FEXP, MVT::f80, Expand);
787 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
789 // First set operation action for all vector types to either promote
790 // (for widening) or expand (for scalarization). Then we will selectively
791 // turn on ones that can be effectively codegen'd.
792 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
793 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
794 MVT VT = (MVT::SimpleValueType)i;
795 setOperationAction(ISD::ADD , VT, Expand);
796 setOperationAction(ISD::SUB , VT, Expand);
797 setOperationAction(ISD::FADD, VT, Expand);
798 setOperationAction(ISD::FNEG, VT, Expand);
799 setOperationAction(ISD::FSUB, VT, Expand);
800 setOperationAction(ISD::MUL , VT, Expand);
801 setOperationAction(ISD::FMUL, VT, Expand);
802 setOperationAction(ISD::SDIV, VT, Expand);
803 setOperationAction(ISD::UDIV, VT, Expand);
804 setOperationAction(ISD::FDIV, VT, Expand);
805 setOperationAction(ISD::SREM, VT, Expand);
806 setOperationAction(ISD::UREM, VT, Expand);
807 setOperationAction(ISD::LOAD, VT, Expand);
808 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
809 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
810 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
811 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
812 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
813 setOperationAction(ISD::FABS, VT, Expand);
814 setOperationAction(ISD::FSIN, VT, Expand);
815 setOperationAction(ISD::FSINCOS, VT, Expand);
816 setOperationAction(ISD::FCOS, VT, Expand);
817 setOperationAction(ISD::FSINCOS, VT, Expand);
818 setOperationAction(ISD::FREM, VT, Expand);
819 setOperationAction(ISD::FMA, VT, Expand);
820 setOperationAction(ISD::FPOWI, VT, Expand);
821 setOperationAction(ISD::FSQRT, VT, Expand);
822 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
823 setOperationAction(ISD::FFLOOR, VT, Expand);
824 setOperationAction(ISD::FCEIL, VT, Expand);
825 setOperationAction(ISD::FTRUNC, VT, Expand);
826 setOperationAction(ISD::FRINT, VT, Expand);
827 setOperationAction(ISD::FNEARBYINT, VT, Expand);
828 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
829 setOperationAction(ISD::MULHS, VT, Expand);
830 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
831 setOperationAction(ISD::MULHU, VT, Expand);
832 setOperationAction(ISD::SDIVREM, VT, Expand);
833 setOperationAction(ISD::UDIVREM, VT, Expand);
834 setOperationAction(ISD::FPOW, VT, Expand);
835 setOperationAction(ISD::CTPOP, VT, Expand);
836 setOperationAction(ISD::CTTZ, VT, Expand);
837 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838 setOperationAction(ISD::CTLZ, VT, Expand);
839 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840 setOperationAction(ISD::SHL, VT, Expand);
841 setOperationAction(ISD::SRA, VT, Expand);
842 setOperationAction(ISD::SRL, VT, Expand);
843 setOperationAction(ISD::ROTL, VT, Expand);
844 setOperationAction(ISD::ROTR, VT, Expand);
845 setOperationAction(ISD::BSWAP, VT, Expand);
846 setOperationAction(ISD::SETCC, VT, Expand);
847 setOperationAction(ISD::FLOG, VT, Expand);
848 setOperationAction(ISD::FLOG2, VT, Expand);
849 setOperationAction(ISD::FLOG10, VT, Expand);
850 setOperationAction(ISD::FEXP, VT, Expand);
851 setOperationAction(ISD::FEXP2, VT, Expand);
852 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857 setOperationAction(ISD::TRUNCATE, VT, Expand);
858 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861 setOperationAction(ISD::VSELECT, VT, Expand);
862 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864 setTruncStoreAction(VT,
865 (MVT::SimpleValueType)InnerVT, Expand);
866 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
871 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872 // with -msoft-float, disable use of MMX as well.
873 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875 // No operations on x86mmx supported, everything uses intrinsics.
878 // MMX-sized vectors (other than x86mmx) are expected to be expanded
879 // into smaller operations.
880 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
881 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
882 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
883 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
884 setOperationAction(ISD::AND, MVT::v8i8, Expand);
885 setOperationAction(ISD::AND, MVT::v4i16, Expand);
886 setOperationAction(ISD::AND, MVT::v2i32, Expand);
887 setOperationAction(ISD::AND, MVT::v1i64, Expand);
888 setOperationAction(ISD::OR, MVT::v8i8, Expand);
889 setOperationAction(ISD::OR, MVT::v4i16, Expand);
890 setOperationAction(ISD::OR, MVT::v2i32, Expand);
891 setOperationAction(ISD::OR, MVT::v1i64, Expand);
892 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
893 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
894 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
895 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
901 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
902 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
903 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
904 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
910 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
913 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
914 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
915 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
916 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
917 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
918 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
919 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
920 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
921 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
922 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
923 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
927 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
930 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931 // registers cannot be used even for integer operations.
932 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
937 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
938 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
939 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
940 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
941 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
942 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
943 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
944 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
945 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
946 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
947 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
948 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
949 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
950 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
951 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
952 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
953 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
954 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
955 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
956 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
957 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
959 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
960 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
961 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
962 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
964 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
965 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
970 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
971 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
972 MVT VT = (MVT::SimpleValueType)i;
973 // Do not attempt to custom lower non-power-of-2 vectors
974 if (!isPowerOf2_32(VT.getVectorNumElements()))
976 // Do not attempt to custom lower non-128-bit vectors
977 if (!VT.is128BitVector())
979 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
980 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
981 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
984 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
985 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
986 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
987 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
991 if (Subtarget->is64Bit()) {
992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
996 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
997 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
998 MVT VT = (MVT::SimpleValueType)i;
1000 // Do not attempt to promote non-128-bit vectors
1001 if (!VT.is128BitVector())
1004 setOperationAction(ISD::AND, VT, Promote);
1005 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1006 setOperationAction(ISD::OR, VT, Promote);
1007 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1008 setOperationAction(ISD::XOR, VT, Promote);
1009 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1010 setOperationAction(ISD::LOAD, VT, Promote);
1011 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1012 setOperationAction(ISD::SELECT, VT, Promote);
1013 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1016 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1018 // Custom lower v2i64 and v2f64 selects.
1019 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1020 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1021 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1022 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1024 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1025 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1027 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1028 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1029 // As there is no 64-bit GPR available, we need build a special custom
1030 // sequence to convert from v2i32 to v2f32.
1031 if (!Subtarget->is64Bit())
1032 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1034 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1035 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1037 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1040 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1041 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1042 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1043 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1044 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1045 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1046 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1047 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1048 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1049 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1050 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1052 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1055 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1057 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1058 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1059 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1060 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1061 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1063 // FIXME: Do we need to handle scalar-to-vector here?
1064 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1065 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
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);
1116 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1117 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1118 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1120 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1122 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1124 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1125 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1126 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1128 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1129 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1139 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1141 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1152 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1154 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1155 // even though v8i16 is a legal type.
1156 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1157 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1158 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1160 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1161 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1162 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1164 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1165 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1167 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1169 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1172 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1176 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1179 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1181 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1183 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1184 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1185 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1187 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1188 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1189 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1190 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1192 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1193 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1194 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1195 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1196 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1197 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1198 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1199 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1200 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1201 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1202 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1203 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1205 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1206 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1207 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1208 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1209 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1210 setOperationAction(ISD::FMA, MVT::f32, Legal);
1211 setOperationAction(ISD::FMA, MVT::f64, Legal);
1214 if (Subtarget->hasInt256()) {
1215 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1216 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1217 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1218 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1220 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1221 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1222 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1223 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1225 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1226 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1227 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1228 // Don't lower v32i8 because there is no 128-bit byte mul
1230 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1231 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1232 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1233 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1235 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1237 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1238 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1239 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1240 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1242 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1243 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1244 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1245 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1247 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1248 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1249 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1250 // Don't lower v32i8 because there is no 128-bit byte mul
1253 // In the customized shift lowering, the legal cases in AVX2 will be
1255 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1256 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1258 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1259 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1261 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1263 // Custom lower several nodes for 256-bit types.
1264 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1265 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1266 MVT VT = (MVT::SimpleValueType)i;
1268 // Extract subvector is special because the value type
1269 // (result) is 128-bit but the source is 256-bit wide.
1270 if (VT.is128BitVector())
1271 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1273 // Do not attempt to custom lower other non-256-bit vectors
1274 if (!VT.is256BitVector())
1277 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1278 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1279 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1280 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1281 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1282 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1283 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1286 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1287 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1288 MVT VT = (MVT::SimpleValueType)i;
1290 // Do not attempt to promote non-256-bit vectors
1291 if (!VT.is256BitVector())
1294 setOperationAction(ISD::AND, VT, Promote);
1295 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1296 setOperationAction(ISD::OR, VT, Promote);
1297 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1298 setOperationAction(ISD::XOR, VT, Promote);
1299 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1300 setOperationAction(ISD::LOAD, VT, Promote);
1301 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1302 setOperationAction(ISD::SELECT, VT, Promote);
1303 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1307 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1308 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1309 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1310 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1311 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1313 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1314 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1315 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1317 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1318 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1319 setOperationAction(ISD::XOR, MVT::i1, Legal);
1320 setOperationAction(ISD::OR, MVT::i1, Legal);
1321 setOperationAction(ISD::AND, MVT::i1, Legal);
1322 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1323 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1324 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1325 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1326 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1327 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1329 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1330 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1331 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1332 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1333 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1334 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1336 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1337 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1338 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1340 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1341 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1342 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1343 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1345 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1346 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1347 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1348 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1349 if (Subtarget->is64Bit()) {
1350 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1351 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1352 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1353 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1355 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1356 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1357 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1358 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1359 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1360 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1361 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1362 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1363 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1364 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1366 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1367 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1368 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1369 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1372 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1373 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1374 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1375 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1376 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1377 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1378 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1380 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1381 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1383 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1384 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1387 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1388 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1390 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1393 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1396 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1397 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1398 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1399 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1400 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1402 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1403 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1405 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1406 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1408 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1410 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1411 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1413 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1414 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1416 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1417 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1419 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1420 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1421 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1422 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1423 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1424 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1426 // Custom lower several nodes.
1427 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1428 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1429 MVT VT = (MVT::SimpleValueType)i;
1431 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1432 // Extract subvector is special because the value type
1433 // (result) is 256/128-bit but the source is 512-bit wide.
1434 if (VT.is128BitVector() || VT.is256BitVector())
1435 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1437 if (VT.getVectorElementType() == MVT::i1)
1438 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1440 // Do not attempt to custom lower other non-512-bit vectors
1441 if (!VT.is512BitVector())
1444 if ( EltSize >= 32) {
1445 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1446 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1447 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1448 setOperationAction(ISD::VSELECT, VT, Legal);
1449 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1450 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1451 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1454 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1455 MVT VT = (MVT::SimpleValueType)i;
1457 // Do not attempt to promote non-256-bit vectors
1458 if (!VT.is512BitVector())
1461 setOperationAction(ISD::SELECT, VT, Promote);
1462 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1466 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1467 // of this type with custom code.
1468 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1469 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1470 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1474 // We want to custom lower some of our intrinsics.
1475 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1477 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1478 if (!Subtarget->is64Bit())
1479 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1481 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1482 // handle type legalization for these operations here.
1484 // FIXME: We really should do custom legalization for addition and
1485 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1486 // than generic legalization for 64-bit multiplication-with-overflow, though.
1487 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1488 // Add/Sub/Mul with overflow operations are custom lowered.
1490 setOperationAction(ISD::SADDO, VT, Custom);
1491 setOperationAction(ISD::UADDO, VT, Custom);
1492 setOperationAction(ISD::SSUBO, VT, Custom);
1493 setOperationAction(ISD::USUBO, VT, Custom);
1494 setOperationAction(ISD::SMULO, VT, Custom);
1495 setOperationAction(ISD::UMULO, VT, Custom);
1498 // There are no 8-bit 3-address imul/mul instructions
1499 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1500 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1502 if (!Subtarget->is64Bit()) {
1503 // These libcalls are not available in 32-bit.
1504 setLibcallName(RTLIB::SHL_I128, nullptr);
1505 setLibcallName(RTLIB::SRL_I128, nullptr);
1506 setLibcallName(RTLIB::SRA_I128, nullptr);
1509 // Combine sin / cos into one node or libcall if possible.
1510 if (Subtarget->hasSinCos()) {
1511 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1512 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1513 if (Subtarget->isTargetDarwin()) {
1514 // For MacOSX, we don't want to the normal expansion of a libcall to
1515 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1517 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1518 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1522 // We have target-specific dag combine patterns for the following nodes:
1523 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1524 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1525 setTargetDAGCombine(ISD::VSELECT);
1526 setTargetDAGCombine(ISD::SELECT);
1527 setTargetDAGCombine(ISD::SHL);
1528 setTargetDAGCombine(ISD::SRA);
1529 setTargetDAGCombine(ISD::SRL);
1530 setTargetDAGCombine(ISD::OR);
1531 setTargetDAGCombine(ISD::AND);
1532 setTargetDAGCombine(ISD::ADD);
1533 setTargetDAGCombine(ISD::FADD);
1534 setTargetDAGCombine(ISD::FSUB);
1535 setTargetDAGCombine(ISD::FMA);
1536 setTargetDAGCombine(ISD::SUB);
1537 setTargetDAGCombine(ISD::LOAD);
1538 setTargetDAGCombine(ISD::STORE);
1539 setTargetDAGCombine(ISD::ZERO_EXTEND);
1540 setTargetDAGCombine(ISD::ANY_EXTEND);
1541 setTargetDAGCombine(ISD::SIGN_EXTEND);
1542 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1543 setTargetDAGCombine(ISD::TRUNCATE);
1544 setTargetDAGCombine(ISD::SINT_TO_FP);
1545 setTargetDAGCombine(ISD::SETCC);
1546 if (Subtarget->is64Bit())
1547 setTargetDAGCombine(ISD::MUL);
1548 setTargetDAGCombine(ISD::XOR);
1550 computeRegisterProperties();
1552 // On Darwin, -Os means optimize for size without hurting performance,
1553 // do not reduce the limit.
1554 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1555 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1556 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1557 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1558 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1559 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1560 setPrefLoopAlignment(4); // 2^4 bytes.
1562 // Predictable cmov don't hurt on atom because it's in-order.
1563 PredictableSelectIsExpensive = !Subtarget->isAtom();
1565 setPrefFunctionAlignment(4); // 2^4 bytes.
1568 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1570 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1572 if (Subtarget->hasAVX512())
1573 switch(VT.getVectorNumElements()) {
1574 case 8: return MVT::v8i1;
1575 case 16: return MVT::v16i1;
1578 return VT.changeVectorElementTypeToInteger();
1581 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1582 /// the desired ByVal argument alignment.
1583 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1586 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1587 if (VTy->getBitWidth() == 128)
1589 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1590 unsigned EltAlign = 0;
1591 getMaxByValAlign(ATy->getElementType(), EltAlign);
1592 if (EltAlign > MaxAlign)
1593 MaxAlign = EltAlign;
1594 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1595 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1596 unsigned EltAlign = 0;
1597 getMaxByValAlign(STy->getElementType(i), EltAlign);
1598 if (EltAlign > MaxAlign)
1599 MaxAlign = EltAlign;
1606 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1607 /// function arguments in the caller parameter area. For X86, aggregates
1608 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1609 /// are at 4-byte boundaries.
1610 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1611 if (Subtarget->is64Bit()) {
1612 // Max of 8 and alignment of type.
1613 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1620 if (Subtarget->hasSSE1())
1621 getMaxByValAlign(Ty, Align);
1625 /// getOptimalMemOpType - Returns the target specific optimal type for load
1626 /// and store operations as a result of memset, memcpy, and memmove
1627 /// lowering. If DstAlign is zero that means it's safe to destination
1628 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1629 /// means there isn't a need to check it against alignment requirement,
1630 /// probably because the source does not need to be loaded. If 'IsMemset' is
1631 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1632 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1633 /// source is constant so it does not need to be loaded.
1634 /// It returns EVT::Other if the type should be determined using generic
1635 /// target-independent logic.
1637 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1638 unsigned DstAlign, unsigned SrcAlign,
1639 bool IsMemset, bool ZeroMemset,
1641 MachineFunction &MF) const {
1642 const Function *F = MF.getFunction();
1643 if ((!IsMemset || ZeroMemset) &&
1644 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1645 Attribute::NoImplicitFloat)) {
1647 (Subtarget->isUnalignedMemAccessFast() ||
1648 ((DstAlign == 0 || DstAlign >= 16) &&
1649 (SrcAlign == 0 || SrcAlign >= 16)))) {
1651 if (Subtarget->hasInt256())
1653 if (Subtarget->hasFp256())
1656 if (Subtarget->hasSSE2())
1658 if (Subtarget->hasSSE1())
1660 } else if (!MemcpyStrSrc && Size >= 8 &&
1661 !Subtarget->is64Bit() &&
1662 Subtarget->hasSSE2()) {
1663 // Do not use f64 to lower memcpy if source is string constant. It's
1664 // better to use i32 to avoid the loads.
1668 if (Subtarget->is64Bit() && Size >= 8)
1673 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1675 return X86ScalarSSEf32;
1676 else if (VT == MVT::f64)
1677 return X86ScalarSSEf64;
1682 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1686 *Fast = Subtarget->isUnalignedMemAccessFast();
1690 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1691 /// current function. The returned value is a member of the
1692 /// MachineJumpTableInfo::JTEntryKind enum.
1693 unsigned X86TargetLowering::getJumpTableEncoding() const {
1694 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1696 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1697 Subtarget->isPICStyleGOT())
1698 return MachineJumpTableInfo::EK_Custom32;
1700 // Otherwise, use the normal jump table encoding heuristics.
1701 return TargetLowering::getJumpTableEncoding();
1705 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1706 const MachineBasicBlock *MBB,
1707 unsigned uid,MCContext &Ctx) const{
1708 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1709 Subtarget->isPICStyleGOT());
1710 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1712 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1713 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1716 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1718 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1719 SelectionDAG &DAG) const {
1720 if (!Subtarget->is64Bit())
1721 // This doesn't have SDLoc associated with it, but is not really the
1722 // same as a Register.
1723 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1727 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1728 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1730 const MCExpr *X86TargetLowering::
1731 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1732 MCContext &Ctx) const {
1733 // X86-64 uses RIP relative addressing based on the jump table label.
1734 if (Subtarget->isPICStyleRIPRel())
1735 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1737 // Otherwise, the reference is relative to the PIC base.
1738 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1741 // FIXME: Why this routine is here? Move to RegInfo!
1742 std::pair<const TargetRegisterClass*, uint8_t>
1743 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1744 const TargetRegisterClass *RRC = nullptr;
1746 switch (VT.SimpleTy) {
1748 return TargetLowering::findRepresentativeClass(VT);
1749 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1750 RRC = Subtarget->is64Bit() ?
1751 (const TargetRegisterClass*)&X86::GR64RegClass :
1752 (const TargetRegisterClass*)&X86::GR32RegClass;
1755 RRC = &X86::VR64RegClass;
1757 case MVT::f32: case MVT::f64:
1758 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1759 case MVT::v4f32: case MVT::v2f64:
1760 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1762 RRC = &X86::VR128RegClass;
1765 return std::make_pair(RRC, Cost);
1768 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1769 unsigned &Offset) const {
1770 if (!Subtarget->isTargetLinux())
1773 if (Subtarget->is64Bit()) {
1774 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1776 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1788 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1789 unsigned DestAS) const {
1790 assert(SrcAS != DestAS && "Expected different address spaces!");
1792 return SrcAS < 256 && DestAS < 256;
1795 //===----------------------------------------------------------------------===//
1796 // Return Value Calling Convention Implementation
1797 //===----------------------------------------------------------------------===//
1799 #include "X86GenCallingConv.inc"
1802 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1803 MachineFunction &MF, bool isVarArg,
1804 const SmallVectorImpl<ISD::OutputArg> &Outs,
1805 LLVMContext &Context) const {
1806 SmallVector<CCValAssign, 16> RVLocs;
1807 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1809 return CCInfo.CheckReturn(Outs, RetCC_X86);
1812 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1813 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1818 X86TargetLowering::LowerReturn(SDValue Chain,
1819 CallingConv::ID CallConv, bool isVarArg,
1820 const SmallVectorImpl<ISD::OutputArg> &Outs,
1821 const SmallVectorImpl<SDValue> &OutVals,
1822 SDLoc dl, SelectionDAG &DAG) const {
1823 MachineFunction &MF = DAG.getMachineFunction();
1824 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1826 SmallVector<CCValAssign, 16> RVLocs;
1827 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1828 RVLocs, *DAG.getContext());
1829 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1832 SmallVector<SDValue, 6> RetOps;
1833 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1834 // Operand #1 = Bytes To Pop
1835 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1838 // Copy the result values into the output registers.
1839 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1840 CCValAssign &VA = RVLocs[i];
1841 assert(VA.isRegLoc() && "Can only return in registers!");
1842 SDValue ValToCopy = OutVals[i];
1843 EVT ValVT = ValToCopy.getValueType();
1845 // Promote values to the appropriate types
1846 if (VA.getLocInfo() == CCValAssign::SExt)
1847 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1848 else if (VA.getLocInfo() == CCValAssign::ZExt)
1849 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1850 else if (VA.getLocInfo() == CCValAssign::AExt)
1851 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1852 else if (VA.getLocInfo() == CCValAssign::BCvt)
1853 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1855 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1856 "Unexpected FP-extend for return value.");
1858 // If this is x86-64, and we disabled SSE, we can't return FP values,
1859 // or SSE or MMX vectors.
1860 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1861 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1862 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1863 report_fatal_error("SSE register return with SSE disabled");
1865 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1866 // llvm-gcc has never done it right and no one has noticed, so this
1867 // should be OK for now.
1868 if (ValVT == MVT::f64 &&
1869 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1870 report_fatal_error("SSE2 register return with SSE2 disabled");
1872 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1873 // the RET instruction and handled by the FP Stackifier.
1874 if (VA.getLocReg() == X86::ST0 ||
1875 VA.getLocReg() == X86::ST1) {
1876 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1877 // change the value to the FP stack register class.
1878 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1879 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1880 RetOps.push_back(ValToCopy);
1881 // Don't emit a copytoreg.
1885 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1886 // which is returned in RAX / RDX.
1887 if (Subtarget->is64Bit()) {
1888 if (ValVT == MVT::x86mmx) {
1889 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1890 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1891 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1893 // If we don't have SSE2 available, convert to v4f32 so the generated
1894 // register is legal.
1895 if (!Subtarget->hasSSE2())
1896 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1901 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1902 Flag = Chain.getValue(1);
1903 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1906 // The x86-64 ABIs require that for returning structs by value we copy
1907 // the sret argument into %rax/%eax (depending on ABI) for the return.
1908 // Win32 requires us to put the sret argument to %eax as well.
1909 // We saved the argument into a virtual register in the entry block,
1910 // so now we copy the value out and into %rax/%eax.
1911 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1912 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1913 MachineFunction &MF = DAG.getMachineFunction();
1914 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1915 unsigned Reg = FuncInfo->getSRetReturnReg();
1917 "SRetReturnReg should have been set in LowerFormalArguments().");
1918 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1921 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1922 X86::RAX : X86::EAX;
1923 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1924 Flag = Chain.getValue(1);
1926 // RAX/EAX now acts like a return value.
1927 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1930 RetOps[0] = Chain; // Update chain.
1932 // Add the flag if we have it.
1934 RetOps.push_back(Flag);
1936 return DAG.getNode(X86ISD::RET_FLAG, dl,
1937 MVT::Other, &RetOps[0], RetOps.size());
1940 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1941 if (N->getNumValues() != 1)
1943 if (!N->hasNUsesOfValue(1, 0))
1946 SDValue TCChain = Chain;
1947 SDNode *Copy = *N->use_begin();
1948 if (Copy->getOpcode() == ISD::CopyToReg) {
1949 // If the copy has a glue operand, we conservatively assume it isn't safe to
1950 // perform a tail call.
1951 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1953 TCChain = Copy->getOperand(0);
1954 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1957 bool HasRet = false;
1958 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1960 if (UI->getOpcode() != X86ISD::RET_FLAG)
1973 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1974 ISD::NodeType ExtendKind) const {
1976 // TODO: Is this also valid on 32-bit?
1977 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1978 ReturnMVT = MVT::i8;
1980 ReturnMVT = MVT::i32;
1982 MVT MinVT = getRegisterType(ReturnMVT);
1983 return VT.bitsLT(MinVT) ? MinVT : VT;
1986 /// LowerCallResult - Lower the result values of a call into the
1987 /// appropriate copies out of appropriate physical registers.
1990 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1991 CallingConv::ID CallConv, bool isVarArg,
1992 const SmallVectorImpl<ISD::InputArg> &Ins,
1993 SDLoc dl, SelectionDAG &DAG,
1994 SmallVectorImpl<SDValue> &InVals) const {
1996 // Assign locations to each value returned by this call.
1997 SmallVector<CCValAssign, 16> RVLocs;
1998 bool Is64Bit = Subtarget->is64Bit();
1999 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2000 getTargetMachine(), RVLocs, *DAG.getContext());
2001 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2003 // Copy all of the result registers out of their specified physreg.
2004 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2005 CCValAssign &VA = RVLocs[i];
2006 EVT CopyVT = VA.getValVT();
2008 // If this is x86-64, and we disabled SSE, we can't return FP values
2009 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2010 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2011 report_fatal_error("SSE register return with SSE disabled");
2016 // If this is a call to a function that returns an fp value on the floating
2017 // point stack, we must guarantee the value is popped from the stack, so
2018 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2019 // if the return value is not used. We use the FpPOP_RETVAL instruction
2021 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2022 // If we prefer to use the value in xmm registers, copy it out as f80 and
2023 // use a truncate to move it from fp stack reg to xmm reg.
2024 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2025 SDValue Ops[] = { Chain, InFlag };
2026 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2027 MVT::Other, MVT::Glue, Ops), 1);
2028 Val = Chain.getValue(0);
2030 // Round the f80 to the right size, which also moves it to the appropriate
2032 if (CopyVT != VA.getValVT())
2033 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2034 // This truncation won't change the value.
2035 DAG.getIntPtrConstant(1));
2037 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2038 CopyVT, InFlag).getValue(1);
2039 Val = Chain.getValue(0);
2041 InFlag = Chain.getValue(2);
2042 InVals.push_back(Val);
2048 //===----------------------------------------------------------------------===//
2049 // C & StdCall & Fast Calling Convention implementation
2050 //===----------------------------------------------------------------------===//
2051 // StdCall calling convention seems to be standard for many Windows' API
2052 // routines and around. It differs from C calling convention just a little:
2053 // callee should clean up the stack, not caller. Symbols should be also
2054 // decorated in some fancy way :) It doesn't support any vector arguments.
2055 // For info on fast calling convention see Fast Calling Convention (tail call)
2056 // implementation LowerX86_32FastCCCallTo.
2058 /// CallIsStructReturn - Determines whether a call uses struct return
2060 enum StructReturnType {
2065 static StructReturnType
2066 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2068 return NotStructReturn;
2070 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2071 if (!Flags.isSRet())
2072 return NotStructReturn;
2073 if (Flags.isInReg())
2074 return RegStructReturn;
2075 return StackStructReturn;
2078 /// ArgsAreStructReturn - Determines whether a function uses struct
2079 /// return semantics.
2080 static StructReturnType
2081 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2083 return NotStructReturn;
2085 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2086 if (!Flags.isSRet())
2087 return NotStructReturn;
2088 if (Flags.isInReg())
2089 return RegStructReturn;
2090 return StackStructReturn;
2093 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2094 /// by "Src" to address "Dst" with size and alignment information specified by
2095 /// the specific parameter attribute. The copy will be passed as a byval
2096 /// function parameter.
2098 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2099 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2101 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2103 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2104 /*isVolatile*/false, /*AlwaysInline=*/true,
2105 MachinePointerInfo(), MachinePointerInfo());
2108 /// IsTailCallConvention - Return true if the calling convention is one that
2109 /// supports tail call optimization.
2110 static bool IsTailCallConvention(CallingConv::ID CC) {
2111 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2112 CC == CallingConv::HiPE);
2115 /// \brief Return true if the calling convention is a C calling convention.
2116 static bool IsCCallConvention(CallingConv::ID CC) {
2117 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2118 CC == CallingConv::X86_64_SysV);
2121 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2122 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2126 CallingConv::ID CalleeCC = CS.getCallingConv();
2127 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2133 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2134 /// a tailcall target by changing its ABI.
2135 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2136 bool GuaranteedTailCallOpt) {
2137 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2141 X86TargetLowering::LowerMemArgument(SDValue Chain,
2142 CallingConv::ID CallConv,
2143 const SmallVectorImpl<ISD::InputArg> &Ins,
2144 SDLoc dl, SelectionDAG &DAG,
2145 const CCValAssign &VA,
2146 MachineFrameInfo *MFI,
2148 // Create the nodes corresponding to a load from this parameter slot.
2149 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2150 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2151 getTargetMachine().Options.GuaranteedTailCallOpt);
2152 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2155 // If value is passed by pointer we have address passed instead of the value
2157 if (VA.getLocInfo() == CCValAssign::Indirect)
2158 ValVT = VA.getLocVT();
2160 ValVT = VA.getValVT();
2162 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2163 // changed with more analysis.
2164 // In case of tail call optimization mark all arguments mutable. Since they
2165 // could be overwritten by lowering of arguments in case of a tail call.
2166 if (Flags.isByVal()) {
2167 unsigned Bytes = Flags.getByValSize();
2168 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2169 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2170 return DAG.getFrameIndex(FI, getPointerTy());
2172 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2173 VA.getLocMemOffset(), isImmutable);
2174 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2175 return DAG.getLoad(ValVT, dl, Chain, FIN,
2176 MachinePointerInfo::getFixedStack(FI),
2177 false, false, false, 0);
2182 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2183 CallingConv::ID CallConv,
2185 const SmallVectorImpl<ISD::InputArg> &Ins,
2188 SmallVectorImpl<SDValue> &InVals)
2190 MachineFunction &MF = DAG.getMachineFunction();
2191 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2193 const Function* Fn = MF.getFunction();
2194 if (Fn->hasExternalLinkage() &&
2195 Subtarget->isTargetCygMing() &&
2196 Fn->getName() == "main")
2197 FuncInfo->setForceFramePointer(true);
2199 MachineFrameInfo *MFI = MF.getFrameInfo();
2200 bool Is64Bit = Subtarget->is64Bit();
2201 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2203 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2204 "Var args not supported with calling convention fastcc, ghc or hipe");
2206 // Assign locations to all of the incoming arguments.
2207 SmallVector<CCValAssign, 16> ArgLocs;
2208 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2209 ArgLocs, *DAG.getContext());
2211 // Allocate shadow area for Win64
2213 CCInfo.AllocateStack(32, 8);
2215 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2217 unsigned LastVal = ~0U;
2219 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2220 CCValAssign &VA = ArgLocs[i];
2221 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2223 assert(VA.getValNo() != LastVal &&
2224 "Don't support value assigned to multiple locs yet");
2226 LastVal = VA.getValNo();
2228 if (VA.isRegLoc()) {
2229 EVT RegVT = VA.getLocVT();
2230 const TargetRegisterClass *RC;
2231 if (RegVT == MVT::i32)
2232 RC = &X86::GR32RegClass;
2233 else if (Is64Bit && RegVT == MVT::i64)
2234 RC = &X86::GR64RegClass;
2235 else if (RegVT == MVT::f32)
2236 RC = &X86::FR32RegClass;
2237 else if (RegVT == MVT::f64)
2238 RC = &X86::FR64RegClass;
2239 else if (RegVT.is512BitVector())
2240 RC = &X86::VR512RegClass;
2241 else if (RegVT.is256BitVector())
2242 RC = &X86::VR256RegClass;
2243 else if (RegVT.is128BitVector())
2244 RC = &X86::VR128RegClass;
2245 else if (RegVT == MVT::x86mmx)
2246 RC = &X86::VR64RegClass;
2247 else if (RegVT == MVT::i1)
2248 RC = &X86::VK1RegClass;
2249 else if (RegVT == MVT::v8i1)
2250 RC = &X86::VK8RegClass;
2251 else if (RegVT == MVT::v16i1)
2252 RC = &X86::VK16RegClass;
2254 llvm_unreachable("Unknown argument type!");
2256 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2257 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2259 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2260 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2262 if (VA.getLocInfo() == CCValAssign::SExt)
2263 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2264 DAG.getValueType(VA.getValVT()));
2265 else if (VA.getLocInfo() == CCValAssign::ZExt)
2266 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2267 DAG.getValueType(VA.getValVT()));
2268 else if (VA.getLocInfo() == CCValAssign::BCvt)
2269 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2271 if (VA.isExtInLoc()) {
2272 // Handle MMX values passed in XMM regs.
2273 if (RegVT.isVector())
2274 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2276 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2279 assert(VA.isMemLoc());
2280 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2283 // If value is passed via pointer - do a load.
2284 if (VA.getLocInfo() == CCValAssign::Indirect)
2285 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2286 MachinePointerInfo(), false, false, false, 0);
2288 InVals.push_back(ArgValue);
2291 // The x86-64 ABIs require that for returning structs by value we copy
2292 // the sret argument into %rax/%eax (depending on ABI) for the return.
2293 // Win32 requires us to put the sret argument to %eax as well.
2294 // Save the argument into a virtual register so that we can access it
2295 // from the return points.
2296 if (MF.getFunction()->hasStructRetAttr() &&
2297 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2298 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2299 unsigned Reg = FuncInfo->getSRetReturnReg();
2301 MVT PtrTy = getPointerTy();
2302 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2303 FuncInfo->setSRetReturnReg(Reg);
2305 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2306 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2309 unsigned StackSize = CCInfo.getNextStackOffset();
2310 // Align stack specially for tail calls.
2311 if (FuncIsMadeTailCallSafe(CallConv,
2312 MF.getTarget().Options.GuaranteedTailCallOpt))
2313 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2315 // If the function takes variable number of arguments, make a frame index for
2316 // the start of the first vararg value... for expansion of llvm.va_start.
2318 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2319 CallConv != CallingConv::X86_ThisCall)) {
2320 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2323 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2325 // FIXME: We should really autogenerate these arrays
2326 static const MCPhysReg GPR64ArgRegsWin64[] = {
2327 X86::RCX, X86::RDX, X86::R8, X86::R9
2329 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2330 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2332 static const MCPhysReg XMMArgRegs64Bit[] = {
2333 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2334 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2336 const MCPhysReg *GPR64ArgRegs;
2337 unsigned NumXMMRegs = 0;
2340 // The XMM registers which might contain var arg parameters are shadowed
2341 // in their paired GPR. So we only need to save the GPR to their home
2343 TotalNumIntRegs = 4;
2344 GPR64ArgRegs = GPR64ArgRegsWin64;
2346 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2347 GPR64ArgRegs = GPR64ArgRegs64Bit;
2349 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2352 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2355 bool NoImplicitFloatOps = Fn->getAttributes().
2356 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2357 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2358 "SSE register cannot be used when SSE is disabled!");
2359 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2360 NoImplicitFloatOps) &&
2361 "SSE register cannot be used when SSE is disabled!");
2362 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2363 !Subtarget->hasSSE1())
2364 // Kernel mode asks for SSE to be disabled, so don't push them
2366 TotalNumXMMRegs = 0;
2369 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2370 // Get to the caller-allocated home save location. Add 8 to account
2371 // for the return address.
2372 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2373 FuncInfo->setRegSaveFrameIndex(
2374 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2375 // Fixup to set vararg frame on shadow area (4 x i64).
2377 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2379 // For X86-64, if there are vararg parameters that are passed via
2380 // registers, then we must store them to their spots on the stack so
2381 // they may be loaded by deferencing the result of va_next.
2382 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2383 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2384 FuncInfo->setRegSaveFrameIndex(
2385 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2389 // Store the integer parameter registers.
2390 SmallVector<SDValue, 8> MemOps;
2391 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2393 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2394 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2395 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2396 DAG.getIntPtrConstant(Offset));
2397 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2398 &X86::GR64RegClass);
2399 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2401 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2402 MachinePointerInfo::getFixedStack(
2403 FuncInfo->getRegSaveFrameIndex(), Offset),
2405 MemOps.push_back(Store);
2409 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2410 // Now store the XMM (fp + vector) parameter registers.
2411 SmallVector<SDValue, 11> SaveXMMOps;
2412 SaveXMMOps.push_back(Chain);
2414 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2415 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2416 SaveXMMOps.push_back(ALVal);
2418 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2419 FuncInfo->getRegSaveFrameIndex()));
2420 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2421 FuncInfo->getVarArgsFPOffset()));
2423 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2424 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2425 &X86::VR128RegClass);
2426 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2427 SaveXMMOps.push_back(Val);
2429 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2431 &SaveXMMOps[0], SaveXMMOps.size()));
2434 if (!MemOps.empty())
2435 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2436 &MemOps[0], MemOps.size());
2440 // Some CCs need callee pop.
2441 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2442 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2443 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2445 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2446 // If this is an sret function, the return should pop the hidden pointer.
2447 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2448 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2449 argsAreStructReturn(Ins) == StackStructReturn)
2450 FuncInfo->setBytesToPopOnReturn(4);
2454 // RegSaveFrameIndex is X86-64 only.
2455 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2456 if (CallConv == CallingConv::X86_FastCall ||
2457 CallConv == CallingConv::X86_ThisCall)
2458 // fastcc functions can't have varargs.
2459 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2462 FuncInfo->setArgumentStackSize(StackSize);
2468 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2469 SDValue StackPtr, SDValue Arg,
2470 SDLoc dl, SelectionDAG &DAG,
2471 const CCValAssign &VA,
2472 ISD::ArgFlagsTy Flags) const {
2473 unsigned LocMemOffset = VA.getLocMemOffset();
2474 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2475 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2476 if (Flags.isByVal())
2477 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2479 return DAG.getStore(Chain, dl, Arg, PtrOff,
2480 MachinePointerInfo::getStack(LocMemOffset),
2484 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2485 /// optimization is performed and it is required.
2487 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2488 SDValue &OutRetAddr, SDValue Chain,
2489 bool IsTailCall, bool Is64Bit,
2490 int FPDiff, SDLoc dl) const {
2491 // Adjust the Return address stack slot.
2492 EVT VT = getPointerTy();
2493 OutRetAddr = getReturnAddressFrameIndex(DAG);
2495 // Load the "old" Return address.
2496 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2497 false, false, false, 0);
2498 return SDValue(OutRetAddr.getNode(), 1);
2501 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2502 /// optimization is performed and it is required (FPDiff!=0).
2504 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2505 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2506 unsigned SlotSize, int FPDiff, SDLoc dl) {
2507 // Store the return address to the appropriate stack slot.
2508 if (!FPDiff) return Chain;
2509 // Calculate the new stack slot for the return address.
2510 int NewReturnAddrFI =
2511 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2513 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2514 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2515 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2521 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2522 SmallVectorImpl<SDValue> &InVals) const {
2523 SelectionDAG &DAG = CLI.DAG;
2525 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2526 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2527 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2528 SDValue Chain = CLI.Chain;
2529 SDValue Callee = CLI.Callee;
2530 CallingConv::ID CallConv = CLI.CallConv;
2531 bool &isTailCall = CLI.IsTailCall;
2532 bool isVarArg = CLI.IsVarArg;
2534 MachineFunction &MF = DAG.getMachineFunction();
2535 bool Is64Bit = Subtarget->is64Bit();
2536 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2537 StructReturnType SR = callIsStructReturn(Outs);
2538 bool IsSibcall = false;
2540 if (MF.getTarget().Options.DisableTailCalls)
2544 // Check if it's really possible to do a tail call.
2545 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2546 isVarArg, SR != NotStructReturn,
2547 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2548 Outs, OutVals, Ins, DAG);
2550 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2551 report_fatal_error("failed to perform tail call elimination on a call "
2552 "site marked musttail");
2554 // Sibcalls are automatically detected tailcalls which do not require
2556 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2563 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2564 "Var args not supported with calling convention fastcc, ghc or hipe");
2566 // Analyze operands of the call, assigning locations to each operand.
2567 SmallVector<CCValAssign, 16> ArgLocs;
2568 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2569 ArgLocs, *DAG.getContext());
2571 // Allocate shadow area for Win64
2573 CCInfo.AllocateStack(32, 8);
2575 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2577 // Get a count of how many bytes are to be pushed on the stack.
2578 unsigned NumBytes = CCInfo.getNextStackOffset();
2580 // This is a sibcall. The memory operands are available in caller's
2581 // own caller's stack.
2583 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2584 IsTailCallConvention(CallConv))
2585 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2588 if (isTailCall && !IsSibcall) {
2589 // Lower arguments at fp - stackoffset + fpdiff.
2590 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2591 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2593 FPDiff = NumBytesCallerPushed - NumBytes;
2595 // Set the delta of movement of the returnaddr stackslot.
2596 // But only set if delta is greater than previous delta.
2597 if (FPDiff < X86Info->getTCReturnAddrDelta())
2598 X86Info->setTCReturnAddrDelta(FPDiff);
2601 unsigned NumBytesToPush = NumBytes;
2602 unsigned NumBytesToPop = NumBytes;
2604 // If we have an inalloca argument, all stack space has already been allocated
2605 // for us and be right at the top of the stack. We don't support multiple
2606 // arguments passed in memory when using inalloca.
2607 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2609 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2610 "an inalloca argument must be the only memory argument");
2614 Chain = DAG.getCALLSEQ_START(
2615 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2617 SDValue RetAddrFrIdx;
2618 // Load return address for tail calls.
2619 if (isTailCall && FPDiff)
2620 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2621 Is64Bit, FPDiff, dl);
2623 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2624 SmallVector<SDValue, 8> MemOpChains;
2627 // Walk the register/memloc assignments, inserting copies/loads. In the case
2628 // of tail call optimization arguments are handle later.
2629 const X86RegisterInfo *RegInfo =
2630 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2631 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2632 // Skip inalloca arguments, they have already been written.
2633 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2634 if (Flags.isInAlloca())
2637 CCValAssign &VA = ArgLocs[i];
2638 EVT RegVT = VA.getLocVT();
2639 SDValue Arg = OutVals[i];
2640 bool isByVal = Flags.isByVal();
2642 // Promote the value if needed.
2643 switch (VA.getLocInfo()) {
2644 default: llvm_unreachable("Unknown loc info!");
2645 case CCValAssign::Full: break;
2646 case CCValAssign::SExt:
2647 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2649 case CCValAssign::ZExt:
2650 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2652 case CCValAssign::AExt:
2653 if (RegVT.is128BitVector()) {
2654 // Special case: passing MMX values in XMM registers.
2655 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2656 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2657 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2659 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2661 case CCValAssign::BCvt:
2662 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2664 case CCValAssign::Indirect: {
2665 // Store the argument.
2666 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2667 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2668 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2669 MachinePointerInfo::getFixedStack(FI),
2676 if (VA.isRegLoc()) {
2677 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2678 if (isVarArg && IsWin64) {
2679 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2680 // shadow reg if callee is a varargs function.
2681 unsigned ShadowReg = 0;
2682 switch (VA.getLocReg()) {
2683 case X86::XMM0: ShadowReg = X86::RCX; break;
2684 case X86::XMM1: ShadowReg = X86::RDX; break;
2685 case X86::XMM2: ShadowReg = X86::R8; break;
2686 case X86::XMM3: ShadowReg = X86::R9; break;
2689 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2691 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2692 assert(VA.isMemLoc());
2693 if (!StackPtr.getNode())
2694 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2696 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2697 dl, DAG, VA, Flags));
2701 if (!MemOpChains.empty())
2702 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2703 &MemOpChains[0], MemOpChains.size());
2705 if (Subtarget->isPICStyleGOT()) {
2706 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2709 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2710 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2712 // If we are tail calling and generating PIC/GOT style code load the
2713 // address of the callee into ECX. The value in ecx is used as target of
2714 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2715 // for tail calls on PIC/GOT architectures. Normally we would just put the
2716 // address of GOT into ebx and then call target@PLT. But for tail calls
2717 // ebx would be restored (since ebx is callee saved) before jumping to the
2720 // Note: The actual moving to ECX is done further down.
2721 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2722 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2723 !G->getGlobal()->hasProtectedVisibility())
2724 Callee = LowerGlobalAddress(Callee, DAG);
2725 else if (isa<ExternalSymbolSDNode>(Callee))
2726 Callee = LowerExternalSymbol(Callee, DAG);
2730 if (Is64Bit && isVarArg && !IsWin64) {
2731 // From AMD64 ABI document:
2732 // For calls that may call functions that use varargs or stdargs
2733 // (prototype-less calls or calls to functions containing ellipsis (...) in
2734 // the declaration) %al is used as hidden argument to specify the number
2735 // of SSE registers used. The contents of %al do not need to match exactly
2736 // the number of registers, but must be an ubound on the number of SSE
2737 // registers used and is in the range 0 - 8 inclusive.
2739 // Count the number of XMM registers allocated.
2740 static const MCPhysReg XMMArgRegs[] = {
2741 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2742 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2744 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2745 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2746 && "SSE registers cannot be used when SSE is disabled");
2748 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2749 DAG.getConstant(NumXMMRegs, MVT::i8)));
2752 // For tail calls lower the arguments to the 'real' stack slot.
2754 // Force all the incoming stack arguments to be loaded from the stack
2755 // before any new outgoing arguments are stored to the stack, because the
2756 // outgoing stack slots may alias the incoming argument stack slots, and
2757 // the alias isn't otherwise explicit. This is slightly more conservative
2758 // than necessary, because it means that each store effectively depends
2759 // on every argument instead of just those arguments it would clobber.
2760 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2762 SmallVector<SDValue, 8> MemOpChains2;
2765 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2766 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2767 CCValAssign &VA = ArgLocs[i];
2770 assert(VA.isMemLoc());
2771 SDValue Arg = OutVals[i];
2772 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2773 // Create frame index.
2774 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2775 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2776 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2777 FIN = DAG.getFrameIndex(FI, getPointerTy());
2779 if (Flags.isByVal()) {
2780 // Copy relative to framepointer.
2781 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2782 if (!StackPtr.getNode())
2783 StackPtr = DAG.getCopyFromReg(Chain, dl,
2784 RegInfo->getStackRegister(),
2786 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2788 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2792 // Store relative to framepointer.
2793 MemOpChains2.push_back(
2794 DAG.getStore(ArgChain, dl, Arg, FIN,
2795 MachinePointerInfo::getFixedStack(FI),
2801 if (!MemOpChains2.empty())
2802 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2803 &MemOpChains2[0], MemOpChains2.size());
2805 // Store the return address to the appropriate stack slot.
2806 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2807 getPointerTy(), RegInfo->getSlotSize(),
2811 // Build a sequence of copy-to-reg nodes chained together with token chain
2812 // and flag operands which copy the outgoing args into registers.
2814 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2815 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2816 RegsToPass[i].second, InFlag);
2817 InFlag = Chain.getValue(1);
2820 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2821 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2822 // In the 64-bit large code model, we have to make all calls
2823 // through a register, since the call instruction's 32-bit
2824 // pc-relative offset may not be large enough to hold the whole
2826 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2827 // If the callee is a GlobalAddress node (quite common, every direct call
2828 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2831 // We should use extra load for direct calls to dllimported functions in
2833 const GlobalValue *GV = G->getGlobal();
2834 if (!GV->hasDLLImportStorageClass()) {
2835 unsigned char OpFlags = 0;
2836 bool ExtraLoad = false;
2837 unsigned WrapperKind = ISD::DELETED_NODE;
2839 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2840 // external symbols most go through the PLT in PIC mode. If the symbol
2841 // has hidden or protected visibility, or if it is static or local, then
2842 // we don't need to use the PLT - we can directly call it.
2843 if (Subtarget->isTargetELF() &&
2844 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2845 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2846 OpFlags = X86II::MO_PLT;
2847 } else if (Subtarget->isPICStyleStubAny() &&
2848 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2849 (!Subtarget->getTargetTriple().isMacOSX() ||
2850 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2851 // PC-relative references to external symbols should go through $stub,
2852 // unless we're building with the leopard linker or later, which
2853 // automatically synthesizes these stubs.
2854 OpFlags = X86II::MO_DARWIN_STUB;
2855 } else if (Subtarget->isPICStyleRIPRel() &&
2856 isa<Function>(GV) &&
2857 cast<Function>(GV)->getAttributes().
2858 hasAttribute(AttributeSet::FunctionIndex,
2859 Attribute::NonLazyBind)) {
2860 // If the function is marked as non-lazy, generate an indirect call
2861 // which loads from the GOT directly. This avoids runtime overhead
2862 // at the cost of eager binding (and one extra byte of encoding).
2863 OpFlags = X86II::MO_GOTPCREL;
2864 WrapperKind = X86ISD::WrapperRIP;
2868 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2869 G->getOffset(), OpFlags);
2871 // Add a wrapper if needed.
2872 if (WrapperKind != ISD::DELETED_NODE)
2873 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2874 // Add extra indirection if needed.
2876 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2877 MachinePointerInfo::getGOT(),
2878 false, false, false, 0);
2880 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2881 unsigned char OpFlags = 0;
2883 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2884 // external symbols should go through the PLT.
2885 if (Subtarget->isTargetELF() &&
2886 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2887 OpFlags = X86II::MO_PLT;
2888 } else if (Subtarget->isPICStyleStubAny() &&
2889 (!Subtarget->getTargetTriple().isMacOSX() ||
2890 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2891 // PC-relative references to external symbols should go through $stub,
2892 // unless we're building with the leopard linker or later, which
2893 // automatically synthesizes these stubs.
2894 OpFlags = X86II::MO_DARWIN_STUB;
2897 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2901 // Returns a chain & a flag for retval copy to use.
2902 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2903 SmallVector<SDValue, 8> Ops;
2905 if (!IsSibcall && isTailCall) {
2906 Chain = DAG.getCALLSEQ_END(Chain,
2907 DAG.getIntPtrConstant(NumBytesToPop, true),
2908 DAG.getIntPtrConstant(0, true), InFlag, dl);
2909 InFlag = Chain.getValue(1);
2912 Ops.push_back(Chain);
2913 Ops.push_back(Callee);
2916 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2918 // Add argument registers to the end of the list so that they are known live
2920 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2921 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2922 RegsToPass[i].second.getValueType()));
2924 // Add a register mask operand representing the call-preserved registers.
2925 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2926 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2927 assert(Mask && "Missing call preserved mask for calling convention");
2928 Ops.push_back(DAG.getRegisterMask(Mask));
2930 if (InFlag.getNode())
2931 Ops.push_back(InFlag);
2935 //// If this is the first return lowered for this function, add the regs
2936 //// to the liveout set for the function.
2937 // This isn't right, although it's probably harmless on x86; liveouts
2938 // should be computed from returns not tail calls. Consider a void
2939 // function making a tail call to a function returning int.
2940 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2943 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2944 InFlag = Chain.getValue(1);
2946 // Create the CALLSEQ_END node.
2947 unsigned NumBytesForCalleeToPop;
2948 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2949 getTargetMachine().Options.GuaranteedTailCallOpt))
2950 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2951 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2952 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2953 SR == StackStructReturn)
2954 // If this is a call to a struct-return function, the callee
2955 // pops the hidden struct pointer, so we have to push it back.
2956 // This is common for Darwin/X86, Linux & Mingw32 targets.
2957 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2958 NumBytesForCalleeToPop = 4;
2960 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2962 // Returns a flag for retval copy to use.
2964 Chain = DAG.getCALLSEQ_END(Chain,
2965 DAG.getIntPtrConstant(NumBytesToPop, true),
2966 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2969 InFlag = Chain.getValue(1);
2972 // Handle result values, copying them out of physregs into vregs that we
2974 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2975 Ins, dl, DAG, InVals);
2978 //===----------------------------------------------------------------------===//
2979 // Fast Calling Convention (tail call) implementation
2980 //===----------------------------------------------------------------------===//
2982 // Like std call, callee cleans arguments, convention except that ECX is
2983 // reserved for storing the tail called function address. Only 2 registers are
2984 // free for argument passing (inreg). Tail call optimization is performed
2986 // * tailcallopt is enabled
2987 // * caller/callee are fastcc
2988 // On X86_64 architecture with GOT-style position independent code only local
2989 // (within module) calls are supported at the moment.
2990 // To keep the stack aligned according to platform abi the function
2991 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2992 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2993 // If a tail called function callee has more arguments than the caller the
2994 // caller needs to make sure that there is room to move the RETADDR to. This is
2995 // achieved by reserving an area the size of the argument delta right after the
2996 // original REtADDR, but before the saved framepointer or the spilled registers
2997 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3009 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3010 /// for a 16 byte align requirement.
3012 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3013 SelectionDAG& DAG) const {
3014 MachineFunction &MF = DAG.getMachineFunction();
3015 const TargetMachine &TM = MF.getTarget();
3016 const X86RegisterInfo *RegInfo =
3017 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3018 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3019 unsigned StackAlignment = TFI.getStackAlignment();
3020 uint64_t AlignMask = StackAlignment - 1;
3021 int64_t Offset = StackSize;
3022 unsigned SlotSize = RegInfo->getSlotSize();
3023 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3024 // Number smaller than 12 so just add the difference.
3025 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3027 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3028 Offset = ((~AlignMask) & Offset) + StackAlignment +
3029 (StackAlignment-SlotSize);
3034 /// MatchingStackOffset - Return true if the given stack call argument is
3035 /// already available in the same position (relatively) of the caller's
3036 /// incoming argument stack.
3038 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3039 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3040 const X86InstrInfo *TII) {
3041 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3043 if (Arg.getOpcode() == ISD::CopyFromReg) {
3044 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3045 if (!TargetRegisterInfo::isVirtualRegister(VR))
3047 MachineInstr *Def = MRI->getVRegDef(VR);
3050 if (!Flags.isByVal()) {
3051 if (!TII->isLoadFromStackSlot(Def, FI))
3054 unsigned Opcode = Def->getOpcode();
3055 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3056 Def->getOperand(1).isFI()) {
3057 FI = Def->getOperand(1).getIndex();
3058 Bytes = Flags.getByValSize();
3062 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3063 if (Flags.isByVal())
3064 // ByVal argument is passed in as a pointer but it's now being
3065 // dereferenced. e.g.
3066 // define @foo(%struct.X* %A) {
3067 // tail call @bar(%struct.X* byval %A)
3070 SDValue Ptr = Ld->getBasePtr();
3071 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3074 FI = FINode->getIndex();
3075 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3076 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3077 FI = FINode->getIndex();
3078 Bytes = Flags.getByValSize();
3082 assert(FI != INT_MAX);
3083 if (!MFI->isFixedObjectIndex(FI))
3085 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3088 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3089 /// for tail call optimization. Targets which want to do tail call
3090 /// optimization should implement this function.
3092 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3093 CallingConv::ID CalleeCC,
3095 bool isCalleeStructRet,
3096 bool isCallerStructRet,
3098 const SmallVectorImpl<ISD::OutputArg> &Outs,
3099 const SmallVectorImpl<SDValue> &OutVals,
3100 const SmallVectorImpl<ISD::InputArg> &Ins,
3101 SelectionDAG &DAG) const {
3102 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3105 // If -tailcallopt is specified, make fastcc functions tail-callable.
3106 const MachineFunction &MF = DAG.getMachineFunction();
3107 const Function *CallerF = MF.getFunction();
3109 // If the function return type is x86_fp80 and the callee return type is not,
3110 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3111 // perform a tailcall optimization here.
3112 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3115 CallingConv::ID CallerCC = CallerF->getCallingConv();
3116 bool CCMatch = CallerCC == CalleeCC;
3117 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3118 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3120 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3121 if (IsTailCallConvention(CalleeCC) && CCMatch)
3126 // Look for obvious safe cases to perform tail call optimization that do not
3127 // require ABI changes. This is what gcc calls sibcall.
3129 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3130 // emit a special epilogue.
3131 const X86RegisterInfo *RegInfo =
3132 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3133 if (RegInfo->needsStackRealignment(MF))
3136 // Also avoid sibcall optimization if either caller or callee uses struct
3137 // return semantics.
3138 if (isCalleeStructRet || isCallerStructRet)
3141 // An stdcall/thiscall caller is expected to clean up its arguments; the
3142 // callee isn't going to do that.
3143 // FIXME: this is more restrictive than needed. We could produce a tailcall
3144 // when the stack adjustment matches. For example, with a thiscall that takes
3145 // only one argument.
3146 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3147 CallerCC == CallingConv::X86_ThisCall))
3150 // Do not sibcall optimize vararg calls unless all arguments are passed via
3152 if (isVarArg && !Outs.empty()) {
3154 // Optimizing for varargs on Win64 is unlikely to be safe without
3155 // additional testing.
3156 if (IsCalleeWin64 || IsCallerWin64)
3159 SmallVector<CCValAssign, 16> ArgLocs;
3160 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3161 getTargetMachine(), ArgLocs, *DAG.getContext());
3163 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3164 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3165 if (!ArgLocs[i].isRegLoc())
3169 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3170 // stack. Therefore, if it's not used by the call it is not safe to optimize
3171 // this into a sibcall.
3172 bool Unused = false;
3173 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3180 SmallVector<CCValAssign, 16> RVLocs;
3181 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3182 getTargetMachine(), RVLocs, *DAG.getContext());
3183 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3184 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3185 CCValAssign &VA = RVLocs[i];
3186 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3191 // If the calling conventions do not match, then we'd better make sure the
3192 // results are returned in the same way as what the caller expects.
3194 SmallVector<CCValAssign, 16> RVLocs1;
3195 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3196 getTargetMachine(), RVLocs1, *DAG.getContext());
3197 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3199 SmallVector<CCValAssign, 16> RVLocs2;
3200 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3201 getTargetMachine(), RVLocs2, *DAG.getContext());
3202 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3204 if (RVLocs1.size() != RVLocs2.size())
3206 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3207 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3209 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3211 if (RVLocs1[i].isRegLoc()) {
3212 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3215 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3221 // If the callee takes no arguments then go on to check the results of the
3223 if (!Outs.empty()) {
3224 // Check if stack adjustment is needed. For now, do not do this if any
3225 // argument is passed on the stack.
3226 SmallVector<CCValAssign, 16> ArgLocs;
3227 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3228 getTargetMachine(), ArgLocs, *DAG.getContext());
3230 // Allocate shadow area for Win64
3232 CCInfo.AllocateStack(32, 8);
3234 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3235 if (CCInfo.getNextStackOffset()) {
3236 MachineFunction &MF = DAG.getMachineFunction();
3237 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3240 // Check if the arguments are already laid out in the right way as
3241 // the caller's fixed stack objects.
3242 MachineFrameInfo *MFI = MF.getFrameInfo();
3243 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3244 const X86InstrInfo *TII =
3245 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3246 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3247 CCValAssign &VA = ArgLocs[i];
3248 SDValue Arg = OutVals[i];
3249 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3250 if (VA.getLocInfo() == CCValAssign::Indirect)
3252 if (!VA.isRegLoc()) {
3253 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3260 // If the tailcall address may be in a register, then make sure it's
3261 // possible to register allocate for it. In 32-bit, the call address can
3262 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3263 // callee-saved registers are restored. These happen to be the same
3264 // registers used to pass 'inreg' arguments so watch out for those.
3265 if (!Subtarget->is64Bit() &&
3266 ((!isa<GlobalAddressSDNode>(Callee) &&
3267 !isa<ExternalSymbolSDNode>(Callee)) ||
3268 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3269 unsigned NumInRegs = 0;
3270 // In PIC we need an extra register to formulate the address computation
3272 unsigned MaxInRegs =
3273 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3275 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3276 CCValAssign &VA = ArgLocs[i];
3279 unsigned Reg = VA.getLocReg();
3282 case X86::EAX: case X86::EDX: case X86::ECX:
3283 if (++NumInRegs == MaxInRegs)
3295 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3296 const TargetLibraryInfo *libInfo) const {
3297 return X86::createFastISel(funcInfo, libInfo);
3300 //===----------------------------------------------------------------------===//
3301 // Other Lowering Hooks
3302 //===----------------------------------------------------------------------===//
3304 static bool MayFoldLoad(SDValue Op) {
3305 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3308 static bool MayFoldIntoStore(SDValue Op) {
3309 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3312 static bool isTargetShuffle(unsigned Opcode) {
3314 default: return false;
3315 case X86ISD::PSHUFD:
3316 case X86ISD::PSHUFHW:
3317 case X86ISD::PSHUFLW:
3319 case X86ISD::PALIGNR:
3320 case X86ISD::MOVLHPS:
3321 case X86ISD::MOVLHPD:
3322 case X86ISD::MOVHLPS:
3323 case X86ISD::MOVLPS:
3324 case X86ISD::MOVLPD:
3325 case X86ISD::MOVSHDUP:
3326 case X86ISD::MOVSLDUP:
3327 case X86ISD::MOVDDUP:
3330 case X86ISD::UNPCKL:
3331 case X86ISD::UNPCKH:
3332 case X86ISD::VPERMILP:
3333 case X86ISD::VPERM2X128:
3334 case X86ISD::VPERMI:
3339 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3340 SDValue V1, SelectionDAG &DAG) {
3342 default: llvm_unreachable("Unknown x86 shuffle node");
3343 case X86ISD::MOVSHDUP:
3344 case X86ISD::MOVSLDUP:
3345 case X86ISD::MOVDDUP:
3346 return DAG.getNode(Opc, dl, VT, V1);
3350 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3351 SDValue V1, unsigned TargetMask,
3352 SelectionDAG &DAG) {
3354 default: llvm_unreachable("Unknown x86 shuffle node");
3355 case X86ISD::PSHUFD:
3356 case X86ISD::PSHUFHW:
3357 case X86ISD::PSHUFLW:
3358 case X86ISD::VPERMILP:
3359 case X86ISD::VPERMI:
3360 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3364 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3365 SDValue V1, SDValue V2, unsigned TargetMask,
3366 SelectionDAG &DAG) {
3368 default: llvm_unreachable("Unknown x86 shuffle node");
3369 case X86ISD::PALIGNR:
3371 case X86ISD::VPERM2X128:
3372 return DAG.getNode(Opc, dl, VT, V1, V2,
3373 DAG.getConstant(TargetMask, MVT::i8));
3377 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3378 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3380 default: llvm_unreachable("Unknown x86 shuffle node");
3381 case X86ISD::MOVLHPS:
3382 case X86ISD::MOVLHPD:
3383 case X86ISD::MOVHLPS:
3384 case X86ISD::MOVLPS:
3385 case X86ISD::MOVLPD:
3388 case X86ISD::UNPCKL:
3389 case X86ISD::UNPCKH:
3390 return DAG.getNode(Opc, dl, VT, V1, V2);
3394 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3395 MachineFunction &MF = DAG.getMachineFunction();
3396 const X86RegisterInfo *RegInfo =
3397 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3398 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3399 int ReturnAddrIndex = FuncInfo->getRAIndex();
3401 if (ReturnAddrIndex == 0) {
3402 // Set up a frame object for the return address.
3403 unsigned SlotSize = RegInfo->getSlotSize();
3404 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3407 FuncInfo->setRAIndex(ReturnAddrIndex);
3410 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3413 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3414 bool hasSymbolicDisplacement) {
3415 // Offset should fit into 32 bit immediate field.
3416 if (!isInt<32>(Offset))
3419 // If we don't have a symbolic displacement - we don't have any extra
3421 if (!hasSymbolicDisplacement)
3424 // FIXME: Some tweaks might be needed for medium code model.
3425 if (M != CodeModel::Small && M != CodeModel::Kernel)
3428 // For small code model we assume that latest object is 16MB before end of 31
3429 // bits boundary. We may also accept pretty large negative constants knowing
3430 // that all objects are in the positive half of address space.
3431 if (M == CodeModel::Small && Offset < 16*1024*1024)
3434 // For kernel code model we know that all object resist in the negative half
3435 // of 32bits address space. We may not accept negative offsets, since they may
3436 // be just off and we may accept pretty large positive ones.
3437 if (M == CodeModel::Kernel && Offset > 0)
3443 /// isCalleePop - Determines whether the callee is required to pop its
3444 /// own arguments. Callee pop is necessary to support tail calls.
3445 bool X86::isCalleePop(CallingConv::ID CallingConv,
3446 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3450 switch (CallingConv) {
3453 case CallingConv::X86_StdCall:
3455 case CallingConv::X86_FastCall:
3457 case CallingConv::X86_ThisCall:
3459 case CallingConv::Fast:
3461 case CallingConv::GHC:
3463 case CallingConv::HiPE:
3468 /// \brief Return true if the condition is an unsigned comparison operation.
3469 static bool isX86CCUnsigned(unsigned X86CC) {
3471 default: llvm_unreachable("Invalid integer condition!");
3472 case X86::COND_E: return true;
3473 case X86::COND_G: return false;
3474 case X86::COND_GE: return false;
3475 case X86::COND_L: return false;
3476 case X86::COND_LE: return false;
3477 case X86::COND_NE: return true;
3478 case X86::COND_B: return true;
3479 case X86::COND_A: return true;
3480 case X86::COND_BE: return true;
3481 case X86::COND_AE: return true;
3483 llvm_unreachable("covered switch fell through?!");
3486 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3487 /// specific condition code, returning the condition code and the LHS/RHS of the
3488 /// comparison to make.
3489 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3490 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3492 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3493 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3494 // X > -1 -> X == 0, jump !sign.
3495 RHS = DAG.getConstant(0, RHS.getValueType());
3496 return X86::COND_NS;
3498 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3499 // X < 0 -> X == 0, jump on sign.
3502 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3504 RHS = DAG.getConstant(0, RHS.getValueType());
3505 return X86::COND_LE;
3509 switch (SetCCOpcode) {
3510 default: llvm_unreachable("Invalid integer condition!");
3511 case ISD::SETEQ: return X86::COND_E;
3512 case ISD::SETGT: return X86::COND_G;
3513 case ISD::SETGE: return X86::COND_GE;
3514 case ISD::SETLT: return X86::COND_L;
3515 case ISD::SETLE: return X86::COND_LE;
3516 case ISD::SETNE: return X86::COND_NE;
3517 case ISD::SETULT: return X86::COND_B;
3518 case ISD::SETUGT: return X86::COND_A;
3519 case ISD::SETULE: return X86::COND_BE;
3520 case ISD::SETUGE: return X86::COND_AE;
3524 // First determine if it is required or is profitable to flip the operands.
3526 // If LHS is a foldable load, but RHS is not, flip the condition.
3527 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3528 !ISD::isNON_EXTLoad(RHS.getNode())) {
3529 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3530 std::swap(LHS, RHS);
3533 switch (SetCCOpcode) {
3539 std::swap(LHS, RHS);
3543 // On a floating point condition, the flags are set as follows:
3545 // 0 | 0 | 0 | X > Y
3546 // 0 | 0 | 1 | X < Y
3547 // 1 | 0 | 0 | X == Y
3548 // 1 | 1 | 1 | unordered
3549 switch (SetCCOpcode) {
3550 default: llvm_unreachable("Condcode should be pre-legalized away");
3552 case ISD::SETEQ: return X86::COND_E;
3553 case ISD::SETOLT: // flipped
3555 case ISD::SETGT: return X86::COND_A;
3556 case ISD::SETOLE: // flipped
3558 case ISD::SETGE: return X86::COND_AE;
3559 case ISD::SETUGT: // flipped
3561 case ISD::SETLT: return X86::COND_B;
3562 case ISD::SETUGE: // flipped
3564 case ISD::SETLE: return X86::COND_BE;
3566 case ISD::SETNE: return X86::COND_NE;
3567 case ISD::SETUO: return X86::COND_P;
3568 case ISD::SETO: return X86::COND_NP;
3570 case ISD::SETUNE: return X86::COND_INVALID;
3574 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3575 /// code. Current x86 isa includes the following FP cmov instructions:
3576 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3577 static bool hasFPCMov(unsigned X86CC) {
3593 /// isFPImmLegal - Returns true if the target can instruction select the
3594 /// specified FP immediate natively. If false, the legalizer will
3595 /// materialize the FP immediate as a load from a constant pool.
3596 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3597 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3598 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3604 /// \brief Returns true if it is beneficial to convert a load of a constant
3605 /// to just the constant itself.
3606 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3608 assert(Ty->isIntegerTy());
3610 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3611 if (BitSize == 0 || BitSize > 64)
3616 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3617 /// the specified range (L, H].
3618 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3619 return (Val < 0) || (Val >= Low && Val < Hi);
3622 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3623 /// specified value.
3624 static bool isUndefOrEqual(int Val, int CmpVal) {
3625 return (Val < 0 || Val == CmpVal);
3628 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3629 /// from position Pos and ending in Pos+Size, falls within the specified
3630 /// sequential range (L, L+Pos]. or is undef.
3631 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3632 unsigned Pos, unsigned Size, int Low) {
3633 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3634 if (!isUndefOrEqual(Mask[i], Low))
3639 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3640 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3641 /// the second operand.
3642 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3643 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3644 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3645 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3646 return (Mask[0] < 2 && Mask[1] < 2);
3650 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3651 /// is suitable for input to PSHUFHW.
3652 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3653 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3656 // Lower quadword copied in order or undef.
3657 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3660 // Upper quadword shuffled.
3661 for (unsigned i = 4; i != 8; ++i)
3662 if (!isUndefOrInRange(Mask[i], 4, 8))
3665 if (VT == MVT::v16i16) {
3666 // Lower quadword copied in order or undef.
3667 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3670 // Upper quadword shuffled.
3671 for (unsigned i = 12; i != 16; ++i)
3672 if (!isUndefOrInRange(Mask[i], 12, 16))
3679 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3680 /// is suitable for input to PSHUFLW.
3681 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3682 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3685 // Upper quadword copied in order.
3686 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3689 // Lower quadword shuffled.
3690 for (unsigned i = 0; i != 4; ++i)
3691 if (!isUndefOrInRange(Mask[i], 0, 4))
3694 if (VT == MVT::v16i16) {
3695 // Upper quadword copied in order.
3696 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3699 // Lower quadword shuffled.
3700 for (unsigned i = 8; i != 12; ++i)
3701 if (!isUndefOrInRange(Mask[i], 8, 12))
3708 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3709 /// is suitable for input to PALIGNR.
3710 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3711 const X86Subtarget *Subtarget) {
3712 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3713 (VT.is256BitVector() && !Subtarget->hasInt256()))
3716 unsigned NumElts = VT.getVectorNumElements();
3717 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3718 unsigned NumLaneElts = NumElts/NumLanes;
3720 // Do not handle 64-bit element shuffles with palignr.
3721 if (NumLaneElts == 2)
3724 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3726 for (i = 0; i != NumLaneElts; ++i) {
3731 // Lane is all undef, go to next lane
3732 if (i == NumLaneElts)
3735 int Start = Mask[i+l];
3737 // Make sure its in this lane in one of the sources
3738 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3739 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3742 // If not lane 0, then we must match lane 0
3743 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3746 // Correct second source to be contiguous with first source
3747 if (Start >= (int)NumElts)
3748 Start -= NumElts - NumLaneElts;
3750 // Make sure we're shifting in the right direction.
3751 if (Start <= (int)(i+l))
3756 // Check the rest of the elements to see if they are consecutive.
3757 for (++i; i != NumLaneElts; ++i) {
3758 int Idx = Mask[i+l];
3760 // Make sure its in this lane
3761 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3762 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3765 // If not lane 0, then we must match lane 0
3766 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3769 if (Idx >= (int)NumElts)
3770 Idx -= NumElts - NumLaneElts;
3772 if (!isUndefOrEqual(Idx, Start+i))
3781 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3782 /// the two vector operands have swapped position.
3783 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3784 unsigned NumElems) {
3785 for (unsigned i = 0; i != NumElems; ++i) {
3789 else if (idx < (int)NumElems)
3790 Mask[i] = idx + NumElems;
3792 Mask[i] = idx - NumElems;
3796 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3797 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3798 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3799 /// reverse of what x86 shuffles want.
3800 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3802 unsigned NumElems = VT.getVectorNumElements();
3803 unsigned NumLanes = VT.getSizeInBits()/128;
3804 unsigned NumLaneElems = NumElems/NumLanes;
3806 if (NumLaneElems != 2 && NumLaneElems != 4)
3809 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3810 bool symetricMaskRequired =
3811 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3813 // VSHUFPSY divides the resulting vector into 4 chunks.
3814 // The sources are also splitted into 4 chunks, and each destination
3815 // chunk must come from a different source chunk.
3817 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3818 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3820 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3821 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3823 // VSHUFPDY divides the resulting vector into 4 chunks.
3824 // The sources are also splitted into 4 chunks, and each destination
3825 // chunk must come from a different source chunk.
3827 // SRC1 => X3 X2 X1 X0
3828 // SRC2 => Y3 Y2 Y1 Y0
3830 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3832 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3833 unsigned HalfLaneElems = NumLaneElems/2;
3834 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3835 for (unsigned i = 0; i != NumLaneElems; ++i) {
3836 int Idx = Mask[i+l];
3837 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3838 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3840 // For VSHUFPSY, the mask of the second half must be the same as the
3841 // first but with the appropriate offsets. This works in the same way as
3842 // VPERMILPS works with masks.
3843 if (!symetricMaskRequired || Idx < 0)
3845 if (MaskVal[i] < 0) {
3846 MaskVal[i] = Idx - l;
3849 if ((signed)(Idx - l) != MaskVal[i])
3857 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3858 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3859 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3860 if (!VT.is128BitVector())
3863 unsigned NumElems = VT.getVectorNumElements();
3868 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3869 return isUndefOrEqual(Mask[0], 6) &&
3870 isUndefOrEqual(Mask[1], 7) &&
3871 isUndefOrEqual(Mask[2], 2) &&
3872 isUndefOrEqual(Mask[3], 3);
3875 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3876 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3878 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3879 if (!VT.is128BitVector())
3882 unsigned NumElems = VT.getVectorNumElements();
3887 return isUndefOrEqual(Mask[0], 2) &&
3888 isUndefOrEqual(Mask[1], 3) &&
3889 isUndefOrEqual(Mask[2], 2) &&
3890 isUndefOrEqual(Mask[3], 3);
3893 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3894 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3895 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3896 if (!VT.is128BitVector())
3899 unsigned NumElems = VT.getVectorNumElements();
3901 if (NumElems != 2 && NumElems != 4)
3904 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3905 if (!isUndefOrEqual(Mask[i], i + NumElems))
3908 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3909 if (!isUndefOrEqual(Mask[i], i))
3915 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3916 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3917 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3918 if (!VT.is128BitVector())
3921 unsigned NumElems = VT.getVectorNumElements();
3923 if (NumElems != 2 && NumElems != 4)
3926 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3927 if (!isUndefOrEqual(Mask[i], i))
3930 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3931 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3937 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3938 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3939 /// i. e: If all but one element come from the same vector.
3940 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3941 // TODO: Deal with AVX's VINSERTPS
3942 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3945 unsigned CorrectPosV1 = 0;
3946 unsigned CorrectPosV2 = 0;
3947 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3950 else if (Mask[i] == i + 4)
3953 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3954 // We have 3 elements from one vector, and one from another.
3961 // Some special combinations that can be optimized.
3964 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3965 SelectionDAG &DAG) {
3966 MVT VT = SVOp->getSimpleValueType(0);
3969 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3972 ArrayRef<int> Mask = SVOp->getMask();
3974 // These are the special masks that may be optimized.
3975 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3976 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3977 bool MatchEvenMask = true;
3978 bool MatchOddMask = true;
3979 for (int i=0; i<8; ++i) {
3980 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3981 MatchEvenMask = false;
3982 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3983 MatchOddMask = false;
3986 if (!MatchEvenMask && !MatchOddMask)
3989 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3991 SDValue Op0 = SVOp->getOperand(0);
3992 SDValue Op1 = SVOp->getOperand(1);
3994 if (MatchEvenMask) {
3995 // Shift the second operand right to 32 bits.
3996 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3997 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3999 // Shift the first operand left to 32 bits.
4000 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4001 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4003 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4004 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4007 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4008 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4009 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4010 bool HasInt256, bool V2IsSplat = false) {
4012 assert(VT.getSizeInBits() >= 128 &&
4013 "Unsupported vector type for unpckl");
4015 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4017 unsigned NumOf256BitLanes;
4018 unsigned NumElts = VT.getVectorNumElements();
4019 if (VT.is256BitVector()) {
4020 if (NumElts != 4 && NumElts != 8 &&
4021 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4024 NumOf256BitLanes = 1;
4025 } else if (VT.is512BitVector()) {
4026 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4027 "Unsupported vector type for unpckh");
4029 NumOf256BitLanes = 2;
4032 NumOf256BitLanes = 1;
4035 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4036 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4038 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4039 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4040 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4041 int BitI = Mask[l256*NumEltsInStride+l+i];
4042 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4043 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4045 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4047 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4055 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4056 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4057 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4058 bool HasInt256, bool V2IsSplat = false) {
4059 assert(VT.getSizeInBits() >= 128 &&
4060 "Unsupported vector type for unpckh");
4062 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4064 unsigned NumOf256BitLanes;
4065 unsigned NumElts = VT.getVectorNumElements();
4066 if (VT.is256BitVector()) {
4067 if (NumElts != 4 && NumElts != 8 &&
4068 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4071 NumOf256BitLanes = 1;
4072 } else if (VT.is512BitVector()) {
4073 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4074 "Unsupported vector type for unpckh");
4076 NumOf256BitLanes = 2;
4079 NumOf256BitLanes = 1;
4082 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4083 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4085 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4086 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4087 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4088 int BitI = Mask[l256*NumEltsInStride+l+i];
4089 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4090 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4092 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4094 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4102 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4103 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4105 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4106 unsigned NumElts = VT.getVectorNumElements();
4107 bool Is256BitVec = VT.is256BitVector();
4109 if (VT.is512BitVector())
4111 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4112 "Unsupported vector type for unpckh");
4114 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4115 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4118 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4119 // FIXME: Need a better way to get rid of this, there's no latency difference
4120 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4121 // the former later. We should also remove the "_undef" special mask.
4122 if (NumElts == 4 && Is256BitVec)
4125 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4126 // independently on 128-bit lanes.
4127 unsigned NumLanes = VT.getSizeInBits()/128;
4128 unsigned NumLaneElts = NumElts/NumLanes;
4130 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4131 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4132 int BitI = Mask[l+i];
4133 int BitI1 = Mask[l+i+1];
4135 if (!isUndefOrEqual(BitI, j))
4137 if (!isUndefOrEqual(BitI1, j))
4145 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4146 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4148 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4149 unsigned NumElts = VT.getVectorNumElements();
4151 if (VT.is512BitVector())
4154 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4155 "Unsupported vector type for unpckh");
4157 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4158 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4161 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4162 // independently on 128-bit lanes.
4163 unsigned NumLanes = VT.getSizeInBits()/128;
4164 unsigned NumLaneElts = NumElts/NumLanes;
4166 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4167 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4168 int BitI = Mask[l+i];
4169 int BitI1 = Mask[l+i+1];
4170 if (!isUndefOrEqual(BitI, j))
4172 if (!isUndefOrEqual(BitI1, j))
4179 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4180 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4181 /// MOVSD, and MOVD, i.e. setting the lowest element.
4182 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4183 if (VT.getVectorElementType().getSizeInBits() < 32)
4185 if (!VT.is128BitVector())
4188 unsigned NumElts = VT.getVectorNumElements();
4190 if (!isUndefOrEqual(Mask[0], NumElts))
4193 for (unsigned i = 1; i != NumElts; ++i)
4194 if (!isUndefOrEqual(Mask[i], i))
4200 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4201 /// as permutations between 128-bit chunks or halves. As an example: this
4203 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4204 /// The first half comes from the second half of V1 and the second half from the
4205 /// the second half of V2.
4206 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4207 if (!HasFp256 || !VT.is256BitVector())
4210 // The shuffle result is divided into half A and half B. In total the two
4211 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4212 // B must come from C, D, E or F.
4213 unsigned HalfSize = VT.getVectorNumElements()/2;
4214 bool MatchA = false, MatchB = false;
4216 // Check if A comes from one of C, D, E, F.
4217 for (unsigned Half = 0; Half != 4; ++Half) {
4218 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4224 // Check if B comes from one of C, D, E, F.
4225 for (unsigned Half = 0; Half != 4; ++Half) {
4226 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4232 return MatchA && MatchB;
4235 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4236 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4237 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4238 MVT VT = SVOp->getSimpleValueType(0);
4240 unsigned HalfSize = VT.getVectorNumElements()/2;
4242 unsigned FstHalf = 0, SndHalf = 0;
4243 for (unsigned i = 0; i < HalfSize; ++i) {
4244 if (SVOp->getMaskElt(i) > 0) {
4245 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4249 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4250 if (SVOp->getMaskElt(i) > 0) {
4251 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4256 return (FstHalf | (SndHalf << 4));
4259 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4260 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4261 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4265 unsigned NumElts = VT.getVectorNumElements();
4267 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4268 for (unsigned i = 0; i != NumElts; ++i) {
4271 Imm8 |= Mask[i] << (i*2);
4276 unsigned LaneSize = 4;
4277 SmallVector<int, 4> MaskVal(LaneSize, -1);
4279 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4280 for (unsigned i = 0; i != LaneSize; ++i) {
4281 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4285 if (MaskVal[i] < 0) {
4286 MaskVal[i] = Mask[i+l] - l;
4287 Imm8 |= MaskVal[i] << (i*2);
4290 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4297 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4298 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4299 /// Note that VPERMIL mask matching is different depending whether theunderlying
4300 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4301 /// to the same elements of the low, but to the higher half of the source.
4302 /// In VPERMILPD the two lanes could be shuffled independently of each other
4303 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4304 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4305 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4306 if (VT.getSizeInBits() < 256 || EltSize < 32)
4308 bool symetricMaskRequired = (EltSize == 32);
4309 unsigned NumElts = VT.getVectorNumElements();
4311 unsigned NumLanes = VT.getSizeInBits()/128;
4312 unsigned LaneSize = NumElts/NumLanes;
4313 // 2 or 4 elements in one lane
4315 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4316 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4317 for (unsigned i = 0; i != LaneSize; ++i) {
4318 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4320 if (symetricMaskRequired) {
4321 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4322 ExpectedMaskVal[i] = Mask[i+l] - l;
4325 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4333 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4334 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4335 /// element of vector 2 and the other elements to come from vector 1 in order.
4336 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4337 bool V2IsSplat = false, bool V2IsUndef = false) {
4338 if (!VT.is128BitVector())
4341 unsigned NumOps = VT.getVectorNumElements();
4342 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4345 if (!isUndefOrEqual(Mask[0], 0))
4348 for (unsigned i = 1; i != NumOps; ++i)
4349 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4350 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4351 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4357 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4358 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4359 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4360 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4361 const X86Subtarget *Subtarget) {
4362 if (!Subtarget->hasSSE3())
4365 unsigned NumElems = VT.getVectorNumElements();
4367 if ((VT.is128BitVector() && NumElems != 4) ||
4368 (VT.is256BitVector() && NumElems != 8) ||
4369 (VT.is512BitVector() && NumElems != 16))
4372 // "i+1" is the value the indexed mask element must have
4373 for (unsigned i = 0; i != NumElems; i += 2)
4374 if (!isUndefOrEqual(Mask[i], i+1) ||
4375 !isUndefOrEqual(Mask[i+1], i+1))
4381 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4382 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4383 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4384 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4385 const X86Subtarget *Subtarget) {
4386 if (!Subtarget->hasSSE3())
4389 unsigned NumElems = VT.getVectorNumElements();
4391 if ((VT.is128BitVector() && NumElems != 4) ||
4392 (VT.is256BitVector() && NumElems != 8) ||
4393 (VT.is512BitVector() && NumElems != 16))
4396 // "i" is the value the indexed mask element must have
4397 for (unsigned i = 0; i != NumElems; i += 2)
4398 if (!isUndefOrEqual(Mask[i], i) ||
4399 !isUndefOrEqual(Mask[i+1], i))
4405 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4406 /// specifies a shuffle of elements that is suitable for input to 256-bit
4407 /// version of MOVDDUP.
4408 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4409 if (!HasFp256 || !VT.is256BitVector())
4412 unsigned NumElts = VT.getVectorNumElements();
4416 for (unsigned i = 0; i != NumElts/2; ++i)
4417 if (!isUndefOrEqual(Mask[i], 0))
4419 for (unsigned i = NumElts/2; i != NumElts; ++i)
4420 if (!isUndefOrEqual(Mask[i], NumElts/2))
4425 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4426 /// specifies a shuffle of elements that is suitable for input to 128-bit
4427 /// version of MOVDDUP.
4428 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4429 if (!VT.is128BitVector())
4432 unsigned e = VT.getVectorNumElements() / 2;
4433 for (unsigned i = 0; i != e; ++i)
4434 if (!isUndefOrEqual(Mask[i], i))
4436 for (unsigned i = 0; i != e; ++i)
4437 if (!isUndefOrEqual(Mask[e+i], i))
4442 /// isVEXTRACTIndex - Return true if the specified
4443 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4444 /// suitable for instruction that extract 128 or 256 bit vectors
4445 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4446 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4447 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4450 // The index should be aligned on a vecWidth-bit boundary.
4452 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4454 MVT VT = N->getSimpleValueType(0);
4455 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4456 bool Result = (Index * ElSize) % vecWidth == 0;
4461 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4462 /// operand specifies a subvector insert that is suitable for input to
4463 /// insertion of 128 or 256-bit subvectors
4464 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4465 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4466 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4468 // The index should be aligned on a vecWidth-bit boundary.
4470 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4472 MVT VT = N->getSimpleValueType(0);
4473 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4474 bool Result = (Index * ElSize) % vecWidth == 0;
4479 bool X86::isVINSERT128Index(SDNode *N) {
4480 return isVINSERTIndex(N, 128);
4483 bool X86::isVINSERT256Index(SDNode *N) {
4484 return isVINSERTIndex(N, 256);
4487 bool X86::isVEXTRACT128Index(SDNode *N) {
4488 return isVEXTRACTIndex(N, 128);
4491 bool X86::isVEXTRACT256Index(SDNode *N) {
4492 return isVEXTRACTIndex(N, 256);
4495 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4496 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4497 /// Handles 128-bit and 256-bit.
4498 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4499 MVT VT = N->getSimpleValueType(0);
4501 assert((VT.getSizeInBits() >= 128) &&
4502 "Unsupported vector type for PSHUF/SHUFP");
4504 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4505 // independently on 128-bit lanes.
4506 unsigned NumElts = VT.getVectorNumElements();
4507 unsigned NumLanes = VT.getSizeInBits()/128;
4508 unsigned NumLaneElts = NumElts/NumLanes;
4510 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4511 "Only supports 2, 4 or 8 elements per lane");
4513 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4515 for (unsigned i = 0; i != NumElts; ++i) {
4516 int Elt = N->getMaskElt(i);
4517 if (Elt < 0) continue;
4518 Elt &= NumLaneElts - 1;
4519 unsigned ShAmt = (i << Shift) % 8;
4520 Mask |= Elt << ShAmt;
4526 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4527 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4528 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4529 MVT VT = N->getSimpleValueType(0);
4531 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4532 "Unsupported vector type for PSHUFHW");
4534 unsigned NumElts = VT.getVectorNumElements();
4537 for (unsigned l = 0; l != NumElts; l += 8) {
4538 // 8 nodes per lane, but we only care about the last 4.
4539 for (unsigned i = 0; i < 4; ++i) {
4540 int Elt = N->getMaskElt(l+i+4);
4541 if (Elt < 0) continue;
4542 Elt &= 0x3; // only 2-bits.
4543 Mask |= Elt << (i * 2);
4550 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4551 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4552 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4553 MVT VT = N->getSimpleValueType(0);
4555 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4556 "Unsupported vector type for PSHUFHW");
4558 unsigned NumElts = VT.getVectorNumElements();
4561 for (unsigned l = 0; l != NumElts; l += 8) {
4562 // 8 nodes per lane, but we only care about the first 4.
4563 for (unsigned i = 0; i < 4; ++i) {
4564 int Elt = N->getMaskElt(l+i);
4565 if (Elt < 0) continue;
4566 Elt &= 0x3; // only 2-bits
4567 Mask |= Elt << (i * 2);
4574 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4575 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4576 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4577 MVT VT = SVOp->getSimpleValueType(0);
4578 unsigned EltSize = VT.is512BitVector() ? 1 :
4579 VT.getVectorElementType().getSizeInBits() >> 3;
4581 unsigned NumElts = VT.getVectorNumElements();
4582 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4583 unsigned NumLaneElts = NumElts/NumLanes;
4587 for (i = 0; i != NumElts; ++i) {
4588 Val = SVOp->getMaskElt(i);
4592 if (Val >= (int)NumElts)
4593 Val -= NumElts - NumLaneElts;
4595 assert(Val - i > 0 && "PALIGNR imm should be positive");
4596 return (Val - i) * EltSize;
4599 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4600 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4601 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4602 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4605 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4607 MVT VecVT = N->getOperand(0).getSimpleValueType();
4608 MVT ElVT = VecVT.getVectorElementType();
4610 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4611 return Index / NumElemsPerChunk;
4614 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4615 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4616 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4617 llvm_unreachable("Illegal insert subvector for VINSERT");
4620 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4622 MVT VecVT = N->getSimpleValueType(0);
4623 MVT ElVT = VecVT.getVectorElementType();
4625 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4626 return Index / NumElemsPerChunk;
4629 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4630 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4631 /// and VINSERTI128 instructions.
4632 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4633 return getExtractVEXTRACTImmediate(N, 128);
4636 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4637 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4638 /// and VINSERTI64x4 instructions.
4639 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4640 return getExtractVEXTRACTImmediate(N, 256);
4643 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4644 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4645 /// and VINSERTI128 instructions.
4646 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4647 return getInsertVINSERTImmediate(N, 128);
4650 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4651 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4652 /// and VINSERTI64x4 instructions.
4653 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4654 return getInsertVINSERTImmediate(N, 256);
4657 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4659 bool X86::isZeroNode(SDValue Elt) {
4660 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4661 return CN->isNullValue();
4662 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4663 return CFP->getValueAPF().isPosZero();
4667 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4668 /// their permute mask.
4669 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4670 SelectionDAG &DAG) {
4671 MVT VT = SVOp->getSimpleValueType(0);
4672 unsigned NumElems = VT.getVectorNumElements();
4673 SmallVector<int, 8> MaskVec;
4675 for (unsigned i = 0; i != NumElems; ++i) {
4676 int Idx = SVOp->getMaskElt(i);
4678 if (Idx < (int)NumElems)
4683 MaskVec.push_back(Idx);
4685 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4686 SVOp->getOperand(0), &MaskVec[0]);
4689 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4690 /// match movhlps. The lower half elements should come from upper half of
4691 /// V1 (and in order), and the upper half elements should come from the upper
4692 /// half of V2 (and in order).
4693 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4694 if (!VT.is128BitVector())
4696 if (VT.getVectorNumElements() != 4)
4698 for (unsigned i = 0, e = 2; i != e; ++i)
4699 if (!isUndefOrEqual(Mask[i], i+2))
4701 for (unsigned i = 2; i != 4; ++i)
4702 if (!isUndefOrEqual(Mask[i], i+4))
4707 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4708 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4710 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4711 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4713 N = N->getOperand(0).getNode();
4714 if (!ISD::isNON_EXTLoad(N))
4717 *LD = cast<LoadSDNode>(N);
4721 // Test whether the given value is a vector value which will be legalized
4723 static bool WillBeConstantPoolLoad(SDNode *N) {
4724 if (N->getOpcode() != ISD::BUILD_VECTOR)
4727 // Check for any non-constant elements.
4728 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4729 switch (N->getOperand(i).getNode()->getOpcode()) {
4731 case ISD::ConstantFP:
4738 // Vectors of all-zeros and all-ones are materialized with special
4739 // instructions rather than being loaded.
4740 return !ISD::isBuildVectorAllZeros(N) &&
4741 !ISD::isBuildVectorAllOnes(N);
4744 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4745 /// match movlp{s|d}. The lower half elements should come from lower half of
4746 /// V1 (and in order), and the upper half elements should come from the upper
4747 /// half of V2 (and in order). And since V1 will become the source of the
4748 /// MOVLP, it must be either a vector load or a scalar load to vector.
4749 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4750 ArrayRef<int> Mask, MVT VT) {
4751 if (!VT.is128BitVector())
4754 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4756 // Is V2 is a vector load, don't do this transformation. We will try to use
4757 // load folding shufps op.
4758 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4761 unsigned NumElems = VT.getVectorNumElements();
4763 if (NumElems != 2 && NumElems != 4)
4765 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4766 if (!isUndefOrEqual(Mask[i], i))
4768 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4769 if (!isUndefOrEqual(Mask[i], i+NumElems))
4774 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4776 static bool isSplatVector(SDNode *N) {
4777 if (N->getOpcode() != ISD::BUILD_VECTOR)
4780 SDValue SplatValue = N->getOperand(0);
4781 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4782 if (N->getOperand(i) != SplatValue)
4787 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4788 /// to an zero vector.
4789 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4790 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4791 SDValue V1 = N->getOperand(0);
4792 SDValue V2 = N->getOperand(1);
4793 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4794 for (unsigned i = 0; i != NumElems; ++i) {
4795 int Idx = N->getMaskElt(i);
4796 if (Idx >= (int)NumElems) {
4797 unsigned Opc = V2.getOpcode();
4798 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4800 if (Opc != ISD::BUILD_VECTOR ||
4801 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4803 } else if (Idx >= 0) {
4804 unsigned Opc = V1.getOpcode();
4805 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4807 if (Opc != ISD::BUILD_VECTOR ||
4808 !X86::isZeroNode(V1.getOperand(Idx)))
4815 /// getZeroVector - Returns a vector of specified type with all zero elements.
4817 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4818 SelectionDAG &DAG, SDLoc dl) {
4819 assert(VT.isVector() && "Expected a vector type");
4821 // Always build SSE zero vectors as <4 x i32> bitcasted
4822 // to their dest type. This ensures they get CSE'd.
4824 if (VT.is128BitVector()) { // SSE
4825 if (Subtarget->hasSSE2()) { // SSE2
4826 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4827 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4829 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4830 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4832 } else if (VT.is256BitVector()) { // AVX
4833 if (Subtarget->hasInt256()) { // AVX2
4834 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4835 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4836 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4837 array_lengthof(Ops));
4839 // 256-bit logic and arithmetic instructions in AVX are all
4840 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4841 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4842 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4843 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4844 array_lengthof(Ops));
4846 } else if (VT.is512BitVector()) { // AVX-512
4847 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4848 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4849 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4850 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4851 } else if (VT.getScalarType() == MVT::i1) {
4852 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4853 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4854 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4855 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4856 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4857 Ops, VT.getVectorNumElements());
4859 llvm_unreachable("Unexpected vector type");
4861 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4864 /// getOnesVector - Returns a vector of specified type with all bits set.
4865 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4866 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4867 /// Then bitcast to their original type, ensuring they get CSE'd.
4868 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4870 assert(VT.isVector() && "Expected a vector type");
4872 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4874 if (VT.is256BitVector()) {
4875 if (HasInt256) { // AVX2
4876 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4877 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4878 array_lengthof(Ops));
4880 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4881 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4883 } else if (VT.is128BitVector()) {
4884 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4886 llvm_unreachable("Unexpected vector type");
4888 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4891 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4892 /// that point to V2 points to its first element.
4893 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4894 for (unsigned i = 0; i != NumElems; ++i) {
4895 if (Mask[i] > (int)NumElems) {
4901 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4902 /// operation of specified width.
4903 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4905 unsigned NumElems = VT.getVectorNumElements();
4906 SmallVector<int, 8> Mask;
4907 Mask.push_back(NumElems);
4908 for (unsigned i = 1; i != NumElems; ++i)
4910 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4913 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4914 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4916 unsigned NumElems = VT.getVectorNumElements();
4917 SmallVector<int, 8> Mask;
4918 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4920 Mask.push_back(i + NumElems);
4922 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4925 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4926 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4928 unsigned NumElems = VT.getVectorNumElements();
4929 SmallVector<int, 8> Mask;
4930 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4931 Mask.push_back(i + Half);
4932 Mask.push_back(i + NumElems + Half);
4934 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4937 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4938 // a generic shuffle instruction because the target has no such instructions.
4939 // Generate shuffles which repeat i16 and i8 several times until they can be
4940 // represented by v4f32 and then be manipulated by target suported shuffles.
4941 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4942 MVT VT = V.getSimpleValueType();
4943 int NumElems = VT.getVectorNumElements();
4946 while (NumElems > 4) {
4947 if (EltNo < NumElems/2) {
4948 V = getUnpackl(DAG, dl, VT, V, V);
4950 V = getUnpackh(DAG, dl, VT, V, V);
4951 EltNo -= NumElems/2;
4958 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4959 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4960 MVT VT = V.getSimpleValueType();
4963 if (VT.is128BitVector()) {
4964 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4965 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4966 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4968 } else if (VT.is256BitVector()) {
4969 // To use VPERMILPS to splat scalars, the second half of indicies must
4970 // refer to the higher part, which is a duplication of the lower one,
4971 // because VPERMILPS can only handle in-lane permutations.
4972 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4973 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4975 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4976 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4979 llvm_unreachable("Vector size not supported");
4981 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4984 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4985 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4986 MVT SrcVT = SV->getSimpleValueType(0);
4987 SDValue V1 = SV->getOperand(0);
4990 int EltNo = SV->getSplatIndex();
4991 int NumElems = SrcVT.getVectorNumElements();
4992 bool Is256BitVec = SrcVT.is256BitVector();
4994 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4995 "Unknown how to promote splat for type");
4997 // Extract the 128-bit part containing the splat element and update
4998 // the splat element index when it refers to the higher register.
5000 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5001 if (EltNo >= NumElems/2)
5002 EltNo -= NumElems/2;
5005 // All i16 and i8 vector types can't be used directly by a generic shuffle
5006 // instruction because the target has no such instruction. Generate shuffles
5007 // which repeat i16 and i8 several times until they fit in i32, and then can
5008 // be manipulated by target suported shuffles.
5009 MVT EltVT = SrcVT.getVectorElementType();
5010 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5011 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5013 // Recreate the 256-bit vector and place the same 128-bit vector
5014 // into the low and high part. This is necessary because we want
5015 // to use VPERM* to shuffle the vectors
5017 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5020 return getLegalSplat(DAG, V1, EltNo);
5023 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5024 /// vector of zero or undef vector. This produces a shuffle where the low
5025 /// element of V2 is swizzled into the zero/undef vector, landing at element
5026 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5027 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5029 const X86Subtarget *Subtarget,
5030 SelectionDAG &DAG) {
5031 MVT VT = V2.getSimpleValueType();
5033 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5034 unsigned NumElems = VT.getVectorNumElements();
5035 SmallVector<int, 16> MaskVec;
5036 for (unsigned i = 0; i != NumElems; ++i)
5037 // If this is the insertion idx, put the low elt of V2 here.
5038 MaskVec.push_back(i == Idx ? NumElems : i);
5039 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5042 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5043 /// target specific opcode. Returns true if the Mask could be calculated.
5044 /// Sets IsUnary to true if only uses one source.
5045 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5046 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5047 unsigned NumElems = VT.getVectorNumElements();
5051 switch(N->getOpcode()) {
5053 ImmN = N->getOperand(N->getNumOperands()-1);
5054 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5056 case X86ISD::UNPCKH:
5057 DecodeUNPCKHMask(VT, Mask);
5059 case X86ISD::UNPCKL:
5060 DecodeUNPCKLMask(VT, Mask);
5062 case X86ISD::MOVHLPS:
5063 DecodeMOVHLPSMask(NumElems, Mask);
5065 case X86ISD::MOVLHPS:
5066 DecodeMOVLHPSMask(NumElems, Mask);
5068 case X86ISD::PALIGNR:
5069 ImmN = N->getOperand(N->getNumOperands()-1);
5070 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5072 case X86ISD::PSHUFD:
5073 case X86ISD::VPERMILP:
5074 ImmN = N->getOperand(N->getNumOperands()-1);
5075 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5078 case X86ISD::PSHUFHW:
5079 ImmN = N->getOperand(N->getNumOperands()-1);
5080 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5083 case X86ISD::PSHUFLW:
5084 ImmN = N->getOperand(N->getNumOperands()-1);
5085 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5088 case X86ISD::VPERMI:
5089 ImmN = N->getOperand(N->getNumOperands()-1);
5090 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5094 case X86ISD::MOVSD: {
5095 // The index 0 always comes from the first element of the second source,
5096 // this is why MOVSS and MOVSD are used in the first place. The other
5097 // elements come from the other positions of the first source vector
5098 Mask.push_back(NumElems);
5099 for (unsigned i = 1; i != NumElems; ++i) {
5104 case X86ISD::VPERM2X128:
5105 ImmN = N->getOperand(N->getNumOperands()-1);
5106 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5107 if (Mask.empty()) return false;
5109 case X86ISD::MOVDDUP:
5110 case X86ISD::MOVLHPD:
5111 case X86ISD::MOVLPD:
5112 case X86ISD::MOVLPS:
5113 case X86ISD::MOVSHDUP:
5114 case X86ISD::MOVSLDUP:
5115 // Not yet implemented
5117 default: llvm_unreachable("unknown target shuffle node");
5123 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5124 /// element of the result of the vector shuffle.
5125 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5128 return SDValue(); // Limit search depth.
5130 SDValue V = SDValue(N, 0);
5131 EVT VT = V.getValueType();
5132 unsigned Opcode = V.getOpcode();
5134 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5135 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5136 int Elt = SV->getMaskElt(Index);
5139 return DAG.getUNDEF(VT.getVectorElementType());
5141 unsigned NumElems = VT.getVectorNumElements();
5142 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5143 : SV->getOperand(1);
5144 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5147 // Recurse into target specific vector shuffles to find scalars.
5148 if (isTargetShuffle(Opcode)) {
5149 MVT ShufVT = V.getSimpleValueType();
5150 unsigned NumElems = ShufVT.getVectorNumElements();
5151 SmallVector<int, 16> ShuffleMask;
5154 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5157 int Elt = ShuffleMask[Index];
5159 return DAG.getUNDEF(ShufVT.getVectorElementType());
5161 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5163 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5167 // Actual nodes that may contain scalar elements
5168 if (Opcode == ISD::BITCAST) {
5169 V = V.getOperand(0);
5170 EVT SrcVT = V.getValueType();
5171 unsigned NumElems = VT.getVectorNumElements();
5173 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5177 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5178 return (Index == 0) ? V.getOperand(0)
5179 : DAG.getUNDEF(VT.getVectorElementType());
5181 if (V.getOpcode() == ISD::BUILD_VECTOR)
5182 return V.getOperand(Index);
5187 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5188 /// shuffle operation which come from a consecutively from a zero. The
5189 /// search can start in two different directions, from left or right.
5190 /// We count undefs as zeros until PreferredNum is reached.
5191 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5192 unsigned NumElems, bool ZerosFromLeft,
5194 unsigned PreferredNum = -1U) {
5195 unsigned NumZeros = 0;
5196 for (unsigned i = 0; i != NumElems; ++i) {
5197 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5198 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5202 if (X86::isZeroNode(Elt))
5204 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5205 NumZeros = std::min(NumZeros + 1, PreferredNum);
5213 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5214 /// correspond consecutively to elements from one of the vector operands,
5215 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5217 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5218 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5219 unsigned NumElems, unsigned &OpNum) {
5220 bool SeenV1 = false;
5221 bool SeenV2 = false;
5223 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5224 int Idx = SVOp->getMaskElt(i);
5225 // Ignore undef indicies
5229 if (Idx < (int)NumElems)
5234 // Only accept consecutive elements from the same vector
5235 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5239 OpNum = SeenV1 ? 0 : 1;
5243 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5244 /// logical left shift of a vector.
5245 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5246 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5248 SVOp->getSimpleValueType(0).getVectorNumElements();
5249 unsigned NumZeros = getNumOfConsecutiveZeros(
5250 SVOp, NumElems, false /* check zeros from right */, DAG,
5251 SVOp->getMaskElt(0));
5257 // Considering the elements in the mask that are not consecutive zeros,
5258 // check if they consecutively come from only one of the source vectors.
5260 // V1 = {X, A, B, C} 0
5262 // vector_shuffle V1, V2 <1, 2, 3, X>
5264 if (!isShuffleMaskConsecutive(SVOp,
5265 0, // Mask Start Index
5266 NumElems-NumZeros, // Mask End Index(exclusive)
5267 NumZeros, // Where to start looking in the src vector
5268 NumElems, // Number of elements in vector
5269 OpSrc)) // Which source operand ?
5274 ShVal = SVOp->getOperand(OpSrc);
5278 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5279 /// logical left shift of a vector.
5280 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5281 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5283 SVOp->getSimpleValueType(0).getVectorNumElements();
5284 unsigned NumZeros = getNumOfConsecutiveZeros(
5285 SVOp, NumElems, true /* check zeros from left */, DAG,
5286 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5292 // Considering the elements in the mask that are not consecutive zeros,
5293 // check if they consecutively come from only one of the source vectors.
5295 // 0 { A, B, X, X } = V2
5297 // vector_shuffle V1, V2 <X, X, 4, 5>
5299 if (!isShuffleMaskConsecutive(SVOp,
5300 NumZeros, // Mask Start Index
5301 NumElems, // Mask End Index(exclusive)
5302 0, // Where to start looking in the src vector
5303 NumElems, // Number of elements in vector
5304 OpSrc)) // Which source operand ?
5309 ShVal = SVOp->getOperand(OpSrc);
5313 /// isVectorShift - Returns true if the shuffle can be implemented as a
5314 /// logical left or right shift of a vector.
5315 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5316 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5317 // Although the logic below support any bitwidth size, there are no
5318 // shift instructions which handle more than 128-bit vectors.
5319 if (!SVOp->getSimpleValueType(0).is128BitVector())
5322 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5323 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5329 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5331 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5332 unsigned NumNonZero, unsigned NumZero,
5334 const X86Subtarget* Subtarget,
5335 const TargetLowering &TLI) {
5342 for (unsigned i = 0; i < 16; ++i) {
5343 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5344 if (ThisIsNonZero && First) {
5346 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5348 V = DAG.getUNDEF(MVT::v8i16);
5353 SDValue ThisElt, LastElt;
5354 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5355 if (LastIsNonZero) {
5356 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5357 MVT::i16, Op.getOperand(i-1));
5359 if (ThisIsNonZero) {
5360 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5361 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5362 ThisElt, DAG.getConstant(8, MVT::i8));
5364 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5368 if (ThisElt.getNode())
5369 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5370 DAG.getIntPtrConstant(i/2));
5374 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5377 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5379 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5380 unsigned NumNonZero, unsigned NumZero,
5382 const X86Subtarget* Subtarget,
5383 const TargetLowering &TLI) {
5390 for (unsigned i = 0; i < 8; ++i) {
5391 bool isNonZero = (NonZeros & (1 << i)) != 0;
5395 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5397 V = DAG.getUNDEF(MVT::v8i16);
5400 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5401 MVT::v8i16, V, Op.getOperand(i),
5402 DAG.getIntPtrConstant(i));
5409 /// getVShift - Return a vector logical shift node.
5411 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5412 unsigned NumBits, SelectionDAG &DAG,
5413 const TargetLowering &TLI, SDLoc dl) {
5414 assert(VT.is128BitVector() && "Unknown type for VShift");
5415 EVT ShVT = MVT::v2i64;
5416 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5417 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5418 return DAG.getNode(ISD::BITCAST, dl, VT,
5419 DAG.getNode(Opc, dl, ShVT, SrcOp,
5420 DAG.getConstant(NumBits,
5421 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5425 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5427 // Check if the scalar load can be widened into a vector load. And if
5428 // the address is "base + cst" see if the cst can be "absorbed" into
5429 // the shuffle mask.
5430 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5431 SDValue Ptr = LD->getBasePtr();
5432 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5434 EVT PVT = LD->getValueType(0);
5435 if (PVT != MVT::i32 && PVT != MVT::f32)
5440 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5441 FI = FINode->getIndex();
5443 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5444 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5445 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5446 Offset = Ptr.getConstantOperandVal(1);
5447 Ptr = Ptr.getOperand(0);
5452 // FIXME: 256-bit vector instructions don't require a strict alignment,
5453 // improve this code to support it better.
5454 unsigned RequiredAlign = VT.getSizeInBits()/8;
5455 SDValue Chain = LD->getChain();
5456 // Make sure the stack object alignment is at least 16 or 32.
5457 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5458 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5459 if (MFI->isFixedObjectIndex(FI)) {
5460 // Can't change the alignment. FIXME: It's possible to compute
5461 // the exact stack offset and reference FI + adjust offset instead.
5462 // If someone *really* cares about this. That's the way to implement it.
5465 MFI->setObjectAlignment(FI, RequiredAlign);
5469 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5470 // Ptr + (Offset & ~15).
5473 if ((Offset % RequiredAlign) & 3)
5475 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5477 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5478 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5480 int EltNo = (Offset - StartOffset) >> 2;
5481 unsigned NumElems = VT.getVectorNumElements();
5483 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5484 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5485 LD->getPointerInfo().getWithOffset(StartOffset),
5486 false, false, false, 0);
5488 SmallVector<int, 8> Mask;
5489 for (unsigned i = 0; i != NumElems; ++i)
5490 Mask.push_back(EltNo);
5492 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5498 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5499 /// vector of type 'VT', see if the elements can be replaced by a single large
5500 /// load which has the same value as a build_vector whose operands are 'elts'.
5502 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5504 /// FIXME: we'd also like to handle the case where the last elements are zero
5505 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5506 /// There's even a handy isZeroNode for that purpose.
5507 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5508 SDLoc &DL, SelectionDAG &DAG,
5509 bool isAfterLegalize) {
5510 EVT EltVT = VT.getVectorElementType();
5511 unsigned NumElems = Elts.size();
5513 LoadSDNode *LDBase = nullptr;
5514 unsigned LastLoadedElt = -1U;
5516 // For each element in the initializer, see if we've found a load or an undef.
5517 // If we don't find an initial load element, or later load elements are
5518 // non-consecutive, bail out.
5519 for (unsigned i = 0; i < NumElems; ++i) {
5520 SDValue Elt = Elts[i];
5522 if (!Elt.getNode() ||
5523 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5526 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5528 LDBase = cast<LoadSDNode>(Elt.getNode());
5532 if (Elt.getOpcode() == ISD::UNDEF)
5535 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5536 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5541 // If we have found an entire vector of loads and undefs, then return a large
5542 // load of the entire vector width starting at the base pointer. If we found
5543 // consecutive loads for the low half, generate a vzext_load node.
5544 if (LastLoadedElt == NumElems - 1) {
5546 if (isAfterLegalize &&
5547 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5550 SDValue NewLd = SDValue();
5552 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5553 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5554 LDBase->getPointerInfo(),
5555 LDBase->isVolatile(), LDBase->isNonTemporal(),
5556 LDBase->isInvariant(), 0);
5557 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5558 LDBase->getPointerInfo(),
5559 LDBase->isVolatile(), LDBase->isNonTemporal(),
5560 LDBase->isInvariant(), LDBase->getAlignment());
5562 if (LDBase->hasAnyUseOfValue(1)) {
5563 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5565 SDValue(NewLd.getNode(), 1));
5566 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5567 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5568 SDValue(NewLd.getNode(), 1));
5573 if (NumElems == 4 && LastLoadedElt == 1 &&
5574 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5575 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5576 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5578 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5579 array_lengthof(Ops), MVT::i64,
5580 LDBase->getPointerInfo(),
5581 LDBase->getAlignment(),
5582 false/*isVolatile*/, true/*ReadMem*/,
5585 // Make sure the newly-created LOAD is in the same position as LDBase in
5586 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5587 // update uses of LDBase's output chain to use the TokenFactor.
5588 if (LDBase->hasAnyUseOfValue(1)) {
5589 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5590 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5591 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5592 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5593 SDValue(ResNode.getNode(), 1));
5596 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5601 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5602 /// to generate a splat value for the following cases:
5603 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5604 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5605 /// a scalar load, or a constant.
5606 /// The VBROADCAST node is returned when a pattern is found,
5607 /// or SDValue() otherwise.
5608 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5609 SelectionDAG &DAG) {
5610 if (!Subtarget->hasFp256())
5613 MVT VT = Op.getSimpleValueType();
5616 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5617 "Unsupported vector type for broadcast.");
5622 switch (Op.getOpcode()) {
5624 // Unknown pattern found.
5627 case ISD::BUILD_VECTOR: {
5628 // The BUILD_VECTOR node must be a splat.
5629 if (!isSplatVector(Op.getNode()))
5632 Ld = Op.getOperand(0);
5633 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5634 Ld.getOpcode() == ISD::ConstantFP);
5636 // The suspected load node has several users. Make sure that all
5637 // of its users are from the BUILD_VECTOR node.
5638 // Constants may have multiple users.
5639 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5644 case ISD::VECTOR_SHUFFLE: {
5645 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5647 // Shuffles must have a splat mask where the first element is
5649 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5652 SDValue Sc = Op.getOperand(0);
5653 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5654 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5656 if (!Subtarget->hasInt256())
5659 // Use the register form of the broadcast instruction available on AVX2.
5660 if (VT.getSizeInBits() >= 256)
5661 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5662 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5665 Ld = Sc.getOperand(0);
5666 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5667 Ld.getOpcode() == ISD::ConstantFP);
5669 // The scalar_to_vector node and the suspected
5670 // load node must have exactly one user.
5671 // Constants may have multiple users.
5673 // AVX-512 has register version of the broadcast
5674 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5675 Ld.getValueType().getSizeInBits() >= 32;
5676 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5683 bool IsGE256 = (VT.getSizeInBits() >= 256);
5685 // Handle the broadcasting a single constant scalar from the constant pool
5686 // into a vector. On Sandybridge it is still better to load a constant vector
5687 // from the constant pool and not to broadcast it from a scalar.
5688 if (ConstSplatVal && Subtarget->hasInt256()) {
5689 EVT CVT = Ld.getValueType();
5690 assert(!CVT.isVector() && "Must not broadcast a vector type");
5691 unsigned ScalarSize = CVT.getSizeInBits();
5693 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5694 const Constant *C = nullptr;
5695 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5696 C = CI->getConstantIntValue();
5697 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5698 C = CF->getConstantFPValue();
5700 assert(C && "Invalid constant type");
5702 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5703 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5704 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5705 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5706 MachinePointerInfo::getConstantPool(),
5707 false, false, false, Alignment);
5709 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5713 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5714 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5716 // Handle AVX2 in-register broadcasts.
5717 if (!IsLoad && Subtarget->hasInt256() &&
5718 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5719 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5721 // The scalar source must be a normal load.
5725 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5726 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5728 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5729 // double since there is no vbroadcastsd xmm
5730 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5731 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5732 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5735 // Unsupported broadcast.
5739 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5740 /// underlying vector and index.
5742 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5744 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5746 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5747 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5750 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5752 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5754 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5755 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5758 // In this case the vector is the extract_subvector expression and the index
5759 // is 2, as specified by the shuffle.
5760 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5761 SDValue ShuffleVec = SVOp->getOperand(0);
5762 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5763 assert(ShuffleVecVT.getVectorElementType() ==
5764 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5766 int ShuffleIdx = SVOp->getMaskElt(Idx);
5767 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5768 ExtractedFromVec = ShuffleVec;
5774 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5775 MVT VT = Op.getSimpleValueType();
5777 // Skip if insert_vec_elt is not supported.
5778 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5779 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5783 unsigned NumElems = Op.getNumOperands();
5787 SmallVector<unsigned, 4> InsertIndices;
5788 SmallVector<int, 8> Mask(NumElems, -1);
5790 for (unsigned i = 0; i != NumElems; ++i) {
5791 unsigned Opc = Op.getOperand(i).getOpcode();
5793 if (Opc == ISD::UNDEF)
5796 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5797 // Quit if more than 1 elements need inserting.
5798 if (InsertIndices.size() > 1)
5801 InsertIndices.push_back(i);
5805 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5806 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5807 // Quit if non-constant index.
5808 if (!isa<ConstantSDNode>(ExtIdx))
5810 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5812 // Quit if extracted from vector of different type.
5813 if (ExtractedFromVec.getValueType() != VT)
5816 if (!VecIn1.getNode())
5817 VecIn1 = ExtractedFromVec;
5818 else if (VecIn1 != ExtractedFromVec) {
5819 if (!VecIn2.getNode())
5820 VecIn2 = ExtractedFromVec;
5821 else if (VecIn2 != ExtractedFromVec)
5822 // Quit if more than 2 vectors to shuffle
5826 if (ExtractedFromVec == VecIn1)
5828 else if (ExtractedFromVec == VecIn2)
5829 Mask[i] = Idx + NumElems;
5832 if (!VecIn1.getNode())
5835 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5836 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5837 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5838 unsigned Idx = InsertIndices[i];
5839 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5840 DAG.getIntPtrConstant(Idx));
5846 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5848 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5850 MVT VT = Op.getSimpleValueType();
5851 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5852 "Unexpected type in LowerBUILD_VECTORvXi1!");
5855 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5856 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5857 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5858 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5859 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5860 Ops, VT.getVectorNumElements());
5863 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5864 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5865 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5866 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5867 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5868 Ops, VT.getVectorNumElements());
5871 bool AllContants = true;
5872 uint64_t Immediate = 0;
5873 int NonConstIdx = -1;
5874 bool IsSplat = true;
5875 unsigned NumNonConsts = 0;
5876 unsigned NumConsts = 0;
5877 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5878 SDValue In = Op.getOperand(idx);
5879 if (In.getOpcode() == ISD::UNDEF)
5881 if (!isa<ConstantSDNode>(In)) {
5882 AllContants = false;
5888 if (cast<ConstantSDNode>(In)->getZExtValue())
5889 Immediate |= (1ULL << idx);
5891 if (In != Op.getOperand(0))
5896 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5897 DAG.getConstant(Immediate, MVT::i16));
5898 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5899 DAG.getIntPtrConstant(0));
5902 if (NumNonConsts == 1 && NonConstIdx != 0) {
5905 SDValue VecAsImm = DAG.getConstant(Immediate,
5906 MVT::getIntegerVT(VT.getSizeInBits()));
5907 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5910 DstVec = DAG.getUNDEF(VT);
5911 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5912 Op.getOperand(NonConstIdx),
5913 DAG.getIntPtrConstant(NonConstIdx));
5915 if (!IsSplat && (NonConstIdx != 0))
5916 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5917 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5920 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5921 DAG.getConstant(-1, SelectVT),
5922 DAG.getConstant(0, SelectVT));
5924 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5925 DAG.getConstant((Immediate | 1), SelectVT),
5926 DAG.getConstant(Immediate, SelectVT));
5927 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5931 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5934 MVT VT = Op.getSimpleValueType();
5935 MVT ExtVT = VT.getVectorElementType();
5936 unsigned NumElems = Op.getNumOperands();
5938 // Generate vectors for predicate vectors.
5939 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5940 return LowerBUILD_VECTORvXi1(Op, DAG);
5942 // Vectors containing all zeros can be matched by pxor and xorps later
5943 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5944 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5945 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5946 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5949 return getZeroVector(VT, Subtarget, DAG, dl);
5952 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5953 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5954 // vpcmpeqd on 256-bit vectors.
5955 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5956 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5959 if (!VT.is512BitVector())
5960 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5963 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5964 if (Broadcast.getNode())
5967 unsigned EVTBits = ExtVT.getSizeInBits();
5969 unsigned NumZero = 0;
5970 unsigned NumNonZero = 0;
5971 unsigned NonZeros = 0;
5972 bool IsAllConstants = true;
5973 SmallSet<SDValue, 8> Values;
5974 for (unsigned i = 0; i < NumElems; ++i) {
5975 SDValue Elt = Op.getOperand(i);
5976 if (Elt.getOpcode() == ISD::UNDEF)
5979 if (Elt.getOpcode() != ISD::Constant &&
5980 Elt.getOpcode() != ISD::ConstantFP)
5981 IsAllConstants = false;
5982 if (X86::isZeroNode(Elt))
5985 NonZeros |= (1 << i);
5990 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5991 if (NumNonZero == 0)
5992 return DAG.getUNDEF(VT);
5994 // Special case for single non-zero, non-undef, element.
5995 if (NumNonZero == 1) {
5996 unsigned Idx = countTrailingZeros(NonZeros);
5997 SDValue Item = Op.getOperand(Idx);
5999 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6000 // the value are obviously zero, truncate the value to i32 and do the
6001 // insertion that way. Only do this if the value is non-constant or if the
6002 // value is a constant being inserted into element 0. It is cheaper to do
6003 // a constant pool load than it is to do a movd + shuffle.
6004 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6005 (!IsAllConstants || Idx == 0)) {
6006 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6008 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6009 EVT VecVT = MVT::v4i32;
6010 unsigned VecElts = 4;
6012 // Truncate the value (which may itself be a constant) to i32, and
6013 // convert it to a vector with movd (S2V+shuffle to zero extend).
6014 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6015 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6016 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6018 // Now we have our 32-bit value zero extended in the low element of
6019 // a vector. If Idx != 0, swizzle it into place.
6021 SmallVector<int, 4> Mask;
6022 Mask.push_back(Idx);
6023 for (unsigned i = 1; i != VecElts; ++i)
6025 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6028 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6032 // If we have a constant or non-constant insertion into the low element of
6033 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6034 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6035 // depending on what the source datatype is.
6038 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6040 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6041 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6042 if (VT.is256BitVector() || VT.is512BitVector()) {
6043 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6044 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6045 Item, DAG.getIntPtrConstant(0));
6047 assert(VT.is128BitVector() && "Expected an SSE value type!");
6048 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6049 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6050 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6053 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6054 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6055 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6056 if (VT.is256BitVector()) {
6057 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6058 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6060 assert(VT.is128BitVector() && "Expected an SSE value type!");
6061 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6063 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6067 // Is it a vector logical left shift?
6068 if (NumElems == 2 && Idx == 1 &&
6069 X86::isZeroNode(Op.getOperand(0)) &&
6070 !X86::isZeroNode(Op.getOperand(1))) {
6071 unsigned NumBits = VT.getSizeInBits();
6072 return getVShift(true, VT,
6073 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6074 VT, Op.getOperand(1)),
6075 NumBits/2, DAG, *this, dl);
6078 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6081 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6082 // is a non-constant being inserted into an element other than the low one,
6083 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6084 // movd/movss) to move this into the low element, then shuffle it into
6086 if (EVTBits == 32) {
6087 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6089 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6090 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6091 SmallVector<int, 8> MaskVec;
6092 for (unsigned i = 0; i != NumElems; ++i)
6093 MaskVec.push_back(i == Idx ? 0 : 1);
6094 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6098 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6099 if (Values.size() == 1) {
6100 if (EVTBits == 32) {
6101 // Instead of a shuffle like this:
6102 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6103 // Check if it's possible to issue this instead.
6104 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6105 unsigned Idx = countTrailingZeros(NonZeros);
6106 SDValue Item = Op.getOperand(Idx);
6107 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6108 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6113 // A vector full of immediates; various special cases are already
6114 // handled, so this is best done with a single constant-pool load.
6118 // For AVX-length vectors, build the individual 128-bit pieces and use
6119 // shuffles to put them in place.
6120 if (VT.is256BitVector() || VT.is512BitVector()) {
6121 SmallVector<SDValue, 64> V;
6122 for (unsigned i = 0; i != NumElems; ++i)
6123 V.push_back(Op.getOperand(i));
6125 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6127 // Build both the lower and upper subvector.
6128 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6129 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6132 // Recreate the wider vector with the lower and upper part.
6133 if (VT.is256BitVector())
6134 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6135 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6138 // Let legalizer expand 2-wide build_vectors.
6139 if (EVTBits == 64) {
6140 if (NumNonZero == 1) {
6141 // One half is zero or undef.
6142 unsigned Idx = countTrailingZeros(NonZeros);
6143 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6144 Op.getOperand(Idx));
6145 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6150 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6151 if (EVTBits == 8 && NumElems == 16) {
6152 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6154 if (V.getNode()) return V;
6157 if (EVTBits == 16 && NumElems == 8) {
6158 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6160 if (V.getNode()) return V;
6163 // If element VT is == 32 bits, turn it into a number of shuffles.
6164 SmallVector<SDValue, 8> V(NumElems);
6165 if (NumElems == 4 && NumZero > 0) {
6166 for (unsigned i = 0; i < 4; ++i) {
6167 bool isZero = !(NonZeros & (1 << i));
6169 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6171 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6174 for (unsigned i = 0; i < 2; ++i) {
6175 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6178 V[i] = V[i*2]; // Must be a zero vector.
6181 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6184 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6187 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6192 bool Reverse1 = (NonZeros & 0x3) == 2;
6193 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6197 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6198 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6200 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6203 if (Values.size() > 1 && VT.is128BitVector()) {
6204 // Check for a build vector of consecutive loads.
6205 for (unsigned i = 0; i < NumElems; ++i)
6206 V[i] = Op.getOperand(i);
6208 // Check for elements which are consecutive loads.
6209 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6213 // Check for a build vector from mostly shuffle plus few inserting.
6214 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6218 // For SSE 4.1, use insertps to put the high elements into the low element.
6219 if (getSubtarget()->hasSSE41()) {
6221 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6222 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6224 Result = DAG.getUNDEF(VT);
6226 for (unsigned i = 1; i < NumElems; ++i) {
6227 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6228 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6229 Op.getOperand(i), DAG.getIntPtrConstant(i));
6234 // Otherwise, expand into a number of unpckl*, start by extending each of
6235 // our (non-undef) elements to the full vector width with the element in the
6236 // bottom slot of the vector (which generates no code for SSE).
6237 for (unsigned i = 0; i < NumElems; ++i) {
6238 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6239 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6241 V[i] = DAG.getUNDEF(VT);
6244 // Next, we iteratively mix elements, e.g. for v4f32:
6245 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6246 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6247 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6248 unsigned EltStride = NumElems >> 1;
6249 while (EltStride != 0) {
6250 for (unsigned i = 0; i < EltStride; ++i) {
6251 // If V[i+EltStride] is undef and this is the first round of mixing,
6252 // then it is safe to just drop this shuffle: V[i] is already in the
6253 // right place, the one element (since it's the first round) being
6254 // inserted as undef can be dropped. This isn't safe for successive
6255 // rounds because they will permute elements within both vectors.
6256 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6257 EltStride == NumElems/2)
6260 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6269 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6270 // to create 256-bit vectors from two other 128-bit ones.
6271 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6273 MVT ResVT = Op.getSimpleValueType();
6275 assert((ResVT.is256BitVector() ||
6276 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6278 SDValue V1 = Op.getOperand(0);
6279 SDValue V2 = Op.getOperand(1);
6280 unsigned NumElems = ResVT.getVectorNumElements();
6281 if(ResVT.is256BitVector())
6282 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6284 if (Op.getNumOperands() == 4) {
6285 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6286 ResVT.getVectorNumElements()/2);
6287 SDValue V3 = Op.getOperand(2);
6288 SDValue V4 = Op.getOperand(3);
6289 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6290 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6292 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6295 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6296 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6297 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6298 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6299 Op.getNumOperands() == 4)));
6301 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6302 // from two other 128-bit ones.
6304 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6305 return LowerAVXCONCAT_VECTORS(Op, DAG);
6308 // Try to lower a shuffle node into a simple blend instruction.
6310 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6311 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6312 SDValue V1 = SVOp->getOperand(0);
6313 SDValue V2 = SVOp->getOperand(1);
6315 MVT VT = SVOp->getSimpleValueType(0);
6316 MVT EltVT = VT.getVectorElementType();
6317 unsigned NumElems = VT.getVectorNumElements();
6319 // There is no blend with immediate in AVX-512.
6320 if (VT.is512BitVector())
6323 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6325 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6328 // Check the mask for BLEND and build the value.
6329 unsigned MaskValue = 0;
6330 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6331 unsigned NumLanes = (NumElems-1)/8 + 1;
6332 unsigned NumElemsInLane = NumElems / NumLanes;
6334 // Blend for v16i16 should be symetric for the both lanes.
6335 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6337 int SndLaneEltIdx = (NumLanes == 2) ?
6338 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6339 int EltIdx = SVOp->getMaskElt(i);
6341 if ((EltIdx < 0 || EltIdx == (int)i) &&
6342 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6345 if (((unsigned)EltIdx == (i + NumElems)) &&
6346 (SndLaneEltIdx < 0 ||
6347 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6348 MaskValue |= (1<<i);
6353 // Convert i32 vectors to floating point if it is not AVX2.
6354 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6356 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6357 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6359 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6360 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6363 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6364 DAG.getConstant(MaskValue, MVT::i32));
6365 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6368 /// In vector type \p VT, return true if the element at index \p InputIdx
6369 /// falls on a different 128-bit lane than \p OutputIdx.
6370 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6371 unsigned OutputIdx) {
6372 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6373 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6376 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6377 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6378 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6379 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6381 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6382 SelectionDAG &DAG) {
6383 MVT VT = V1.getSimpleValueType();
6384 assert(VT.is128BitVector() || VT.is256BitVector());
6386 MVT EltVT = VT.getVectorElementType();
6387 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6388 unsigned NumElts = VT.getVectorNumElements();
6390 SmallVector<SDValue, 32> PshufbMask;
6391 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6392 int InputIdx = MaskVals[OutputIdx];
6393 unsigned InputByteIdx;
6395 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6396 InputByteIdx = 0x80;
6398 // Cross lane is not allowed.
6399 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6401 InputByteIdx = InputIdx * EltSizeInBytes;
6402 // Index is an byte offset within the 128-bit lane.
6403 InputByteIdx &= 0xf;
6406 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6407 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6408 if (InputByteIdx != 0x80)
6413 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6415 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6416 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6417 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6418 PshufbMask.data(), PshufbMask.size()));
6421 // v8i16 shuffles - Prefer shuffles in the following order:
6422 // 1. [all] pshuflw, pshufhw, optional move
6423 // 2. [ssse3] 1 x pshufb
6424 // 3. [ssse3] 2 x pshufb + 1 x por
6425 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6427 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6428 SelectionDAG &DAG) {
6429 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6430 SDValue V1 = SVOp->getOperand(0);
6431 SDValue V2 = SVOp->getOperand(1);
6433 SmallVector<int, 8> MaskVals;
6435 // Determine if more than 1 of the words in each of the low and high quadwords
6436 // of the result come from the same quadword of one of the two inputs. Undef
6437 // mask values count as coming from any quadword, for better codegen.
6439 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6440 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6441 unsigned LoQuad[] = { 0, 0, 0, 0 };
6442 unsigned HiQuad[] = { 0, 0, 0, 0 };
6443 // Indices of quads used.
6444 std::bitset<4> InputQuads;
6445 for (unsigned i = 0; i < 8; ++i) {
6446 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6447 int EltIdx = SVOp->getMaskElt(i);
6448 MaskVals.push_back(EltIdx);
6457 InputQuads.set(EltIdx / 4);
6460 int BestLoQuad = -1;
6461 unsigned MaxQuad = 1;
6462 for (unsigned i = 0; i < 4; ++i) {
6463 if (LoQuad[i] > MaxQuad) {
6465 MaxQuad = LoQuad[i];
6469 int BestHiQuad = -1;
6471 for (unsigned i = 0; i < 4; ++i) {
6472 if (HiQuad[i] > MaxQuad) {
6474 MaxQuad = HiQuad[i];
6478 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6479 // of the two input vectors, shuffle them into one input vector so only a
6480 // single pshufb instruction is necessary. If there are more than 2 input
6481 // quads, disable the next transformation since it does not help SSSE3.
6482 bool V1Used = InputQuads[0] || InputQuads[1];
6483 bool V2Used = InputQuads[2] || InputQuads[3];
6484 if (Subtarget->hasSSSE3()) {
6485 if (InputQuads.count() == 2 && V1Used && V2Used) {
6486 BestLoQuad = InputQuads[0] ? 0 : 1;
6487 BestHiQuad = InputQuads[2] ? 2 : 3;
6489 if (InputQuads.count() > 2) {
6495 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6496 // the shuffle mask. If a quad is scored as -1, that means that it contains
6497 // words from all 4 input quadwords.
6499 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6501 BestLoQuad < 0 ? 0 : BestLoQuad,
6502 BestHiQuad < 0 ? 1 : BestHiQuad
6504 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6505 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6506 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6507 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6509 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6510 // source words for the shuffle, to aid later transformations.
6511 bool AllWordsInNewV = true;
6512 bool InOrder[2] = { true, true };
6513 for (unsigned i = 0; i != 8; ++i) {
6514 int idx = MaskVals[i];
6516 InOrder[i/4] = false;
6517 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6519 AllWordsInNewV = false;
6523 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6524 if (AllWordsInNewV) {
6525 for (int i = 0; i != 8; ++i) {
6526 int idx = MaskVals[i];
6529 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6530 if ((idx != i) && idx < 4)
6532 if ((idx != i) && idx > 3)
6541 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6542 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6543 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6544 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6545 unsigned TargetMask = 0;
6546 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6547 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6548 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6549 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6550 getShufflePSHUFLWImmediate(SVOp);
6551 V1 = NewV.getOperand(0);
6552 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6556 // Promote splats to a larger type which usually leads to more efficient code.
6557 // FIXME: Is this true if pshufb is available?
6558 if (SVOp->isSplat())
6559 return PromoteSplat(SVOp, DAG);
6561 // If we have SSSE3, and all words of the result are from 1 input vector,
6562 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6563 // is present, fall back to case 4.
6564 if (Subtarget->hasSSSE3()) {
6565 SmallVector<SDValue,16> pshufbMask;
6567 // If we have elements from both input vectors, set the high bit of the
6568 // shuffle mask element to zero out elements that come from V2 in the V1
6569 // mask, and elements that come from V1 in the V2 mask, so that the two
6570 // results can be OR'd together.
6571 bool TwoInputs = V1Used && V2Used;
6572 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6574 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6576 // Calculate the shuffle mask for the second input, shuffle it, and
6577 // OR it with the first shuffled input.
6578 CommuteVectorShuffleMask(MaskVals, 8);
6579 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6580 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6581 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6584 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6585 // and update MaskVals with new element order.
6586 std::bitset<8> InOrder;
6587 if (BestLoQuad >= 0) {
6588 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6589 for (int i = 0; i != 4; ++i) {
6590 int idx = MaskVals[i];
6593 } else if ((idx / 4) == BestLoQuad) {
6598 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6601 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6602 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6603 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6605 getShufflePSHUFLWImmediate(SVOp), DAG);
6609 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6610 // and update MaskVals with the new element order.
6611 if (BestHiQuad >= 0) {
6612 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6613 for (unsigned i = 4; i != 8; ++i) {
6614 int idx = MaskVals[i];
6617 } else if ((idx / 4) == BestHiQuad) {
6618 MaskV[i] = (idx & 3) + 4;
6622 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6625 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6626 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6627 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6629 getShufflePSHUFHWImmediate(SVOp), DAG);
6633 // In case BestHi & BestLo were both -1, which means each quadword has a word
6634 // from each of the four input quadwords, calculate the InOrder bitvector now
6635 // before falling through to the insert/extract cleanup.
6636 if (BestLoQuad == -1 && BestHiQuad == -1) {
6638 for (int i = 0; i != 8; ++i)
6639 if (MaskVals[i] < 0 || MaskVals[i] == i)
6643 // The other elements are put in the right place using pextrw and pinsrw.
6644 for (unsigned i = 0; i != 8; ++i) {
6647 int EltIdx = MaskVals[i];
6650 SDValue ExtOp = (EltIdx < 8) ?
6651 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6652 DAG.getIntPtrConstant(EltIdx)) :
6653 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6654 DAG.getIntPtrConstant(EltIdx - 8));
6655 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6656 DAG.getIntPtrConstant(i));
6661 /// \brief v16i16 shuffles
6663 /// FIXME: We only support generation of a single pshufb currently. We can
6664 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6665 /// well (e.g 2 x pshufb + 1 x por).
6667 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6668 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6669 SDValue V1 = SVOp->getOperand(0);
6670 SDValue V2 = SVOp->getOperand(1);
6673 if (V2.getOpcode() != ISD::UNDEF)
6676 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6677 return getPSHUFB(MaskVals, V1, dl, DAG);
6680 // v16i8 shuffles - Prefer shuffles in the following order:
6681 // 1. [ssse3] 1 x pshufb
6682 // 2. [ssse3] 2 x pshufb + 1 x por
6683 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6684 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6685 const X86Subtarget* Subtarget,
6686 SelectionDAG &DAG) {
6687 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6688 SDValue V1 = SVOp->getOperand(0);
6689 SDValue V2 = SVOp->getOperand(1);
6691 ArrayRef<int> MaskVals = SVOp->getMask();
6693 // Promote splats to a larger type which usually leads to more efficient code.
6694 // FIXME: Is this true if pshufb is available?
6695 if (SVOp->isSplat())
6696 return PromoteSplat(SVOp, DAG);
6698 // If we have SSSE3, case 1 is generated when all result bytes come from
6699 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6700 // present, fall back to case 3.
6702 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6703 if (Subtarget->hasSSSE3()) {
6704 SmallVector<SDValue,16> pshufbMask;
6706 // If all result elements are from one input vector, then only translate
6707 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6709 // Otherwise, we have elements from both input vectors, and must zero out
6710 // elements that come from V2 in the first mask, and V1 in the second mask
6711 // so that we can OR them together.
6712 for (unsigned i = 0; i != 16; ++i) {
6713 int EltIdx = MaskVals[i];
6714 if (EltIdx < 0 || EltIdx >= 16)
6716 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6718 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6719 DAG.getNode(ISD::BUILD_VECTOR, dl,
6720 MVT::v16i8, &pshufbMask[0], 16));
6722 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6723 // the 2nd operand if it's undefined or zero.
6724 if (V2.getOpcode() == ISD::UNDEF ||
6725 ISD::isBuildVectorAllZeros(V2.getNode()))
6728 // Calculate the shuffle mask for the second input, shuffle it, and
6729 // OR it with the first shuffled input.
6731 for (unsigned i = 0; i != 16; ++i) {
6732 int EltIdx = MaskVals[i];
6733 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6734 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6736 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6737 DAG.getNode(ISD::BUILD_VECTOR, dl,
6738 MVT::v16i8, &pshufbMask[0], 16));
6739 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6742 // No SSSE3 - Calculate in place words and then fix all out of place words
6743 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6744 // the 16 different words that comprise the two doublequadword input vectors.
6745 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6746 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6748 for (int i = 0; i != 8; ++i) {
6749 int Elt0 = MaskVals[i*2];
6750 int Elt1 = MaskVals[i*2+1];
6752 // This word of the result is all undef, skip it.
6753 if (Elt0 < 0 && Elt1 < 0)
6756 // This word of the result is already in the correct place, skip it.
6757 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6760 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6761 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6764 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6765 // using a single extract together, load it and store it.
6766 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6767 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6768 DAG.getIntPtrConstant(Elt1 / 2));
6769 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6770 DAG.getIntPtrConstant(i));
6774 // If Elt1 is defined, extract it from the appropriate source. If the
6775 // source byte is not also odd, shift the extracted word left 8 bits
6776 // otherwise clear the bottom 8 bits if we need to do an or.
6778 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6779 DAG.getIntPtrConstant(Elt1 / 2));
6780 if ((Elt1 & 1) == 0)
6781 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6783 TLI.getShiftAmountTy(InsElt.getValueType())));
6785 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6786 DAG.getConstant(0xFF00, MVT::i16));
6788 // If Elt0 is defined, extract it from the appropriate source. If the
6789 // source byte is not also even, shift the extracted word right 8 bits. If
6790 // Elt1 was also defined, OR the extracted values together before
6791 // inserting them in the result.
6793 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6794 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6795 if ((Elt0 & 1) != 0)
6796 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6798 TLI.getShiftAmountTy(InsElt0.getValueType())));
6800 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6801 DAG.getConstant(0x00FF, MVT::i16));
6802 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6805 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6806 DAG.getIntPtrConstant(i));
6808 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6811 // v32i8 shuffles - Translate to VPSHUFB if possible.
6813 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6814 const X86Subtarget *Subtarget,
6815 SelectionDAG &DAG) {
6816 MVT VT = SVOp->getSimpleValueType(0);
6817 SDValue V1 = SVOp->getOperand(0);
6818 SDValue V2 = SVOp->getOperand(1);
6820 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6822 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6823 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6824 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6826 // VPSHUFB may be generated if
6827 // (1) one of input vector is undefined or zeroinitializer.
6828 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6829 // And (2) the mask indexes don't cross the 128-bit lane.
6830 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6831 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6834 if (V1IsAllZero && !V2IsAllZero) {
6835 CommuteVectorShuffleMask(MaskVals, 32);
6838 return getPSHUFB(MaskVals, V1, dl, DAG);
6841 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6842 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6843 /// done when every pair / quad of shuffle mask elements point to elements in
6844 /// the right sequence. e.g.
6845 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6847 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6848 SelectionDAG &DAG) {
6849 MVT VT = SVOp->getSimpleValueType(0);
6851 unsigned NumElems = VT.getVectorNumElements();
6854 switch (VT.SimpleTy) {
6855 default: llvm_unreachable("Unexpected!");
6856 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6857 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6858 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6859 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6860 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6861 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6864 SmallVector<int, 8> MaskVec;
6865 for (unsigned i = 0; i != NumElems; i += Scale) {
6867 for (unsigned j = 0; j != Scale; ++j) {
6868 int EltIdx = SVOp->getMaskElt(i+j);
6872 StartIdx = (EltIdx / Scale);
6873 if (EltIdx != (int)(StartIdx*Scale + j))
6876 MaskVec.push_back(StartIdx);
6879 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6880 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6881 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6884 /// getVZextMovL - Return a zero-extending vector move low node.
6886 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6887 SDValue SrcOp, SelectionDAG &DAG,
6888 const X86Subtarget *Subtarget, SDLoc dl) {
6889 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6890 LoadSDNode *LD = nullptr;
6891 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6892 LD = dyn_cast<LoadSDNode>(SrcOp);
6894 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6896 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6897 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6898 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6899 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6900 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6902 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6903 return DAG.getNode(ISD::BITCAST, dl, VT,
6904 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6905 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6913 return DAG.getNode(ISD::BITCAST, dl, VT,
6914 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6915 DAG.getNode(ISD::BITCAST, dl,
6919 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6920 /// which could not be matched by any known target speficic shuffle
6922 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6924 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6925 if (NewOp.getNode())
6928 MVT VT = SVOp->getSimpleValueType(0);
6930 unsigned NumElems = VT.getVectorNumElements();
6931 unsigned NumLaneElems = NumElems / 2;
6934 MVT EltVT = VT.getVectorElementType();
6935 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6938 SmallVector<int, 16> Mask;
6939 for (unsigned l = 0; l < 2; ++l) {
6940 // Build a shuffle mask for the output, discovering on the fly which
6941 // input vectors to use as shuffle operands (recorded in InputUsed).
6942 // If building a suitable shuffle vector proves too hard, then bail
6943 // out with UseBuildVector set.
6944 bool UseBuildVector = false;
6945 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6946 unsigned LaneStart = l * NumLaneElems;
6947 for (unsigned i = 0; i != NumLaneElems; ++i) {
6948 // The mask element. This indexes into the input.
6949 int Idx = SVOp->getMaskElt(i+LaneStart);
6951 // the mask element does not index into any input vector.
6956 // The input vector this mask element indexes into.
6957 int Input = Idx / NumLaneElems;
6959 // Turn the index into an offset from the start of the input vector.
6960 Idx -= Input * NumLaneElems;
6962 // Find or create a shuffle vector operand to hold this input.
6964 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6965 if (InputUsed[OpNo] == Input)
6966 // This input vector is already an operand.
6968 if (InputUsed[OpNo] < 0) {
6969 // Create a new operand for this input vector.
6970 InputUsed[OpNo] = Input;
6975 if (OpNo >= array_lengthof(InputUsed)) {
6976 // More than two input vectors used! Give up on trying to create a
6977 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6978 UseBuildVector = true;
6982 // Add the mask index for the new shuffle vector.
6983 Mask.push_back(Idx + OpNo * NumLaneElems);
6986 if (UseBuildVector) {
6987 SmallVector<SDValue, 16> SVOps;
6988 for (unsigned i = 0; i != NumLaneElems; ++i) {
6989 // The mask element. This indexes into the input.
6990 int Idx = SVOp->getMaskElt(i+LaneStart);
6992 SVOps.push_back(DAG.getUNDEF(EltVT));
6996 // The input vector this mask element indexes into.
6997 int Input = Idx / NumElems;
6999 // Turn the index into an offset from the start of the input vector.
7000 Idx -= Input * NumElems;
7002 // Extract the vector element by hand.
7003 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7004 SVOp->getOperand(Input),
7005 DAG.getIntPtrConstant(Idx)));
7008 // Construct the output using a BUILD_VECTOR.
7009 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
7011 } else if (InputUsed[0] < 0) {
7012 // No input vectors were used! The result is undefined.
7013 Output[l] = DAG.getUNDEF(NVT);
7015 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7016 (InputUsed[0] % 2) * NumLaneElems,
7018 // If only one input was used, use an undefined vector for the other.
7019 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7020 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7021 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7022 // At least one input vector was used. Create a new shuffle vector.
7023 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7029 // Concatenate the result back
7030 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7033 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7034 /// 4 elements, and match them with several different shuffle types.
7036 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7037 SDValue V1 = SVOp->getOperand(0);
7038 SDValue V2 = SVOp->getOperand(1);
7040 MVT VT = SVOp->getSimpleValueType(0);
7042 assert(VT.is128BitVector() && "Unsupported vector size");
7044 std::pair<int, int> Locs[4];
7045 int Mask1[] = { -1, -1, -1, -1 };
7046 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7050 for (unsigned i = 0; i != 4; ++i) {
7051 int Idx = PermMask[i];
7053 Locs[i] = std::make_pair(-1, -1);
7055 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7057 Locs[i] = std::make_pair(0, NumLo);
7061 Locs[i] = std::make_pair(1, NumHi);
7063 Mask1[2+NumHi] = Idx;
7069 if (NumLo <= 2 && NumHi <= 2) {
7070 // If no more than two elements come from either vector. This can be
7071 // implemented with two shuffles. First shuffle gather the elements.
7072 // The second shuffle, which takes the first shuffle as both of its
7073 // vector operands, put the elements into the right order.
7074 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7076 int Mask2[] = { -1, -1, -1, -1 };
7078 for (unsigned i = 0; i != 4; ++i)
7079 if (Locs[i].first != -1) {
7080 unsigned Idx = (i < 2) ? 0 : 4;
7081 Idx += Locs[i].first * 2 + Locs[i].second;
7085 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7088 if (NumLo == 3 || NumHi == 3) {
7089 // Otherwise, we must have three elements from one vector, call it X, and
7090 // one element from the other, call it Y. First, use a shufps to build an
7091 // intermediate vector with the one element from Y and the element from X
7092 // that will be in the same half in the final destination (the indexes don't
7093 // matter). Then, use a shufps to build the final vector, taking the half
7094 // containing the element from Y from the intermediate, and the other half
7097 // Normalize it so the 3 elements come from V1.
7098 CommuteVectorShuffleMask(PermMask, 4);
7102 // Find the element from V2.
7104 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7105 int Val = PermMask[HiIndex];
7112 Mask1[0] = PermMask[HiIndex];
7114 Mask1[2] = PermMask[HiIndex^1];
7116 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7119 Mask1[0] = PermMask[0];
7120 Mask1[1] = PermMask[1];
7121 Mask1[2] = HiIndex & 1 ? 6 : 4;
7122 Mask1[3] = HiIndex & 1 ? 4 : 6;
7123 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7126 Mask1[0] = HiIndex & 1 ? 2 : 0;
7127 Mask1[1] = HiIndex & 1 ? 0 : 2;
7128 Mask1[2] = PermMask[2];
7129 Mask1[3] = PermMask[3];
7134 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7137 // Break it into (shuffle shuffle_hi, shuffle_lo).
7138 int LoMask[] = { -1, -1, -1, -1 };
7139 int HiMask[] = { -1, -1, -1, -1 };
7141 int *MaskPtr = LoMask;
7142 unsigned MaskIdx = 0;
7145 for (unsigned i = 0; i != 4; ++i) {
7152 int Idx = PermMask[i];
7154 Locs[i] = std::make_pair(-1, -1);
7155 } else if (Idx < 4) {
7156 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7157 MaskPtr[LoIdx] = Idx;
7160 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7161 MaskPtr[HiIdx] = Idx;
7166 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7167 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7168 int MaskOps[] = { -1, -1, -1, -1 };
7169 for (unsigned i = 0; i != 4; ++i)
7170 if (Locs[i].first != -1)
7171 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7172 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7175 static bool MayFoldVectorLoad(SDValue V) {
7176 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7177 V = V.getOperand(0);
7179 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7180 V = V.getOperand(0);
7181 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7182 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7183 // BUILD_VECTOR (load), undef
7184 V = V.getOperand(0);
7186 return MayFoldLoad(V);
7190 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7191 MVT VT = Op.getSimpleValueType();
7193 // Canonizalize to v2f64.
7194 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7195 return DAG.getNode(ISD::BITCAST, dl, VT,
7196 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7201 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7203 SDValue V1 = Op.getOperand(0);
7204 SDValue V2 = Op.getOperand(1);
7205 MVT VT = Op.getSimpleValueType();
7207 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7209 if (HasSSE2 && VT == MVT::v2f64)
7210 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7212 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7213 return DAG.getNode(ISD::BITCAST, dl, VT,
7214 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7215 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7216 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7220 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7221 SDValue V1 = Op.getOperand(0);
7222 SDValue V2 = Op.getOperand(1);
7223 MVT VT = Op.getSimpleValueType();
7225 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7226 "unsupported shuffle type");
7228 if (V2.getOpcode() == ISD::UNDEF)
7232 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7236 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7237 SDValue V1 = Op.getOperand(0);
7238 SDValue V2 = Op.getOperand(1);
7239 MVT VT = Op.getSimpleValueType();
7240 unsigned NumElems = VT.getVectorNumElements();
7242 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7243 // operand of these instructions is only memory, so check if there's a
7244 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7246 bool CanFoldLoad = false;
7248 // Trivial case, when V2 comes from a load.
7249 if (MayFoldVectorLoad(V2))
7252 // When V1 is a load, it can be folded later into a store in isel, example:
7253 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7255 // (MOVLPSmr addr:$src1, VR128:$src2)
7256 // So, recognize this potential and also use MOVLPS or MOVLPD
7257 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7260 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7262 if (HasSSE2 && NumElems == 2)
7263 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7266 // If we don't care about the second element, proceed to use movss.
7267 if (SVOp->getMaskElt(1) != -1)
7268 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7271 // movl and movlp will both match v2i64, but v2i64 is never matched by
7272 // movl earlier because we make it strict to avoid messing with the movlp load
7273 // folding logic (see the code above getMOVLP call). Match it here then,
7274 // this is horrible, but will stay like this until we move all shuffle
7275 // matching to x86 specific nodes. Note that for the 1st condition all
7276 // types are matched with movsd.
7278 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7279 // as to remove this logic from here, as much as possible
7280 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7281 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7282 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7285 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7287 // Invert the operand order and use SHUFPS to match it.
7288 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7289 getShuffleSHUFImmediate(SVOp), DAG);
7292 // It is only safe to call this function if isINSERTPSMask is true for
7293 // this shufflevector mask.
7294 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7295 SelectionDAG &DAG) {
7296 // Generate an insertps instruction when inserting an f32 from memory onto a
7297 // v4f32 or when copying a member from one v4f32 to another.
7298 // We also use it for transferring i32 from one register to another,
7299 // since it simply copies the same bits.
7300 // If we're transfering an i32 from memory to a specific element in a
7301 // register, we output a generic DAG that will match the PINSRD
7303 // TODO: Optimize for AVX cases too (VINSERTPS)
7304 MVT VT = SVOp->getSimpleValueType(0);
7305 MVT EVT = VT.getVectorElementType();
7306 SDValue V1 = SVOp->getOperand(0);
7307 SDValue V2 = SVOp->getOperand(1);
7308 auto Mask = SVOp->getMask();
7309 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7310 "unsupported vector type for insertps/pinsrd");
7312 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7313 [](const int &i) { return i < 4; });
7321 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7322 [](const int &i) { return i < 4; }) -
7327 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7328 [](const int &i) { return i >= 4; }) -
7332 if (MayFoldLoad(From)) {
7333 // Trivial case, when From comes from a load and is only used by the
7334 // shuffle. Make it use insertps from the vector that we need from that
7336 SDValue Addr = From.getOperand(1);
7338 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7339 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7340 Addr.getSimpleValueType()));
7342 LoadSDNode *Load = cast<LoadSDNode>(From);
7344 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7345 DAG.getMachineFunction().getMachineMemOperand(
7346 Load->getMemOperand(), 0, EVT.getStoreSize()));
7348 if (EVT == MVT::f32) {
7349 // Create this as a scalar to vector to match the instruction pattern.
7350 SDValue LoadScalarToVector =
7351 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7352 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7353 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7355 } else { // EVT == MVT::i32
7356 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7357 // instruction, to match the PINSRD instruction, which loads an i32 to a
7358 // certain vector element.
7359 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7360 DAG.getConstant(DestIndex, MVT::i32));
7364 // Vector-element-to-vector
7365 unsigned SrcIndex = Mask[DestIndex] % 4;
7366 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7367 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7370 // Reduce a vector shuffle to zext.
7371 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7372 SelectionDAG &DAG) {
7373 // PMOVZX is only available from SSE41.
7374 if (!Subtarget->hasSSE41())
7377 MVT VT = Op.getSimpleValueType();
7379 // Only AVX2 support 256-bit vector integer extending.
7380 if (!Subtarget->hasInt256() && VT.is256BitVector())
7383 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7385 SDValue V1 = Op.getOperand(0);
7386 SDValue V2 = Op.getOperand(1);
7387 unsigned NumElems = VT.getVectorNumElements();
7389 // Extending is an unary operation and the element type of the source vector
7390 // won't be equal to or larger than i64.
7391 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7392 VT.getVectorElementType() == MVT::i64)
7395 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7396 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7397 while ((1U << Shift) < NumElems) {
7398 if (SVOp->getMaskElt(1U << Shift) == 1)
7401 // The maximal ratio is 8, i.e. from i8 to i64.
7406 // Check the shuffle mask.
7407 unsigned Mask = (1U << Shift) - 1;
7408 for (unsigned i = 0; i != NumElems; ++i) {
7409 int EltIdx = SVOp->getMaskElt(i);
7410 if ((i & Mask) != 0 && EltIdx != -1)
7412 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7416 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7417 MVT NeVT = MVT::getIntegerVT(NBits);
7418 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7420 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7423 // Simplify the operand as it's prepared to be fed into shuffle.
7424 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7425 if (V1.getOpcode() == ISD::BITCAST &&
7426 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7427 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7428 V1.getOperand(0).getOperand(0)
7429 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7430 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7431 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7432 ConstantSDNode *CIdx =
7433 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7434 // If it's foldable, i.e. normal load with single use, we will let code
7435 // selection to fold it. Otherwise, we will short the conversion sequence.
7436 if (CIdx && CIdx->getZExtValue() == 0 &&
7437 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7438 MVT FullVT = V.getSimpleValueType();
7439 MVT V1VT = V1.getSimpleValueType();
7440 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7441 // The "ext_vec_elt" node is wider than the result node.
7442 // In this case we should extract subvector from V.
7443 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7444 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7445 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7446 FullVT.getVectorNumElements()/Ratio);
7447 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7448 DAG.getIntPtrConstant(0));
7450 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7454 return DAG.getNode(ISD::BITCAST, DL, VT,
7455 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7459 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7460 SelectionDAG &DAG) {
7461 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7462 MVT VT = Op.getSimpleValueType();
7464 SDValue V1 = Op.getOperand(0);
7465 SDValue V2 = Op.getOperand(1);
7467 if (isZeroShuffle(SVOp))
7468 return getZeroVector(VT, Subtarget, DAG, dl);
7470 // Handle splat operations
7471 if (SVOp->isSplat()) {
7472 // Use vbroadcast whenever the splat comes from a foldable load
7473 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7474 if (Broadcast.getNode())
7478 // Check integer expanding shuffles.
7479 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7480 if (NewOp.getNode())
7483 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7485 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7486 VT == MVT::v16i16 || VT == MVT::v32i8) {
7487 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7488 if (NewOp.getNode())
7489 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7490 } else if ((VT == MVT::v4i32 ||
7491 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7492 // FIXME: Figure out a cleaner way to do this.
7493 // Try to make use of movq to zero out the top part.
7494 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7495 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7496 if (NewOp.getNode()) {
7497 MVT NewVT = NewOp.getSimpleValueType();
7498 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7499 NewVT, true, false))
7500 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7501 DAG, Subtarget, dl);
7503 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7504 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7505 if (NewOp.getNode()) {
7506 MVT NewVT = NewOp.getSimpleValueType();
7507 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7508 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7509 DAG, Subtarget, dl);
7517 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7518 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7519 SDValue V1 = Op.getOperand(0);
7520 SDValue V2 = Op.getOperand(1);
7521 MVT VT = Op.getSimpleValueType();
7523 unsigned NumElems = VT.getVectorNumElements();
7524 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7525 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7526 bool V1IsSplat = false;
7527 bool V2IsSplat = false;
7528 bool HasSSE2 = Subtarget->hasSSE2();
7529 bool HasFp256 = Subtarget->hasFp256();
7530 bool HasInt256 = Subtarget->hasInt256();
7531 MachineFunction &MF = DAG.getMachineFunction();
7532 bool OptForSize = MF.getFunction()->getAttributes().
7533 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7535 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7537 if (V1IsUndef && V2IsUndef)
7538 return DAG.getUNDEF(VT);
7540 // When we create a shuffle node we put the UNDEF node to second operand,
7541 // but in some cases the first operand may be transformed to UNDEF.
7542 // In this case we should just commute the node.
7544 return CommuteVectorShuffle(SVOp, DAG);
7546 // Vector shuffle lowering takes 3 steps:
7548 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7549 // narrowing and commutation of operands should be handled.
7550 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7552 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7553 // so the shuffle can be broken into other shuffles and the legalizer can
7554 // try the lowering again.
7556 // The general idea is that no vector_shuffle operation should be left to
7557 // be matched during isel, all of them must be converted to a target specific
7560 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7561 // narrowing and commutation of operands should be handled. The actual code
7562 // doesn't include all of those, work in progress...
7563 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7564 if (NewOp.getNode())
7567 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7569 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7570 // unpckh_undef). Only use pshufd if speed is more important than size.
7571 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7572 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7573 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7574 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7576 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7577 V2IsUndef && MayFoldVectorLoad(V1))
7578 return getMOVDDup(Op, dl, V1, DAG);
7580 if (isMOVHLPS_v_undef_Mask(M, VT))
7581 return getMOVHighToLow(Op, dl, DAG);
7583 // Use to match splats
7584 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7585 (VT == MVT::v2f64 || VT == MVT::v2i64))
7586 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7588 if (isPSHUFDMask(M, VT)) {
7589 // The actual implementation will match the mask in the if above and then
7590 // during isel it can match several different instructions, not only pshufd
7591 // as its name says, sad but true, emulate the behavior for now...
7592 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7593 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7595 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7597 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7598 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7600 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7601 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7604 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7608 if (isPALIGNRMask(M, VT, Subtarget))
7609 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7610 getShufflePALIGNRImmediate(SVOp),
7613 // Check if this can be converted into a logical shift.
7614 bool isLeft = false;
7617 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7618 if (isShift && ShVal.hasOneUse()) {
7619 // If the shifted value has multiple uses, it may be cheaper to use
7620 // v_set0 + movlhps or movhlps, etc.
7621 MVT EltVT = VT.getVectorElementType();
7622 ShAmt *= EltVT.getSizeInBits();
7623 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7626 if (isMOVLMask(M, VT)) {
7627 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7628 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7629 if (!isMOVLPMask(M, VT)) {
7630 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7631 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7633 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7634 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7638 // FIXME: fold these into legal mask.
7639 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7640 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7642 if (isMOVHLPSMask(M, VT))
7643 return getMOVHighToLow(Op, dl, DAG);
7645 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7646 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7648 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7649 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7651 if (isMOVLPMask(M, VT))
7652 return getMOVLP(Op, dl, DAG, HasSSE2);
7654 if (ShouldXformToMOVHLPS(M, VT) ||
7655 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7656 return CommuteVectorShuffle(SVOp, DAG);
7659 // No better options. Use a vshldq / vsrldq.
7660 MVT EltVT = VT.getVectorElementType();
7661 ShAmt *= EltVT.getSizeInBits();
7662 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7665 bool Commuted = false;
7666 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7667 // 1,1,1,1 -> v8i16 though.
7668 V1IsSplat = isSplatVector(V1.getNode());
7669 V2IsSplat = isSplatVector(V2.getNode());
7671 // Canonicalize the splat or undef, if present, to be on the RHS.
7672 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7673 CommuteVectorShuffleMask(M, NumElems);
7675 std::swap(V1IsSplat, V2IsSplat);
7679 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7680 // Shuffling low element of v1 into undef, just return v1.
7683 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7684 // the instruction selector will not match, so get a canonical MOVL with
7685 // swapped operands to undo the commute.
7686 return getMOVL(DAG, dl, VT, V2, V1);
7689 if (isUNPCKLMask(M, VT, HasInt256))
7690 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7692 if (isUNPCKHMask(M, VT, HasInt256))
7693 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7696 // Normalize mask so all entries that point to V2 points to its first
7697 // element then try to match unpck{h|l} again. If match, return a
7698 // new vector_shuffle with the corrected mask.p
7699 SmallVector<int, 8> NewMask(M.begin(), M.end());
7700 NormalizeMask(NewMask, NumElems);
7701 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7702 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7703 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7704 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7708 // Commute is back and try unpck* again.
7709 // FIXME: this seems wrong.
7710 CommuteVectorShuffleMask(M, NumElems);
7712 std::swap(V1IsSplat, V2IsSplat);
7714 if (isUNPCKLMask(M, VT, HasInt256))
7715 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7717 if (isUNPCKHMask(M, VT, HasInt256))
7718 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7721 // Normalize the node to match x86 shuffle ops if needed
7722 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7723 return CommuteVectorShuffle(SVOp, DAG);
7725 // The checks below are all present in isShuffleMaskLegal, but they are
7726 // inlined here right now to enable us to directly emit target specific
7727 // nodes, and remove one by one until they don't return Op anymore.
7729 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7730 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7731 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7732 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7735 if (isPSHUFHWMask(M, VT, HasInt256))
7736 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7737 getShufflePSHUFHWImmediate(SVOp),
7740 if (isPSHUFLWMask(M, VT, HasInt256))
7741 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7742 getShufflePSHUFLWImmediate(SVOp),
7745 if (isSHUFPMask(M, VT))
7746 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7747 getShuffleSHUFImmediate(SVOp), DAG);
7749 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7750 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7751 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7752 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7754 //===--------------------------------------------------------------------===//
7755 // Generate target specific nodes for 128 or 256-bit shuffles only
7756 // supported in the AVX instruction set.
7759 // Handle VMOVDDUPY permutations
7760 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7761 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7763 // Handle VPERMILPS/D* permutations
7764 if (isVPERMILPMask(M, VT)) {
7765 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7766 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7767 getShuffleSHUFImmediate(SVOp), DAG);
7768 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7769 getShuffleSHUFImmediate(SVOp), DAG);
7772 // Handle VPERM2F128/VPERM2I128 permutations
7773 if (isVPERM2X128Mask(M, VT, HasFp256))
7774 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7775 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7777 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7778 if (BlendOp.getNode())
7781 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7782 return getINSERTPS(SVOp, dl, DAG);
7785 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7786 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7788 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7789 VT.is512BitVector()) {
7790 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7791 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7792 SmallVector<SDValue, 16> permclMask;
7793 for (unsigned i = 0; i != NumElems; ++i) {
7794 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7797 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7798 &permclMask[0], NumElems);
7800 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7801 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7802 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7803 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7804 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7807 //===--------------------------------------------------------------------===//
7808 // Since no target specific shuffle was selected for this generic one,
7809 // lower it into other known shuffles. FIXME: this isn't true yet, but
7810 // this is the plan.
7813 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7814 if (VT == MVT::v8i16) {
7815 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7816 if (NewOp.getNode())
7820 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7821 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7822 if (NewOp.getNode())
7826 if (VT == MVT::v16i8) {
7827 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7828 if (NewOp.getNode())
7832 if (VT == MVT::v32i8) {
7833 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7834 if (NewOp.getNode())
7838 // Handle all 128-bit wide vectors with 4 elements, and match them with
7839 // several different shuffle types.
7840 if (NumElems == 4 && VT.is128BitVector())
7841 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7843 // Handle general 256-bit shuffles
7844 if (VT.is256BitVector())
7845 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7850 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7851 MVT VT = Op.getSimpleValueType();
7854 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7857 if (VT.getSizeInBits() == 8) {
7858 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7859 Op.getOperand(0), Op.getOperand(1));
7860 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7861 DAG.getValueType(VT));
7862 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7865 if (VT.getSizeInBits() == 16) {
7866 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7867 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7869 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7870 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7871 DAG.getNode(ISD::BITCAST, dl,
7875 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7876 Op.getOperand(0), Op.getOperand(1));
7877 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7878 DAG.getValueType(VT));
7879 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7882 if (VT == MVT::f32) {
7883 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7884 // the result back to FR32 register. It's only worth matching if the
7885 // result has a single use which is a store or a bitcast to i32. And in
7886 // the case of a store, it's not worth it if the index is a constant 0,
7887 // because a MOVSSmr can be used instead, which is smaller and faster.
7888 if (!Op.hasOneUse())
7890 SDNode *User = *Op.getNode()->use_begin();
7891 if ((User->getOpcode() != ISD::STORE ||
7892 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7893 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7894 (User->getOpcode() != ISD::BITCAST ||
7895 User->getValueType(0) != MVT::i32))
7897 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7898 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7901 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7904 if (VT == MVT::i32 || VT == MVT::i64) {
7905 // ExtractPS/pextrq works with constant index.
7906 if (isa<ConstantSDNode>(Op.getOperand(1)))
7912 /// Extract one bit from mask vector, like v16i1 or v8i1.
7913 /// AVX-512 feature.
7915 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7916 SDValue Vec = Op.getOperand(0);
7918 MVT VecVT = Vec.getSimpleValueType();
7919 SDValue Idx = Op.getOperand(1);
7920 MVT EltVT = Op.getSimpleValueType();
7922 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7924 // variable index can't be handled in mask registers,
7925 // extend vector to VR512
7926 if (!isa<ConstantSDNode>(Idx)) {
7927 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7928 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7929 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7930 ExtVT.getVectorElementType(), Ext, Idx);
7931 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7934 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7935 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7936 unsigned MaxSift = rc->getSize()*8 - 1;
7937 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7938 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7939 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7940 DAG.getConstant(MaxSift, MVT::i8));
7941 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7942 DAG.getIntPtrConstant(0));
7946 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7947 SelectionDAG &DAG) const {
7949 SDValue Vec = Op.getOperand(0);
7950 MVT VecVT = Vec.getSimpleValueType();
7951 SDValue Idx = Op.getOperand(1);
7953 if (Op.getSimpleValueType() == MVT::i1)
7954 return ExtractBitFromMaskVector(Op, DAG);
7956 if (!isa<ConstantSDNode>(Idx)) {
7957 if (VecVT.is512BitVector() ||
7958 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7959 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7962 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7963 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7964 MaskEltVT.getSizeInBits());
7966 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7967 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7968 getZeroVector(MaskVT, Subtarget, DAG, dl),
7969 Idx, DAG.getConstant(0, getPointerTy()));
7970 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7971 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7972 Perm, DAG.getConstant(0, getPointerTy()));
7977 // If this is a 256-bit vector result, first extract the 128-bit vector and
7978 // then extract the element from the 128-bit vector.
7979 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7981 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7982 // Get the 128-bit vector.
7983 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7984 MVT EltVT = VecVT.getVectorElementType();
7986 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7988 //if (IdxVal >= NumElems/2)
7989 // IdxVal -= NumElems/2;
7990 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7991 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7992 DAG.getConstant(IdxVal, MVT::i32));
7995 assert(VecVT.is128BitVector() && "Unexpected vector length");
7997 if (Subtarget->hasSSE41()) {
7998 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8003 MVT VT = Op.getSimpleValueType();
8004 // TODO: handle v16i8.
8005 if (VT.getSizeInBits() == 16) {
8006 SDValue Vec = Op.getOperand(0);
8007 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8009 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8010 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8011 DAG.getNode(ISD::BITCAST, dl,
8014 // Transform it so it match pextrw which produces a 32-bit result.
8015 MVT EltVT = MVT::i32;
8016 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8017 Op.getOperand(0), Op.getOperand(1));
8018 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8019 DAG.getValueType(VT));
8020 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8023 if (VT.getSizeInBits() == 32) {
8024 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8028 // SHUFPS the element to the lowest double word, then movss.
8029 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8030 MVT VVT = Op.getOperand(0).getSimpleValueType();
8031 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8032 DAG.getUNDEF(VVT), Mask);
8033 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8034 DAG.getIntPtrConstant(0));
8037 if (VT.getSizeInBits() == 64) {
8038 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8039 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8040 // to match extract_elt for f64.
8041 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8045 // UNPCKHPD the element to the lowest double word, then movsd.
8046 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8047 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8048 int Mask[2] = { 1, -1 };
8049 MVT VVT = Op.getOperand(0).getSimpleValueType();
8050 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8051 DAG.getUNDEF(VVT), Mask);
8052 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8053 DAG.getIntPtrConstant(0));
8059 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8060 MVT VT = Op.getSimpleValueType();
8061 MVT EltVT = VT.getVectorElementType();
8064 SDValue N0 = Op.getOperand(0);
8065 SDValue N1 = Op.getOperand(1);
8066 SDValue N2 = Op.getOperand(2);
8068 if (!VT.is128BitVector())
8071 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8072 isa<ConstantSDNode>(N2)) {
8074 if (VT == MVT::v8i16)
8075 Opc = X86ISD::PINSRW;
8076 else if (VT == MVT::v16i8)
8077 Opc = X86ISD::PINSRB;
8079 Opc = X86ISD::PINSRB;
8081 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8083 if (N1.getValueType() != MVT::i32)
8084 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8085 if (N2.getValueType() != MVT::i32)
8086 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8087 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8090 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8091 // Bits [7:6] of the constant are the source select. This will always be
8092 // zero here. The DAG Combiner may combine an extract_elt index into these
8093 // bits. For example (insert (extract, 3), 2) could be matched by putting
8094 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8095 // Bits [5:4] of the constant are the destination select. This is the
8096 // value of the incoming immediate.
8097 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8098 // combine either bitwise AND or insert of float 0.0 to set these bits.
8099 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8100 // Create this as a scalar to vector..
8101 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8102 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8105 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8106 // PINSR* works with constant index.
8112 /// Insert one bit to mask vector, like v16i1 or v8i1.
8113 /// AVX-512 feature.
8115 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8117 SDValue Vec = Op.getOperand(0);
8118 SDValue Elt = Op.getOperand(1);
8119 SDValue Idx = Op.getOperand(2);
8120 MVT VecVT = Vec.getSimpleValueType();
8122 if (!isa<ConstantSDNode>(Idx)) {
8123 // Non constant index. Extend source and destination,
8124 // insert element and then truncate the result.
8125 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8126 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8127 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8128 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8129 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8130 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8133 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8134 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8135 if (Vec.getOpcode() == ISD::UNDEF)
8136 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8137 DAG.getConstant(IdxVal, MVT::i8));
8138 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8139 unsigned MaxSift = rc->getSize()*8 - 1;
8140 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8141 DAG.getConstant(MaxSift, MVT::i8));
8142 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8143 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8144 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8147 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8148 MVT VT = Op.getSimpleValueType();
8149 MVT EltVT = VT.getVectorElementType();
8151 if (EltVT == MVT::i1)
8152 return InsertBitToMaskVector(Op, DAG);
8155 SDValue N0 = Op.getOperand(0);
8156 SDValue N1 = Op.getOperand(1);
8157 SDValue N2 = Op.getOperand(2);
8159 // If this is a 256-bit vector result, first extract the 128-bit vector,
8160 // insert the element into the extracted half and then place it back.
8161 if (VT.is256BitVector() || VT.is512BitVector()) {
8162 if (!isa<ConstantSDNode>(N2))
8165 // Get the desired 128-bit vector half.
8166 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8167 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8169 // Insert the element into the desired half.
8170 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8171 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8173 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8174 DAG.getConstant(IdxIn128, MVT::i32));
8176 // Insert the changed part back to the 256-bit vector
8177 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8180 if (Subtarget->hasSSE41())
8181 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8183 if (EltVT == MVT::i8)
8186 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8187 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8188 // as its second argument.
8189 if (N1.getValueType() != MVT::i32)
8190 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8191 if (N2.getValueType() != MVT::i32)
8192 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8193 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8198 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8200 MVT OpVT = Op.getSimpleValueType();
8202 // If this is a 256-bit vector result, first insert into a 128-bit
8203 // vector and then insert into the 256-bit vector.
8204 if (!OpVT.is128BitVector()) {
8205 // Insert into a 128-bit vector.
8206 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8207 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8208 OpVT.getVectorNumElements() / SizeFactor);
8210 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8212 // Insert the 128-bit vector.
8213 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8216 if (OpVT == MVT::v1i64 &&
8217 Op.getOperand(0).getValueType() == MVT::i64)
8218 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8220 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8221 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8222 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8223 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8226 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8227 // a simple subregister reference or explicit instructions to grab
8228 // upper bits of a vector.
8229 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8230 SelectionDAG &DAG) {
8232 SDValue In = Op.getOperand(0);
8233 SDValue Idx = Op.getOperand(1);
8234 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8235 MVT ResVT = Op.getSimpleValueType();
8236 MVT InVT = In.getSimpleValueType();
8238 if (Subtarget->hasFp256()) {
8239 if (ResVT.is128BitVector() &&
8240 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8241 isa<ConstantSDNode>(Idx)) {
8242 return Extract128BitVector(In, IdxVal, DAG, dl);
8244 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8245 isa<ConstantSDNode>(Idx)) {
8246 return Extract256BitVector(In, IdxVal, DAG, dl);
8252 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8253 // simple superregister reference or explicit instructions to insert
8254 // the upper bits of a vector.
8255 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8256 SelectionDAG &DAG) {
8257 if (Subtarget->hasFp256()) {
8258 SDLoc dl(Op.getNode());
8259 SDValue Vec = Op.getNode()->getOperand(0);
8260 SDValue SubVec = Op.getNode()->getOperand(1);
8261 SDValue Idx = Op.getNode()->getOperand(2);
8263 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8264 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8265 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8266 isa<ConstantSDNode>(Idx)) {
8267 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8268 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8271 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8272 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8273 isa<ConstantSDNode>(Idx)) {
8274 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8275 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8281 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8282 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8283 // one of the above mentioned nodes. It has to be wrapped because otherwise
8284 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8285 // be used to form addressing mode. These wrapped nodes will be selected
8288 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8289 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8291 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8293 unsigned char OpFlag = 0;
8294 unsigned WrapperKind = X86ISD::Wrapper;
8295 CodeModel::Model M = getTargetMachine().getCodeModel();
8297 if (Subtarget->isPICStyleRIPRel() &&
8298 (M == CodeModel::Small || M == CodeModel::Kernel))
8299 WrapperKind = X86ISD::WrapperRIP;
8300 else if (Subtarget->isPICStyleGOT())
8301 OpFlag = X86II::MO_GOTOFF;
8302 else if (Subtarget->isPICStyleStubPIC())
8303 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8305 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8307 CP->getOffset(), OpFlag);
8309 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8310 // With PIC, the address is actually $g + Offset.
8312 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8313 DAG.getNode(X86ISD::GlobalBaseReg,
8314 SDLoc(), getPointerTy()),
8321 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8322 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8324 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8326 unsigned char OpFlag = 0;
8327 unsigned WrapperKind = X86ISD::Wrapper;
8328 CodeModel::Model M = getTargetMachine().getCodeModel();
8330 if (Subtarget->isPICStyleRIPRel() &&
8331 (M == CodeModel::Small || M == CodeModel::Kernel))
8332 WrapperKind = X86ISD::WrapperRIP;
8333 else if (Subtarget->isPICStyleGOT())
8334 OpFlag = X86II::MO_GOTOFF;
8335 else if (Subtarget->isPICStyleStubPIC())
8336 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8338 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8341 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8343 // With PIC, the address is actually $g + Offset.
8345 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8346 DAG.getNode(X86ISD::GlobalBaseReg,
8347 SDLoc(), getPointerTy()),
8354 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8355 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8357 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8359 unsigned char OpFlag = 0;
8360 unsigned WrapperKind = X86ISD::Wrapper;
8361 CodeModel::Model M = getTargetMachine().getCodeModel();
8363 if (Subtarget->isPICStyleRIPRel() &&
8364 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8365 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8366 OpFlag = X86II::MO_GOTPCREL;
8367 WrapperKind = X86ISD::WrapperRIP;
8368 } else if (Subtarget->isPICStyleGOT()) {
8369 OpFlag = X86II::MO_GOT;
8370 } else if (Subtarget->isPICStyleStubPIC()) {
8371 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8372 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8373 OpFlag = X86II::MO_DARWIN_NONLAZY;
8376 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8379 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8381 // With PIC, the address is actually $g + Offset.
8382 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8383 !Subtarget->is64Bit()) {
8384 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8385 DAG.getNode(X86ISD::GlobalBaseReg,
8386 SDLoc(), getPointerTy()),
8390 // For symbols that require a load from a stub to get the address, emit the
8392 if (isGlobalStubReference(OpFlag))
8393 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8394 MachinePointerInfo::getGOT(), false, false, false, 0);
8400 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8401 // Create the TargetBlockAddressAddress node.
8402 unsigned char OpFlags =
8403 Subtarget->ClassifyBlockAddressReference();
8404 CodeModel::Model M = getTargetMachine().getCodeModel();
8405 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8406 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8408 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8411 if (Subtarget->isPICStyleRIPRel() &&
8412 (M == CodeModel::Small || M == CodeModel::Kernel))
8413 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8415 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8417 // With PIC, the address is actually $g + Offset.
8418 if (isGlobalRelativeToPICBase(OpFlags)) {
8419 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8420 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8428 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8429 int64_t Offset, SelectionDAG &DAG) const {
8430 // Create the TargetGlobalAddress node, folding in the constant
8431 // offset if it is legal.
8432 unsigned char OpFlags =
8433 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8434 CodeModel::Model M = getTargetMachine().getCodeModel();
8436 if (OpFlags == X86II::MO_NO_FLAG &&
8437 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8438 // A direct static reference to a global.
8439 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8442 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8445 if (Subtarget->isPICStyleRIPRel() &&
8446 (M == CodeModel::Small || M == CodeModel::Kernel))
8447 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8449 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8451 // With PIC, the address is actually $g + Offset.
8452 if (isGlobalRelativeToPICBase(OpFlags)) {
8453 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8454 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8458 // For globals that require a load from a stub to get the address, emit the
8460 if (isGlobalStubReference(OpFlags))
8461 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8462 MachinePointerInfo::getGOT(), false, false, false, 0);
8464 // If there was a non-zero offset that we didn't fold, create an explicit
8467 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8468 DAG.getConstant(Offset, getPointerTy()));
8474 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8475 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8476 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8477 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8481 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8482 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8483 unsigned char OperandFlags, bool LocalDynamic = false) {
8484 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8485 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8487 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8488 GA->getValueType(0),
8492 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8496 SDValue Ops[] = { Chain, TGA, *InFlag };
8497 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8499 SDValue Ops[] = { Chain, TGA };
8500 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8503 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8504 MFI->setAdjustsStack(true);
8506 SDValue Flag = Chain.getValue(1);
8507 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8510 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8512 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8515 SDLoc dl(GA); // ? function entry point might be better
8516 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8517 DAG.getNode(X86ISD::GlobalBaseReg,
8518 SDLoc(), PtrVT), InFlag);
8519 InFlag = Chain.getValue(1);
8521 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8524 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8526 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8528 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8529 X86::RAX, X86II::MO_TLSGD);
8532 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8538 // Get the start address of the TLS block for this module.
8539 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8540 .getInfo<X86MachineFunctionInfo>();
8541 MFI->incNumLocalDynamicTLSAccesses();
8545 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8546 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8549 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8550 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8551 InFlag = Chain.getValue(1);
8552 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8553 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8556 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8560 unsigned char OperandFlags = X86II::MO_DTPOFF;
8561 unsigned WrapperKind = X86ISD::Wrapper;
8562 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8563 GA->getValueType(0),
8564 GA->getOffset(), OperandFlags);
8565 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8567 // Add x@dtpoff with the base.
8568 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8571 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8572 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8573 const EVT PtrVT, TLSModel::Model model,
8574 bool is64Bit, bool isPIC) {
8577 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8578 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8579 is64Bit ? 257 : 256));
8581 SDValue ThreadPointer =
8582 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8583 MachinePointerInfo(Ptr), false, false, false, 0);
8585 unsigned char OperandFlags = 0;
8586 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8588 unsigned WrapperKind = X86ISD::Wrapper;
8589 if (model == TLSModel::LocalExec) {
8590 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8591 } else if (model == TLSModel::InitialExec) {
8593 OperandFlags = X86II::MO_GOTTPOFF;
8594 WrapperKind = X86ISD::WrapperRIP;
8596 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8599 llvm_unreachable("Unexpected model");
8602 // emit "addl x@ntpoff,%eax" (local exec)
8603 // or "addl x@indntpoff,%eax" (initial exec)
8604 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8606 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8607 GA->getOffset(), OperandFlags);
8608 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8610 if (model == TLSModel::InitialExec) {
8611 if (isPIC && !is64Bit) {
8612 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8613 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8617 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8618 MachinePointerInfo::getGOT(), false, false, false, 0);
8621 // The address of the thread local variable is the add of the thread
8622 // pointer with the offset of the variable.
8623 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8627 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8629 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8630 const GlobalValue *GV = GA->getGlobal();
8632 if (Subtarget->isTargetELF()) {
8633 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8636 case TLSModel::GeneralDynamic:
8637 if (Subtarget->is64Bit())
8638 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8639 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8640 case TLSModel::LocalDynamic:
8641 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8642 Subtarget->is64Bit());
8643 case TLSModel::InitialExec:
8644 case TLSModel::LocalExec:
8645 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8646 Subtarget->is64Bit(),
8647 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8649 llvm_unreachable("Unknown TLS model.");
8652 if (Subtarget->isTargetDarwin()) {
8653 // Darwin only has one model of TLS. Lower to that.
8654 unsigned char OpFlag = 0;
8655 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8656 X86ISD::WrapperRIP : X86ISD::Wrapper;
8658 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8660 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8661 !Subtarget->is64Bit();
8663 OpFlag = X86II::MO_TLVP_PIC_BASE;
8665 OpFlag = X86II::MO_TLVP;
8667 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8668 GA->getValueType(0),
8669 GA->getOffset(), OpFlag);
8670 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8672 // With PIC32, the address is actually $g + Offset.
8674 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8675 DAG.getNode(X86ISD::GlobalBaseReg,
8676 SDLoc(), getPointerTy()),
8679 // Lowering the machine isd will make sure everything is in the right
8681 SDValue Chain = DAG.getEntryNode();
8682 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8683 SDValue Args[] = { Chain, Offset };
8684 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8686 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8687 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8688 MFI->setAdjustsStack(true);
8690 // And our return value (tls address) is in the standard call return value
8692 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8693 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8697 if (Subtarget->isTargetKnownWindowsMSVC() ||
8698 Subtarget->isTargetWindowsGNU()) {
8699 // Just use the implicit TLS architecture
8700 // Need to generate someting similar to:
8701 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8703 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8704 // mov rcx, qword [rdx+rcx*8]
8705 // mov eax, .tls$:tlsvar
8706 // [rax+rcx] contains the address
8707 // Windows 64bit: gs:0x58
8708 // Windows 32bit: fs:__tls_array
8710 // If GV is an alias then use the aliasee for determining
8711 // thread-localness.
8712 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8713 GV = GA->getAliasedGlobal();
8715 SDValue Chain = DAG.getEntryNode();
8717 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8718 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8719 // use its literal value of 0x2C.
8720 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8721 ? Type::getInt8PtrTy(*DAG.getContext(),
8723 : Type::getInt32PtrTy(*DAG.getContext(),
8727 Subtarget->is64Bit()
8728 ? DAG.getIntPtrConstant(0x58)
8729 : (Subtarget->isTargetWindowsGNU()
8730 ? DAG.getIntPtrConstant(0x2C)
8731 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8733 SDValue ThreadPointer =
8734 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8735 MachinePointerInfo(Ptr), false, false, false, 0);
8737 // Load the _tls_index variable
8738 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8739 if (Subtarget->is64Bit())
8740 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8741 IDX, MachinePointerInfo(), MVT::i32,
8744 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8745 false, false, false, 0);
8747 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8749 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8751 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8752 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8753 false, false, false, 0);
8755 // Get the offset of start of .tls section
8756 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8757 GA->getValueType(0),
8758 GA->getOffset(), X86II::MO_SECREL);
8759 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8761 // The address of the thread local variable is the add of the thread
8762 // pointer with the offset of the variable.
8763 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8766 llvm_unreachable("TLS not implemented for this target.");
8769 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8770 /// and take a 2 x i32 value to shift plus a shift amount.
8771 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8772 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8773 MVT VT = Op.getSimpleValueType();
8774 unsigned VTBits = VT.getSizeInBits();
8776 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8777 SDValue ShOpLo = Op.getOperand(0);
8778 SDValue ShOpHi = Op.getOperand(1);
8779 SDValue ShAmt = Op.getOperand(2);
8780 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8781 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8783 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8784 DAG.getConstant(VTBits - 1, MVT::i8));
8785 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8786 DAG.getConstant(VTBits - 1, MVT::i8))
8787 : DAG.getConstant(0, VT);
8790 if (Op.getOpcode() == ISD::SHL_PARTS) {
8791 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8792 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8794 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8795 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8798 // If the shift amount is larger or equal than the width of a part we can't
8799 // rely on the results of shld/shrd. Insert a test and select the appropriate
8800 // values for large shift amounts.
8801 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8802 DAG.getConstant(VTBits, MVT::i8));
8803 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8804 AndNode, DAG.getConstant(0, MVT::i8));
8807 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8808 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8809 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8811 if (Op.getOpcode() == ISD::SHL_PARTS) {
8812 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8813 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8815 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8816 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8819 SDValue Ops[2] = { Lo, Hi };
8820 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8823 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8824 SelectionDAG &DAG) const {
8825 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8827 if (SrcVT.isVector())
8830 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8831 "Unknown SINT_TO_FP to lower!");
8833 // These are really Legal; return the operand so the caller accepts it as
8835 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8837 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8838 Subtarget->is64Bit()) {
8843 unsigned Size = SrcVT.getSizeInBits()/8;
8844 MachineFunction &MF = DAG.getMachineFunction();
8845 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8846 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8847 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8849 MachinePointerInfo::getFixedStack(SSFI),
8851 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8854 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8856 SelectionDAG &DAG) const {
8860 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8862 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8864 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8866 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8868 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8869 MachineMemOperand *MMO;
8871 int SSFI = FI->getIndex();
8873 DAG.getMachineFunction()
8874 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8875 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8877 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8878 StackSlot = StackSlot.getOperand(1);
8880 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8881 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8883 Tys, Ops, array_lengthof(Ops),
8887 Chain = Result.getValue(1);
8888 SDValue InFlag = Result.getValue(2);
8890 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8891 // shouldn't be necessary except that RFP cannot be live across
8892 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8893 MachineFunction &MF = DAG.getMachineFunction();
8894 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8895 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8896 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8897 Tys = DAG.getVTList(MVT::Other);
8899 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8901 MachineMemOperand *MMO =
8902 DAG.getMachineFunction()
8903 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8904 MachineMemOperand::MOStore, SSFISize, SSFISize);
8906 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8907 Ops, array_lengthof(Ops),
8908 Op.getValueType(), MMO);
8909 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8910 MachinePointerInfo::getFixedStack(SSFI),
8911 false, false, false, 0);
8917 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8918 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8919 SelectionDAG &DAG) const {
8920 // This algorithm is not obvious. Here it is what we're trying to output:
8923 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8924 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8928 pshufd $0x4e, %xmm0, %xmm1
8934 LLVMContext *Context = DAG.getContext();
8936 // Build some magic constants.
8937 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8938 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8939 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8941 SmallVector<Constant*,2> CV1;
8943 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8944 APInt(64, 0x4330000000000000ULL))));
8946 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8947 APInt(64, 0x4530000000000000ULL))));
8948 Constant *C1 = ConstantVector::get(CV1);
8949 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8951 // Load the 64-bit value into an XMM register.
8952 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8954 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8955 MachinePointerInfo::getConstantPool(),
8956 false, false, false, 16);
8957 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8958 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8961 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8962 MachinePointerInfo::getConstantPool(),
8963 false, false, false, 16);
8964 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8965 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8968 if (Subtarget->hasSSE3()) {
8969 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8970 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8972 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8973 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8975 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8976 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8980 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8981 DAG.getIntPtrConstant(0));
8984 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8985 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8986 SelectionDAG &DAG) const {
8988 // FP constant to bias correct the final result.
8989 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8992 // Load the 32-bit value into an XMM register.
8993 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8996 // Zero out the upper parts of the register.
8997 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8999 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9000 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9001 DAG.getIntPtrConstant(0));
9003 // Or the load with the bias.
9004 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9005 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9006 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9008 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9009 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9010 MVT::v2f64, Bias)));
9011 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9012 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9013 DAG.getIntPtrConstant(0));
9015 // Subtract the bias.
9016 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9018 // Handle final rounding.
9019 EVT DestVT = Op.getValueType();
9021 if (DestVT.bitsLT(MVT::f64))
9022 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9023 DAG.getIntPtrConstant(0));
9024 if (DestVT.bitsGT(MVT::f64))
9025 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9027 // Handle final rounding.
9031 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9032 SelectionDAG &DAG) const {
9033 SDValue N0 = Op.getOperand(0);
9034 MVT SVT = N0.getSimpleValueType();
9037 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9038 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9039 "Custom UINT_TO_FP is not supported!");
9041 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9042 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9043 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9046 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9047 SelectionDAG &DAG) const {
9048 SDValue N0 = Op.getOperand(0);
9051 if (Op.getValueType().isVector())
9052 return lowerUINT_TO_FP_vec(Op, DAG);
9054 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9055 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9056 // the optimization here.
9057 if (DAG.SignBitIsZero(N0))
9058 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9060 MVT SrcVT = N0.getSimpleValueType();
9061 MVT DstVT = Op.getSimpleValueType();
9062 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9063 return LowerUINT_TO_FP_i64(Op, DAG);
9064 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9065 return LowerUINT_TO_FP_i32(Op, DAG);
9066 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9069 // Make a 64-bit buffer, and use it to build an FILD.
9070 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9071 if (SrcVT == MVT::i32) {
9072 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9073 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9074 getPointerTy(), StackSlot, WordOff);
9075 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9076 StackSlot, MachinePointerInfo(),
9078 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9079 OffsetSlot, MachinePointerInfo(),
9081 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9085 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9086 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9087 StackSlot, MachinePointerInfo(),
9089 // For i64 source, we need to add the appropriate power of 2 if the input
9090 // was negative. This is the same as the optimization in
9091 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9092 // we must be careful to do the computation in x87 extended precision, not
9093 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9094 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9095 MachineMemOperand *MMO =
9096 DAG.getMachineFunction()
9097 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9098 MachineMemOperand::MOLoad, 8, 8);
9100 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9101 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9102 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9103 array_lengthof(Ops), MVT::i64, MMO);
9105 APInt FF(32, 0x5F800000ULL);
9107 // Check whether the sign bit is set.
9108 SDValue SignSet = DAG.getSetCC(dl,
9109 getSetCCResultType(*DAG.getContext(), MVT::i64),
9110 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9113 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9114 SDValue FudgePtr = DAG.getConstantPool(
9115 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9118 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9119 SDValue Zero = DAG.getIntPtrConstant(0);
9120 SDValue Four = DAG.getIntPtrConstant(4);
9121 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9123 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9125 // Load the value out, extending it from f32 to f80.
9126 // FIXME: Avoid the extend by constructing the right constant pool?
9127 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9128 FudgePtr, MachinePointerInfo::getConstantPool(),
9129 MVT::f32, false, false, 4);
9130 // Extend everything to 80 bits to force it to be done on x87.
9131 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9132 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9135 std::pair<SDValue,SDValue>
9136 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9137 bool IsSigned, bool IsReplace) const {
9140 EVT DstTy = Op.getValueType();
9142 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9143 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9147 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9148 DstTy.getSimpleVT() >= MVT::i16 &&
9149 "Unknown FP_TO_INT to lower!");
9151 // These are really Legal.
9152 if (DstTy == MVT::i32 &&
9153 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9154 return std::make_pair(SDValue(), SDValue());
9155 if (Subtarget->is64Bit() &&
9156 DstTy == MVT::i64 &&
9157 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9158 return std::make_pair(SDValue(), SDValue());
9160 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9161 // stack slot, or into the FTOL runtime function.
9162 MachineFunction &MF = DAG.getMachineFunction();
9163 unsigned MemSize = DstTy.getSizeInBits()/8;
9164 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9165 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9168 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9169 Opc = X86ISD::WIN_FTOL;
9171 switch (DstTy.getSimpleVT().SimpleTy) {
9172 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9173 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9174 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9175 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9178 SDValue Chain = DAG.getEntryNode();
9179 SDValue Value = Op.getOperand(0);
9180 EVT TheVT = Op.getOperand(0).getValueType();
9181 // FIXME This causes a redundant load/store if the SSE-class value is already
9182 // in memory, such as if it is on the callstack.
9183 if (isScalarFPTypeInSSEReg(TheVT)) {
9184 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9185 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9186 MachinePointerInfo::getFixedStack(SSFI),
9188 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9190 Chain, StackSlot, DAG.getValueType(TheVT)
9193 MachineMemOperand *MMO =
9194 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9195 MachineMemOperand::MOLoad, MemSize, MemSize);
9196 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9197 array_lengthof(Ops), DstTy, MMO);
9198 Chain = Value.getValue(1);
9199 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9200 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9203 MachineMemOperand *MMO =
9204 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9205 MachineMemOperand::MOStore, MemSize, MemSize);
9207 if (Opc != X86ISD::WIN_FTOL) {
9208 // Build the FP_TO_INT*_IN_MEM
9209 SDValue Ops[] = { Chain, Value, StackSlot };
9210 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9211 Ops, array_lengthof(Ops), DstTy,
9213 return std::make_pair(FIST, StackSlot);
9215 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9216 DAG.getVTList(MVT::Other, MVT::Glue),
9218 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9219 MVT::i32, ftol.getValue(1));
9220 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9221 MVT::i32, eax.getValue(2));
9222 SDValue Ops[] = { eax, edx };
9223 SDValue pair = IsReplace
9224 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9225 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9226 return std::make_pair(pair, SDValue());
9230 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9231 const X86Subtarget *Subtarget) {
9232 MVT VT = Op->getSimpleValueType(0);
9233 SDValue In = Op->getOperand(0);
9234 MVT InVT = In.getSimpleValueType();
9237 // Optimize vectors in AVX mode:
9240 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9241 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9242 // Concat upper and lower parts.
9245 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9246 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9247 // Concat upper and lower parts.
9250 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9251 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9252 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9255 if (Subtarget->hasInt256())
9256 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9258 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9259 SDValue Undef = DAG.getUNDEF(InVT);
9260 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9261 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9262 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9264 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9265 VT.getVectorNumElements()/2);
9267 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9268 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9270 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9273 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9274 SelectionDAG &DAG) {
9275 MVT VT = Op->getSimpleValueType(0);
9276 SDValue In = Op->getOperand(0);
9277 MVT InVT = In.getSimpleValueType();
9279 unsigned int NumElts = VT.getVectorNumElements();
9280 if (NumElts != 8 && NumElts != 16)
9283 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9284 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9286 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9287 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9288 // Now we have only mask extension
9289 assert(InVT.getVectorElementType() == MVT::i1);
9290 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9291 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9292 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9293 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9294 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9295 MachinePointerInfo::getConstantPool(),
9296 false, false, false, Alignment);
9298 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9299 if (VT.is512BitVector())
9301 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9304 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9305 SelectionDAG &DAG) {
9306 if (Subtarget->hasFp256()) {
9307 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9315 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9316 SelectionDAG &DAG) {
9318 MVT VT = Op.getSimpleValueType();
9319 SDValue In = Op.getOperand(0);
9320 MVT SVT = In.getSimpleValueType();
9322 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9323 return LowerZERO_EXTEND_AVX512(Op, DAG);
9325 if (Subtarget->hasFp256()) {
9326 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9331 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9332 VT.getVectorNumElements() != SVT.getVectorNumElements());
9336 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9338 MVT VT = Op.getSimpleValueType();
9339 SDValue In = Op.getOperand(0);
9340 MVT InVT = In.getSimpleValueType();
9342 if (VT == MVT::i1) {
9343 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9344 "Invalid scalar TRUNCATE operation");
9345 if (InVT == MVT::i32)
9347 if (InVT.getSizeInBits() == 64)
9348 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9349 else if (InVT.getSizeInBits() < 32)
9350 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9351 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9353 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9354 "Invalid TRUNCATE operation");
9356 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9357 if (VT.getVectorElementType().getSizeInBits() >=8)
9358 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9360 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9361 unsigned NumElts = InVT.getVectorNumElements();
9362 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9363 if (InVT.getSizeInBits() < 512) {
9364 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9365 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9369 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9370 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9371 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9372 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9373 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9374 MachinePointerInfo::getConstantPool(),
9375 false, false, false, Alignment);
9376 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9377 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9378 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9381 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9382 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9383 if (Subtarget->hasInt256()) {
9384 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9385 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9386 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9388 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9389 DAG.getIntPtrConstant(0));
9392 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9393 DAG.getIntPtrConstant(0));
9394 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9395 DAG.getIntPtrConstant(2));
9396 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9397 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9398 static const int ShufMask[] = {0, 2, 4, 6};
9399 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9402 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9403 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9404 if (Subtarget->hasInt256()) {
9405 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9407 SmallVector<SDValue,32> pshufbMask;
9408 for (unsigned i = 0; i < 2; ++i) {
9409 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9410 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9411 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9412 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9413 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9414 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9415 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9416 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9417 for (unsigned j = 0; j < 8; ++j)
9418 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9420 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9421 &pshufbMask[0], 32);
9422 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9423 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9425 static const int ShufMask[] = {0, 2, -1, -1};
9426 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9428 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9429 DAG.getIntPtrConstant(0));
9430 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9433 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9434 DAG.getIntPtrConstant(0));
9436 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9437 DAG.getIntPtrConstant(4));
9439 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9440 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9443 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9444 -1, -1, -1, -1, -1, -1, -1, -1};
9446 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9447 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9448 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9450 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9451 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9453 // The MOVLHPS Mask:
9454 static const int ShufMask2[] = {0, 1, 4, 5};
9455 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9456 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9459 // Handle truncation of V256 to V128 using shuffles.
9460 if (!VT.is128BitVector() || !InVT.is256BitVector())
9463 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9465 unsigned NumElems = VT.getVectorNumElements();
9466 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9468 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9469 // Prepare truncation shuffle mask
9470 for (unsigned i = 0; i != NumElems; ++i)
9472 SDValue V = DAG.getVectorShuffle(NVT, DL,
9473 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9474 DAG.getUNDEF(NVT), &MaskVec[0]);
9475 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9476 DAG.getIntPtrConstant(0));
9479 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9480 SelectionDAG &DAG) const {
9481 assert(!Op.getSimpleValueType().isVector());
9483 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9484 /*IsSigned=*/ true, /*IsReplace=*/ false);
9485 SDValue FIST = Vals.first, StackSlot = Vals.second;
9486 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9487 if (!FIST.getNode()) return Op;
9489 if (StackSlot.getNode())
9491 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9492 FIST, StackSlot, MachinePointerInfo(),
9493 false, false, false, 0);
9495 // The node is the result.
9499 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9500 SelectionDAG &DAG) const {
9501 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9502 /*IsSigned=*/ false, /*IsReplace=*/ false);
9503 SDValue FIST = Vals.first, StackSlot = Vals.second;
9504 assert(FIST.getNode() && "Unexpected failure");
9506 if (StackSlot.getNode())
9508 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9509 FIST, StackSlot, MachinePointerInfo(),
9510 false, false, false, 0);
9512 // The node is the result.
9516 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9518 MVT VT = Op.getSimpleValueType();
9519 SDValue In = Op.getOperand(0);
9520 MVT SVT = In.getSimpleValueType();
9522 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9524 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9525 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9526 In, DAG.getUNDEF(SVT)));
9529 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9530 LLVMContext *Context = DAG.getContext();
9532 MVT VT = Op.getSimpleValueType();
9534 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9535 if (VT.isVector()) {
9536 EltVT = VT.getVectorElementType();
9537 NumElts = VT.getVectorNumElements();
9540 if (EltVT == MVT::f64)
9541 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9542 APInt(64, ~(1ULL << 63))));
9544 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9545 APInt(32, ~(1U << 31))));
9546 C = ConstantVector::getSplat(NumElts, C);
9547 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9548 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9549 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9550 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9551 MachinePointerInfo::getConstantPool(),
9552 false, false, false, Alignment);
9553 if (VT.isVector()) {
9554 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9555 return DAG.getNode(ISD::BITCAST, dl, VT,
9556 DAG.getNode(ISD::AND, dl, ANDVT,
9557 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9559 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9561 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9564 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9565 LLVMContext *Context = DAG.getContext();
9567 MVT VT = Op.getSimpleValueType();
9569 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9570 if (VT.isVector()) {
9571 EltVT = VT.getVectorElementType();
9572 NumElts = VT.getVectorNumElements();
9575 if (EltVT == MVT::f64)
9576 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9577 APInt(64, 1ULL << 63)));
9579 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9580 APInt(32, 1U << 31)));
9581 C = ConstantVector::getSplat(NumElts, C);
9582 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9583 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9584 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9585 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9586 MachinePointerInfo::getConstantPool(),
9587 false, false, false, Alignment);
9588 if (VT.isVector()) {
9589 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9590 return DAG.getNode(ISD::BITCAST, dl, VT,
9591 DAG.getNode(ISD::XOR, dl, XORVT,
9592 DAG.getNode(ISD::BITCAST, dl, XORVT,
9594 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9597 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9600 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9601 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9602 LLVMContext *Context = DAG.getContext();
9603 SDValue Op0 = Op.getOperand(0);
9604 SDValue Op1 = Op.getOperand(1);
9606 MVT VT = Op.getSimpleValueType();
9607 MVT SrcVT = Op1.getSimpleValueType();
9609 // If second operand is smaller, extend it first.
9610 if (SrcVT.bitsLT(VT)) {
9611 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9614 // And if it is bigger, shrink it first.
9615 if (SrcVT.bitsGT(VT)) {
9616 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9620 // At this point the operands and the result should have the same
9621 // type, and that won't be f80 since that is not custom lowered.
9623 // First get the sign bit of second operand.
9624 SmallVector<Constant*,4> CV;
9625 if (SrcVT == MVT::f64) {
9626 const fltSemantics &Sem = APFloat::IEEEdouble;
9627 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9628 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9630 const fltSemantics &Sem = APFloat::IEEEsingle;
9631 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9632 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9633 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9634 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9636 Constant *C = ConstantVector::get(CV);
9637 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9638 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9639 MachinePointerInfo::getConstantPool(),
9640 false, false, false, 16);
9641 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9643 // Shift sign bit right or left if the two operands have different types.
9644 if (SrcVT.bitsGT(VT)) {
9645 // Op0 is MVT::f32, Op1 is MVT::f64.
9646 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9647 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9648 DAG.getConstant(32, MVT::i32));
9649 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9650 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9651 DAG.getIntPtrConstant(0));
9654 // Clear first operand sign bit.
9656 if (VT == MVT::f64) {
9657 const fltSemantics &Sem = APFloat::IEEEdouble;
9658 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9659 APInt(64, ~(1ULL << 63)))));
9660 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9662 const fltSemantics &Sem = APFloat::IEEEsingle;
9663 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9664 APInt(32, ~(1U << 31)))));
9665 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9666 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9667 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9669 C = ConstantVector::get(CV);
9670 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9671 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9672 MachinePointerInfo::getConstantPool(),
9673 false, false, false, 16);
9674 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9676 // Or the value with the sign bit.
9677 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9680 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9681 SDValue N0 = Op.getOperand(0);
9683 MVT VT = Op.getSimpleValueType();
9685 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9686 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9687 DAG.getConstant(1, VT));
9688 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9691 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9693 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9694 SelectionDAG &DAG) {
9695 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9697 if (!Subtarget->hasSSE41())
9700 if (!Op->hasOneUse())
9703 SDNode *N = Op.getNode();
9706 SmallVector<SDValue, 8> Opnds;
9707 DenseMap<SDValue, unsigned> VecInMap;
9708 SmallVector<SDValue, 8> VecIns;
9709 EVT VT = MVT::Other;
9711 // Recognize a special case where a vector is casted into wide integer to
9713 Opnds.push_back(N->getOperand(0));
9714 Opnds.push_back(N->getOperand(1));
9716 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9717 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9718 // BFS traverse all OR'd operands.
9719 if (I->getOpcode() == ISD::OR) {
9720 Opnds.push_back(I->getOperand(0));
9721 Opnds.push_back(I->getOperand(1));
9722 // Re-evaluate the number of nodes to be traversed.
9723 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9727 // Quit if a non-EXTRACT_VECTOR_ELT
9728 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9731 // Quit if without a constant index.
9732 SDValue Idx = I->getOperand(1);
9733 if (!isa<ConstantSDNode>(Idx))
9736 SDValue ExtractedFromVec = I->getOperand(0);
9737 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9738 if (M == VecInMap.end()) {
9739 VT = ExtractedFromVec.getValueType();
9740 // Quit if not 128/256-bit vector.
9741 if (!VT.is128BitVector() && !VT.is256BitVector())
9743 // Quit if not the same type.
9744 if (VecInMap.begin() != VecInMap.end() &&
9745 VT != VecInMap.begin()->first.getValueType())
9747 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9748 VecIns.push_back(ExtractedFromVec);
9750 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9753 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9754 "Not extracted from 128-/256-bit vector.");
9756 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9758 for (DenseMap<SDValue, unsigned>::const_iterator
9759 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9760 // Quit if not all elements are used.
9761 if (I->second != FullMask)
9765 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9767 // Cast all vectors into TestVT for PTEST.
9768 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9769 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9771 // If more than one full vectors are evaluated, OR them first before PTEST.
9772 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9773 // Each iteration will OR 2 nodes and append the result until there is only
9774 // 1 node left, i.e. the final OR'd value of all vectors.
9775 SDValue LHS = VecIns[Slot];
9776 SDValue RHS = VecIns[Slot + 1];
9777 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9780 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9781 VecIns.back(), VecIns.back());
9784 /// \brief return true if \c Op has a use that doesn't just read flags.
9785 static bool hasNonFlagsUse(SDValue Op) {
9786 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9789 unsigned UOpNo = UI.getOperandNo();
9790 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9791 // Look pass truncate.
9792 UOpNo = User->use_begin().getOperandNo();
9793 User = *User->use_begin();
9796 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9797 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9803 /// Emit nodes that will be selected as "test Op0,Op0", or something
9805 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9806 SelectionDAG &DAG) const {
9807 if (Op.getValueType() == MVT::i1)
9808 // KORTEST instruction should be selected
9809 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9810 DAG.getConstant(0, Op.getValueType()));
9812 // CF and OF aren't always set the way we want. Determine which
9813 // of these we need.
9814 bool NeedCF = false;
9815 bool NeedOF = false;
9818 case X86::COND_A: case X86::COND_AE:
9819 case X86::COND_B: case X86::COND_BE:
9822 case X86::COND_G: case X86::COND_GE:
9823 case X86::COND_L: case X86::COND_LE:
9824 case X86::COND_O: case X86::COND_NO:
9828 // See if we can use the EFLAGS value from the operand instead of
9829 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9830 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9831 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9832 // Emit a CMP with 0, which is the TEST pattern.
9833 //if (Op.getValueType() == MVT::i1)
9834 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9835 // DAG.getConstant(0, MVT::i1));
9836 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9837 DAG.getConstant(0, Op.getValueType()));
9839 unsigned Opcode = 0;
9840 unsigned NumOperands = 0;
9842 // Truncate operations may prevent the merge of the SETCC instruction
9843 // and the arithmetic instruction before it. Attempt to truncate the operands
9844 // of the arithmetic instruction and use a reduced bit-width instruction.
9845 bool NeedTruncation = false;
9846 SDValue ArithOp = Op;
9847 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9848 SDValue Arith = Op->getOperand(0);
9849 // Both the trunc and the arithmetic op need to have one user each.
9850 if (Arith->hasOneUse())
9851 switch (Arith.getOpcode()) {
9858 NeedTruncation = true;
9864 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9865 // which may be the result of a CAST. We use the variable 'Op', which is the
9866 // non-casted variable when we check for possible users.
9867 switch (ArithOp.getOpcode()) {
9869 // Due to an isel shortcoming, be conservative if this add is likely to be
9870 // selected as part of a load-modify-store instruction. When the root node
9871 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9872 // uses of other nodes in the match, such as the ADD in this case. This
9873 // leads to the ADD being left around and reselected, with the result being
9874 // two adds in the output. Alas, even if none our users are stores, that
9875 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9876 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9877 // climbing the DAG back to the root, and it doesn't seem to be worth the
9879 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9880 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9881 if (UI->getOpcode() != ISD::CopyToReg &&
9882 UI->getOpcode() != ISD::SETCC &&
9883 UI->getOpcode() != ISD::STORE)
9886 if (ConstantSDNode *C =
9887 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9888 // An add of one will be selected as an INC.
9889 if (C->getAPIntValue() == 1) {
9890 Opcode = X86ISD::INC;
9895 // An add of negative one (subtract of one) will be selected as a DEC.
9896 if (C->getAPIntValue().isAllOnesValue()) {
9897 Opcode = X86ISD::DEC;
9903 // Otherwise use a regular EFLAGS-setting add.
9904 Opcode = X86ISD::ADD;
9909 // If we have a constant logical shift that's only used in a comparison
9910 // against zero turn it into an equivalent AND. This allows turning it into
9911 // a TEST instruction later.
9912 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9913 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9914 EVT VT = Op.getValueType();
9915 unsigned BitWidth = VT.getSizeInBits();
9916 unsigned ShAmt = Op->getConstantOperandVal(1);
9917 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9919 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9920 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9921 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9922 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9924 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9925 DAG.getConstant(Mask, VT));
9926 DAG.ReplaceAllUsesWith(Op, New);
9932 // If the primary and result isn't used, don't bother using X86ISD::AND,
9933 // because a TEST instruction will be better.
9934 if (!hasNonFlagsUse(Op))
9940 // Due to the ISEL shortcoming noted above, be conservative if this op is
9941 // likely to be selected as part of a load-modify-store instruction.
9942 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9943 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9944 if (UI->getOpcode() == ISD::STORE)
9947 // Otherwise use a regular EFLAGS-setting instruction.
9948 switch (ArithOp.getOpcode()) {
9949 default: llvm_unreachable("unexpected operator!");
9950 case ISD::SUB: Opcode = X86ISD::SUB; break;
9951 case ISD::XOR: Opcode = X86ISD::XOR; break;
9952 case ISD::AND: Opcode = X86ISD::AND; break;
9954 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9955 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9956 if (EFLAGS.getNode())
9959 Opcode = X86ISD::OR;
9973 return SDValue(Op.getNode(), 1);
9979 // If we found that truncation is beneficial, perform the truncation and
9981 if (NeedTruncation) {
9982 EVT VT = Op.getValueType();
9983 SDValue WideVal = Op->getOperand(0);
9984 EVT WideVT = WideVal.getValueType();
9985 unsigned ConvertedOp = 0;
9986 // Use a target machine opcode to prevent further DAGCombine
9987 // optimizations that may separate the arithmetic operations
9988 // from the setcc node.
9989 switch (WideVal.getOpcode()) {
9991 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9992 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9993 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9994 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9995 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9999 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10000 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10001 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10002 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10003 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10009 // Emit a CMP with 0, which is the TEST pattern.
10010 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10011 DAG.getConstant(0, Op.getValueType()));
10013 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10014 SmallVector<SDValue, 4> Ops;
10015 for (unsigned i = 0; i != NumOperands; ++i)
10016 Ops.push_back(Op.getOperand(i));
10018 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
10019 DAG.ReplaceAllUsesWith(Op, New);
10020 return SDValue(New.getNode(), 1);
10023 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10025 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10026 SDLoc dl, SelectionDAG &DAG) const {
10027 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10028 if (C->getAPIntValue() == 0)
10029 return EmitTest(Op0, X86CC, dl, DAG);
10031 if (Op0.getValueType() == MVT::i1)
10032 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10035 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10036 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10037 // Do the comparison at i32 if it's smaller, besides the Atom case.
10038 // This avoids subregister aliasing issues. Keep the smaller reference
10039 // if we're optimizing for size, however, as that'll allow better folding
10040 // of memory operations.
10041 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10042 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10043 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10044 !Subtarget->isAtom()) {
10045 unsigned ExtendOp =
10046 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10047 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10048 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10050 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10051 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10052 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10054 return SDValue(Sub.getNode(), 1);
10056 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10059 /// Convert a comparison if required by the subtarget.
10060 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10061 SelectionDAG &DAG) const {
10062 // If the subtarget does not support the FUCOMI instruction, floating-point
10063 // comparisons have to be converted.
10064 if (Subtarget->hasCMov() ||
10065 Cmp.getOpcode() != X86ISD::CMP ||
10066 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10067 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10070 // The instruction selector will select an FUCOM instruction instead of
10071 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10072 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10073 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10075 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10076 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10077 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10078 DAG.getConstant(8, MVT::i8));
10079 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10080 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10083 static bool isAllOnes(SDValue V) {
10084 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10085 return C && C->isAllOnesValue();
10088 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10089 /// if it's possible.
10090 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10091 SDLoc dl, SelectionDAG &DAG) const {
10092 SDValue Op0 = And.getOperand(0);
10093 SDValue Op1 = And.getOperand(1);
10094 if (Op0.getOpcode() == ISD::TRUNCATE)
10095 Op0 = Op0.getOperand(0);
10096 if (Op1.getOpcode() == ISD::TRUNCATE)
10097 Op1 = Op1.getOperand(0);
10100 if (Op1.getOpcode() == ISD::SHL)
10101 std::swap(Op0, Op1);
10102 if (Op0.getOpcode() == ISD::SHL) {
10103 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10104 if (And00C->getZExtValue() == 1) {
10105 // If we looked past a truncate, check that it's only truncating away
10107 unsigned BitWidth = Op0.getValueSizeInBits();
10108 unsigned AndBitWidth = And.getValueSizeInBits();
10109 if (BitWidth > AndBitWidth) {
10111 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10112 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10116 RHS = Op0.getOperand(1);
10118 } else if (Op1.getOpcode() == ISD::Constant) {
10119 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10120 uint64_t AndRHSVal = AndRHS->getZExtValue();
10121 SDValue AndLHS = Op0;
10123 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10124 LHS = AndLHS.getOperand(0);
10125 RHS = AndLHS.getOperand(1);
10128 // Use BT if the immediate can't be encoded in a TEST instruction.
10129 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10131 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10135 if (LHS.getNode()) {
10136 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10137 // instruction. Since the shift amount is in-range-or-undefined, we know
10138 // that doing a bittest on the i32 value is ok. We extend to i32 because
10139 // the encoding for the i16 version is larger than the i32 version.
10140 // Also promote i16 to i32 for performance / code size reason.
10141 if (LHS.getValueType() == MVT::i8 ||
10142 LHS.getValueType() == MVT::i16)
10143 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10145 // If the operand types disagree, extend the shift amount to match. Since
10146 // BT ignores high bits (like shifts) we can use anyextend.
10147 if (LHS.getValueType() != RHS.getValueType())
10148 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10150 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10151 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10152 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10153 DAG.getConstant(Cond, MVT::i8), BT);
10159 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10161 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10166 // SSE Condition code mapping:
10175 switch (SetCCOpcode) {
10176 default: llvm_unreachable("Unexpected SETCC condition");
10178 case ISD::SETEQ: SSECC = 0; break;
10180 case ISD::SETGT: Swap = true; // Fallthrough
10182 case ISD::SETOLT: SSECC = 1; break;
10184 case ISD::SETGE: Swap = true; // Fallthrough
10186 case ISD::SETOLE: SSECC = 2; break;
10187 case ISD::SETUO: SSECC = 3; break;
10189 case ISD::SETNE: SSECC = 4; break;
10190 case ISD::SETULE: Swap = true; // Fallthrough
10191 case ISD::SETUGE: SSECC = 5; break;
10192 case ISD::SETULT: Swap = true; // Fallthrough
10193 case ISD::SETUGT: SSECC = 6; break;
10194 case ISD::SETO: SSECC = 7; break;
10196 case ISD::SETONE: SSECC = 8; break;
10199 std::swap(Op0, Op1);
10204 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10205 // ones, and then concatenate the result back.
10206 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10207 MVT VT = Op.getSimpleValueType();
10209 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10210 "Unsupported value type for operation");
10212 unsigned NumElems = VT.getVectorNumElements();
10214 SDValue CC = Op.getOperand(2);
10216 // Extract the LHS vectors
10217 SDValue LHS = Op.getOperand(0);
10218 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10219 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10221 // Extract the RHS vectors
10222 SDValue RHS = Op.getOperand(1);
10223 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10224 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10226 // Issue the operation on the smaller types and concatenate the result back
10227 MVT EltVT = VT.getVectorElementType();
10228 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10229 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10230 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10231 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10234 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10235 const X86Subtarget *Subtarget) {
10236 SDValue Op0 = Op.getOperand(0);
10237 SDValue Op1 = Op.getOperand(1);
10238 SDValue CC = Op.getOperand(2);
10239 MVT VT = Op.getSimpleValueType();
10242 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10243 Op.getValueType().getScalarType() == MVT::i1 &&
10244 "Cannot set masked compare for this operation");
10246 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10248 bool Unsigned = false;
10251 switch (SetCCOpcode) {
10252 default: llvm_unreachable("Unexpected SETCC condition");
10253 case ISD::SETNE: SSECC = 4; break;
10254 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10255 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10256 case ISD::SETLT: Swap = true; //fall-through
10257 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10258 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10259 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10260 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10261 case ISD::SETULE: Unsigned = true; //fall-through
10262 case ISD::SETLE: SSECC = 2; break;
10266 std::swap(Op0, Op1);
10268 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10269 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10270 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10271 DAG.getConstant(SSECC, MVT::i8));
10274 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10275 /// operand \p Op1. If non-trivial (for example because it's not constant)
10276 /// return an empty value.
10277 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10279 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10283 MVT VT = Op1.getSimpleValueType();
10284 MVT EVT = VT.getVectorElementType();
10285 unsigned n = VT.getVectorNumElements();
10286 SmallVector<SDValue, 8> ULTOp1;
10288 for (unsigned i = 0; i < n; ++i) {
10289 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10290 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10293 // Avoid underflow.
10294 APInt Val = Elt->getAPIntValue();
10298 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10301 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1.data(), ULTOp1.size());
10304 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10305 SelectionDAG &DAG) {
10306 SDValue Op0 = Op.getOperand(0);
10307 SDValue Op1 = Op.getOperand(1);
10308 SDValue CC = Op.getOperand(2);
10309 MVT VT = Op.getSimpleValueType();
10310 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10311 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10316 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10317 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10320 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10321 unsigned Opc = X86ISD::CMPP;
10322 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10323 assert(VT.getVectorNumElements() <= 16);
10324 Opc = X86ISD::CMPM;
10326 // In the two special cases we can't handle, emit two comparisons.
10329 unsigned CombineOpc;
10330 if (SetCCOpcode == ISD::SETUEQ) {
10331 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10333 assert(SetCCOpcode == ISD::SETONE);
10334 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10337 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10338 DAG.getConstant(CC0, MVT::i8));
10339 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10340 DAG.getConstant(CC1, MVT::i8));
10341 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10343 // Handle all other FP comparisons here.
10344 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10345 DAG.getConstant(SSECC, MVT::i8));
10348 // Break 256-bit integer vector compare into smaller ones.
10349 if (VT.is256BitVector() && !Subtarget->hasInt256())
10350 return Lower256IntVSETCC(Op, DAG);
10352 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10353 EVT OpVT = Op1.getValueType();
10354 if (Subtarget->hasAVX512()) {
10355 if (Op1.getValueType().is512BitVector() ||
10356 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10357 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10359 // In AVX-512 architecture setcc returns mask with i1 elements,
10360 // But there is no compare instruction for i8 and i16 elements.
10361 // We are not talking about 512-bit operands in this case, these
10362 // types are illegal.
10364 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10365 OpVT.getVectorElementType().getSizeInBits() >= 8))
10366 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10367 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10370 // We are handling one of the integer comparisons here. Since SSE only has
10371 // GT and EQ comparisons for integer, swapping operands and multiple
10372 // operations may be required for some comparisons.
10374 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10375 bool Subus = false;
10377 switch (SetCCOpcode) {
10378 default: llvm_unreachable("Unexpected SETCC condition");
10379 case ISD::SETNE: Invert = true;
10380 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10381 case ISD::SETLT: Swap = true;
10382 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10383 case ISD::SETGE: Swap = true;
10384 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10385 Invert = true; break;
10386 case ISD::SETULT: Swap = true;
10387 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10388 FlipSigns = true; break;
10389 case ISD::SETUGE: Swap = true;
10390 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10391 FlipSigns = true; Invert = true; break;
10394 // Special case: Use min/max operations for SETULE/SETUGE
10395 MVT VET = VT.getVectorElementType();
10397 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10398 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10401 switch (SetCCOpcode) {
10403 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10404 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10407 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10410 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10411 if (!MinMax && hasSubus) {
10412 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10414 // t = psubus Op0, Op1
10415 // pcmpeq t, <0..0>
10416 switch (SetCCOpcode) {
10418 case ISD::SETULT: {
10419 // If the comparison is against a constant we can turn this into a
10420 // setule. With psubus, setule does not require a swap. This is
10421 // beneficial because the constant in the register is no longer
10422 // destructed as the destination so it can be hoisted out of a loop.
10423 // Only do this pre-AVX since vpcmp* is no longer destructive.
10424 if (Subtarget->hasAVX())
10426 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10427 if (ULEOp1.getNode()) {
10429 Subus = true; Invert = false; Swap = false;
10433 // Psubus is better than flip-sign because it requires no inversion.
10434 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10435 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10439 Opc = X86ISD::SUBUS;
10445 std::swap(Op0, Op1);
10447 // Check that the operation in question is available (most are plain SSE2,
10448 // but PCMPGTQ and PCMPEQQ have different requirements).
10449 if (VT == MVT::v2i64) {
10450 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10451 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10453 // First cast everything to the right type.
10454 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10455 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10457 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10458 // bits of the inputs before performing those operations. The lower
10459 // compare is always unsigned.
10462 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10464 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10465 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10466 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10467 Sign, Zero, Sign, Zero);
10469 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10470 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10472 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10473 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10474 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10476 // Create masks for only the low parts/high parts of the 64 bit integers.
10477 static const int MaskHi[] = { 1, 1, 3, 3 };
10478 static const int MaskLo[] = { 0, 0, 2, 2 };
10479 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10480 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10481 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10483 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10484 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10487 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10489 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10492 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10493 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10494 // pcmpeqd + pshufd + pand.
10495 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10497 // First cast everything to the right type.
10498 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10499 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10502 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10504 // Make sure the lower and upper halves are both all-ones.
10505 static const int Mask[] = { 1, 0, 3, 2 };
10506 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10507 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10510 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10512 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10516 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10517 // bits of the inputs before performing those operations.
10519 EVT EltVT = VT.getVectorElementType();
10520 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10521 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10522 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10525 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10527 // If the logical-not of the result is required, perform that now.
10529 Result = DAG.getNOT(dl, Result, VT);
10532 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10535 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10536 getZeroVector(VT, Subtarget, DAG, dl));
10541 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10543 MVT VT = Op.getSimpleValueType();
10545 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10547 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10548 && "SetCC type must be 8-bit or 1-bit integer");
10549 SDValue Op0 = Op.getOperand(0);
10550 SDValue Op1 = Op.getOperand(1);
10552 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10554 // Optimize to BT if possible.
10555 // Lower (X & (1 << N)) == 0 to BT(X, N).
10556 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10557 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10558 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10559 Op1.getOpcode() == ISD::Constant &&
10560 cast<ConstantSDNode>(Op1)->isNullValue() &&
10561 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10562 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10563 if (NewSetCC.getNode())
10567 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10569 if (Op1.getOpcode() == ISD::Constant &&
10570 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10571 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10572 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10574 // If the input is a setcc, then reuse the input setcc or use a new one with
10575 // the inverted condition.
10576 if (Op0.getOpcode() == X86ISD::SETCC) {
10577 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10578 bool Invert = (CC == ISD::SETNE) ^
10579 cast<ConstantSDNode>(Op1)->isNullValue();
10583 CCode = X86::GetOppositeBranchCondition(CCode);
10584 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10585 DAG.getConstant(CCode, MVT::i8),
10586 Op0.getOperand(1));
10588 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10592 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10593 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10594 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10596 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10597 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10600 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10601 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10602 if (X86CC == X86::COND_INVALID)
10605 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10606 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10607 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10608 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10610 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10614 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10615 static bool isX86LogicalCmp(SDValue Op) {
10616 unsigned Opc = Op.getNode()->getOpcode();
10617 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10618 Opc == X86ISD::SAHF)
10620 if (Op.getResNo() == 1 &&
10621 (Opc == X86ISD::ADD ||
10622 Opc == X86ISD::SUB ||
10623 Opc == X86ISD::ADC ||
10624 Opc == X86ISD::SBB ||
10625 Opc == X86ISD::SMUL ||
10626 Opc == X86ISD::UMUL ||
10627 Opc == X86ISD::INC ||
10628 Opc == X86ISD::DEC ||
10629 Opc == X86ISD::OR ||
10630 Opc == X86ISD::XOR ||
10631 Opc == X86ISD::AND))
10634 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10640 static bool isZero(SDValue V) {
10641 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10642 return C && C->isNullValue();
10645 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10646 if (V.getOpcode() != ISD::TRUNCATE)
10649 SDValue VOp0 = V.getOperand(0);
10650 unsigned InBits = VOp0.getValueSizeInBits();
10651 unsigned Bits = V.getValueSizeInBits();
10652 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10655 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10656 bool addTest = true;
10657 SDValue Cond = Op.getOperand(0);
10658 SDValue Op1 = Op.getOperand(1);
10659 SDValue Op2 = Op.getOperand(2);
10661 EVT VT = Op1.getValueType();
10664 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10665 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10666 // sequence later on.
10667 if (Cond.getOpcode() == ISD::SETCC &&
10668 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10669 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10670 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10671 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10672 int SSECC = translateX86FSETCC(
10673 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10676 if (Subtarget->hasAVX512()) {
10677 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10678 DAG.getConstant(SSECC, MVT::i8));
10679 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10681 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10682 DAG.getConstant(SSECC, MVT::i8));
10683 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10684 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10685 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10689 if (Cond.getOpcode() == ISD::SETCC) {
10690 SDValue NewCond = LowerSETCC(Cond, DAG);
10691 if (NewCond.getNode())
10695 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10696 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10697 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10698 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10699 if (Cond.getOpcode() == X86ISD::SETCC &&
10700 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10701 isZero(Cond.getOperand(1).getOperand(1))) {
10702 SDValue Cmp = Cond.getOperand(1);
10704 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10706 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10707 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10708 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10710 SDValue CmpOp0 = Cmp.getOperand(0);
10711 // Apply further optimizations for special cases
10712 // (select (x != 0), -1, 0) -> neg & sbb
10713 // (select (x == 0), 0, -1) -> neg & sbb
10714 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10715 if (YC->isNullValue() &&
10716 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10717 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10718 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10719 DAG.getConstant(0, CmpOp0.getValueType()),
10721 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10722 DAG.getConstant(X86::COND_B, MVT::i8),
10723 SDValue(Neg.getNode(), 1));
10727 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10728 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10729 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10731 SDValue Res = // Res = 0 or -1.
10732 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10733 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10735 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10736 Res = DAG.getNOT(DL, Res, Res.getValueType());
10738 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10739 if (!N2C || !N2C->isNullValue())
10740 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10745 // Look past (and (setcc_carry (cmp ...)), 1).
10746 if (Cond.getOpcode() == ISD::AND &&
10747 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10748 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10749 if (C && C->getAPIntValue() == 1)
10750 Cond = Cond.getOperand(0);
10753 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10754 // setting operand in place of the X86ISD::SETCC.
10755 unsigned CondOpcode = Cond.getOpcode();
10756 if (CondOpcode == X86ISD::SETCC ||
10757 CondOpcode == X86ISD::SETCC_CARRY) {
10758 CC = Cond.getOperand(0);
10760 SDValue Cmp = Cond.getOperand(1);
10761 unsigned Opc = Cmp.getOpcode();
10762 MVT VT = Op.getSimpleValueType();
10764 bool IllegalFPCMov = false;
10765 if (VT.isFloatingPoint() && !VT.isVector() &&
10766 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10767 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10769 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10770 Opc == X86ISD::BT) { // FIXME
10774 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10775 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10776 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10777 Cond.getOperand(0).getValueType() != MVT::i8)) {
10778 SDValue LHS = Cond.getOperand(0);
10779 SDValue RHS = Cond.getOperand(1);
10780 unsigned X86Opcode;
10783 switch (CondOpcode) {
10784 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10785 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10786 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10787 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10788 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10789 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10790 default: llvm_unreachable("unexpected overflowing operator");
10792 if (CondOpcode == ISD::UMULO)
10793 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10796 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10798 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10800 if (CondOpcode == ISD::UMULO)
10801 Cond = X86Op.getValue(2);
10803 Cond = X86Op.getValue(1);
10805 CC = DAG.getConstant(X86Cond, MVT::i8);
10810 // Look pass the truncate if the high bits are known zero.
10811 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10812 Cond = Cond.getOperand(0);
10814 // We know the result of AND is compared against zero. Try to match
10816 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10817 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10818 if (NewSetCC.getNode()) {
10819 CC = NewSetCC.getOperand(0);
10820 Cond = NewSetCC.getOperand(1);
10827 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10828 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10831 // a < b ? -1 : 0 -> RES = ~setcc_carry
10832 // a < b ? 0 : -1 -> RES = setcc_carry
10833 // a >= b ? -1 : 0 -> RES = setcc_carry
10834 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10835 if (Cond.getOpcode() == X86ISD::SUB) {
10836 Cond = ConvertCmpIfNecessary(Cond, DAG);
10837 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10839 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10840 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10841 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10842 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10843 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10844 return DAG.getNOT(DL, Res, Res.getValueType());
10849 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10850 // widen the cmov and push the truncate through. This avoids introducing a new
10851 // branch during isel and doesn't add any extensions.
10852 if (Op.getValueType() == MVT::i8 &&
10853 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10854 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10855 if (T1.getValueType() == T2.getValueType() &&
10856 // Blacklist CopyFromReg to avoid partial register stalls.
10857 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10858 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10859 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10860 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10864 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10865 // condition is true.
10866 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10867 SDValue Ops[] = { Op2, Op1, CC, Cond };
10868 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10871 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10872 MVT VT = Op->getSimpleValueType(0);
10873 SDValue In = Op->getOperand(0);
10874 MVT InVT = In.getSimpleValueType();
10877 unsigned int NumElts = VT.getVectorNumElements();
10878 if (NumElts != 8 && NumElts != 16)
10881 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10882 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10884 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10885 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10887 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10888 Constant *C = ConstantInt::get(*DAG.getContext(),
10889 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10891 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10892 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10893 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10894 MachinePointerInfo::getConstantPool(),
10895 false, false, false, Alignment);
10896 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10897 if (VT.is512BitVector())
10899 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10902 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10903 SelectionDAG &DAG) {
10904 MVT VT = Op->getSimpleValueType(0);
10905 SDValue In = Op->getOperand(0);
10906 MVT InVT = In.getSimpleValueType();
10909 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10910 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10912 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10913 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10914 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10917 if (Subtarget->hasInt256())
10918 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10920 // Optimize vectors in AVX mode
10921 // Sign extend v8i16 to v8i32 and
10924 // Divide input vector into two parts
10925 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10926 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10927 // concat the vectors to original VT
10929 unsigned NumElems = InVT.getVectorNumElements();
10930 SDValue Undef = DAG.getUNDEF(InVT);
10932 SmallVector<int,8> ShufMask1(NumElems, -1);
10933 for (unsigned i = 0; i != NumElems/2; ++i)
10936 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10938 SmallVector<int,8> ShufMask2(NumElems, -1);
10939 for (unsigned i = 0; i != NumElems/2; ++i)
10940 ShufMask2[i] = i + NumElems/2;
10942 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10944 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10945 VT.getVectorNumElements()/2);
10947 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10948 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10950 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10953 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10954 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10955 // from the AND / OR.
10956 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10957 Opc = Op.getOpcode();
10958 if (Opc != ISD::OR && Opc != ISD::AND)
10960 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10961 Op.getOperand(0).hasOneUse() &&
10962 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10963 Op.getOperand(1).hasOneUse());
10966 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10967 // 1 and that the SETCC node has a single use.
10968 static bool isXor1OfSetCC(SDValue Op) {
10969 if (Op.getOpcode() != ISD::XOR)
10971 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10972 if (N1C && N1C->getAPIntValue() == 1) {
10973 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10974 Op.getOperand(0).hasOneUse();
10979 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10980 bool addTest = true;
10981 SDValue Chain = Op.getOperand(0);
10982 SDValue Cond = Op.getOperand(1);
10983 SDValue Dest = Op.getOperand(2);
10986 bool Inverted = false;
10988 if (Cond.getOpcode() == ISD::SETCC) {
10989 // Check for setcc([su]{add,sub,mul}o == 0).
10990 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10991 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10992 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10993 Cond.getOperand(0).getResNo() == 1 &&
10994 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10995 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10996 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10997 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10998 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10999 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11001 Cond = Cond.getOperand(0);
11003 SDValue NewCond = LowerSETCC(Cond, DAG);
11004 if (NewCond.getNode())
11009 // FIXME: LowerXALUO doesn't handle these!!
11010 else if (Cond.getOpcode() == X86ISD::ADD ||
11011 Cond.getOpcode() == X86ISD::SUB ||
11012 Cond.getOpcode() == X86ISD::SMUL ||
11013 Cond.getOpcode() == X86ISD::UMUL)
11014 Cond = LowerXALUO(Cond, DAG);
11017 // Look pass (and (setcc_carry (cmp ...)), 1).
11018 if (Cond.getOpcode() == ISD::AND &&
11019 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11020 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11021 if (C && C->getAPIntValue() == 1)
11022 Cond = Cond.getOperand(0);
11025 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11026 // setting operand in place of the X86ISD::SETCC.
11027 unsigned CondOpcode = Cond.getOpcode();
11028 if (CondOpcode == X86ISD::SETCC ||
11029 CondOpcode == X86ISD::SETCC_CARRY) {
11030 CC = Cond.getOperand(0);
11032 SDValue Cmp = Cond.getOperand(1);
11033 unsigned Opc = Cmp.getOpcode();
11034 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11035 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11039 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11043 // These can only come from an arithmetic instruction with overflow,
11044 // e.g. SADDO, UADDO.
11045 Cond = Cond.getNode()->getOperand(1);
11051 CondOpcode = Cond.getOpcode();
11052 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11053 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11054 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11055 Cond.getOperand(0).getValueType() != MVT::i8)) {
11056 SDValue LHS = Cond.getOperand(0);
11057 SDValue RHS = Cond.getOperand(1);
11058 unsigned X86Opcode;
11061 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11062 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11064 switch (CondOpcode) {
11065 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11067 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11069 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11072 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11073 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11075 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11077 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11080 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11081 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11082 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11083 default: llvm_unreachable("unexpected overflowing operator");
11086 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11087 if (CondOpcode == ISD::UMULO)
11088 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11091 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11093 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11095 if (CondOpcode == ISD::UMULO)
11096 Cond = X86Op.getValue(2);
11098 Cond = X86Op.getValue(1);
11100 CC = DAG.getConstant(X86Cond, MVT::i8);
11104 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11105 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11106 if (CondOpc == ISD::OR) {
11107 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11108 // two branches instead of an explicit OR instruction with a
11110 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11111 isX86LogicalCmp(Cmp)) {
11112 CC = Cond.getOperand(0).getOperand(0);
11113 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11114 Chain, Dest, CC, Cmp);
11115 CC = Cond.getOperand(1).getOperand(0);
11119 } else { // ISD::AND
11120 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11121 // two branches instead of an explicit AND instruction with a
11122 // separate test. However, we only do this if this block doesn't
11123 // have a fall-through edge, because this requires an explicit
11124 // jmp when the condition is false.
11125 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11126 isX86LogicalCmp(Cmp) &&
11127 Op.getNode()->hasOneUse()) {
11128 X86::CondCode CCode =
11129 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11130 CCode = X86::GetOppositeBranchCondition(CCode);
11131 CC = DAG.getConstant(CCode, MVT::i8);
11132 SDNode *User = *Op.getNode()->use_begin();
11133 // Look for an unconditional branch following this conditional branch.
11134 // We need this because we need to reverse the successors in order
11135 // to implement FCMP_OEQ.
11136 if (User->getOpcode() == ISD::BR) {
11137 SDValue FalseBB = User->getOperand(1);
11139 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11140 assert(NewBR == User);
11144 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11145 Chain, Dest, CC, Cmp);
11146 X86::CondCode CCode =
11147 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11148 CCode = X86::GetOppositeBranchCondition(CCode);
11149 CC = DAG.getConstant(CCode, MVT::i8);
11155 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11156 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11157 // It should be transformed during dag combiner except when the condition
11158 // is set by a arithmetics with overflow node.
11159 X86::CondCode CCode =
11160 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11161 CCode = X86::GetOppositeBranchCondition(CCode);
11162 CC = DAG.getConstant(CCode, MVT::i8);
11163 Cond = Cond.getOperand(0).getOperand(1);
11165 } else if (Cond.getOpcode() == ISD::SETCC &&
11166 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11167 // For FCMP_OEQ, we can emit
11168 // two branches instead of an explicit AND instruction with a
11169 // separate test. However, we only do this if this block doesn't
11170 // have a fall-through edge, because this requires an explicit
11171 // jmp when the condition is false.
11172 if (Op.getNode()->hasOneUse()) {
11173 SDNode *User = *Op.getNode()->use_begin();
11174 // Look for an unconditional branch following this conditional branch.
11175 // We need this because we need to reverse the successors in order
11176 // to implement FCMP_OEQ.
11177 if (User->getOpcode() == ISD::BR) {
11178 SDValue FalseBB = User->getOperand(1);
11180 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11181 assert(NewBR == User);
11185 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11186 Cond.getOperand(0), Cond.getOperand(1));
11187 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11188 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11189 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11190 Chain, Dest, CC, Cmp);
11191 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11196 } else if (Cond.getOpcode() == ISD::SETCC &&
11197 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11198 // For FCMP_UNE, we can emit
11199 // two branches instead of an explicit AND instruction with a
11200 // separate test. However, we only do this if this block doesn't
11201 // have a fall-through edge, because this requires an explicit
11202 // jmp when the condition is false.
11203 if (Op.getNode()->hasOneUse()) {
11204 SDNode *User = *Op.getNode()->use_begin();
11205 // Look for an unconditional branch following this conditional branch.
11206 // We need this because we need to reverse the successors in order
11207 // to implement FCMP_UNE.
11208 if (User->getOpcode() == ISD::BR) {
11209 SDValue FalseBB = User->getOperand(1);
11211 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11212 assert(NewBR == User);
11215 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11216 Cond.getOperand(0), Cond.getOperand(1));
11217 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11218 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11219 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11220 Chain, Dest, CC, Cmp);
11221 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11231 // Look pass the truncate if the high bits are known zero.
11232 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11233 Cond = Cond.getOperand(0);
11235 // We know the result of AND is compared against zero. Try to match
11237 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11238 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11239 if (NewSetCC.getNode()) {
11240 CC = NewSetCC.getOperand(0);
11241 Cond = NewSetCC.getOperand(1);
11248 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11249 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11251 Cond = ConvertCmpIfNecessary(Cond, DAG);
11252 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11253 Chain, Dest, CC, Cond);
11256 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11257 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11258 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11259 // that the guard pages used by the OS virtual memory manager are allocated in
11260 // correct sequence.
11262 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11263 SelectionDAG &DAG) const {
11264 MachineFunction &MF = DAG.getMachineFunction();
11265 bool SplitStack = MF.shouldSplitStack();
11266 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11271 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11272 SDNode* Node = Op.getNode();
11274 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11275 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11276 " not tell us which reg is the stack pointer!");
11277 EVT VT = Node->getValueType(0);
11278 SDValue Tmp1 = SDValue(Node, 0);
11279 SDValue Tmp2 = SDValue(Node, 1);
11280 SDValue Tmp3 = Node->getOperand(2);
11281 SDValue Chain = Tmp1.getOperand(0);
11283 // Chain the dynamic stack allocation so that it doesn't modify the stack
11284 // pointer when other instructions are using the stack.
11285 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11288 SDValue Size = Tmp2.getOperand(1);
11289 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11290 Chain = SP.getValue(1);
11291 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11292 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11293 unsigned StackAlign = TFI.getStackAlignment();
11294 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11295 if (Align > StackAlign)
11296 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11297 DAG.getConstant(-(uint64_t)Align, VT));
11298 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11300 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11301 DAG.getIntPtrConstant(0, true), SDValue(),
11304 SDValue Ops[2] = { Tmp1, Tmp2 };
11305 return DAG.getMergeValues(Ops, 2, dl);
11309 SDValue Chain = Op.getOperand(0);
11310 SDValue Size = Op.getOperand(1);
11311 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11312 EVT VT = Op.getNode()->getValueType(0);
11314 bool Is64Bit = Subtarget->is64Bit();
11315 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11318 MachineRegisterInfo &MRI = MF.getRegInfo();
11321 // The 64 bit implementation of segmented stacks needs to clobber both r10
11322 // r11. This makes it impossible to use it along with nested parameters.
11323 const Function *F = MF.getFunction();
11325 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11327 if (I->hasNestAttr())
11328 report_fatal_error("Cannot use segmented stacks with functions that "
11329 "have nested arguments.");
11332 const TargetRegisterClass *AddrRegClass =
11333 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11334 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11335 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11336 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11337 DAG.getRegister(Vreg, SPTy));
11338 SDValue Ops1[2] = { Value, Chain };
11339 return DAG.getMergeValues(Ops1, 2, dl);
11342 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11344 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11345 Flag = Chain.getValue(1);
11346 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11348 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11350 const X86RegisterInfo *RegInfo =
11351 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11352 unsigned SPReg = RegInfo->getStackRegister();
11353 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11354 Chain = SP.getValue(1);
11357 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11358 DAG.getConstant(-(uint64_t)Align, VT));
11359 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11362 SDValue Ops1[2] = { SP, Chain };
11363 return DAG.getMergeValues(Ops1, 2, dl);
11367 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11368 MachineFunction &MF = DAG.getMachineFunction();
11369 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11371 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11374 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11375 // vastart just stores the address of the VarArgsFrameIndex slot into the
11376 // memory location argument.
11377 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11379 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11380 MachinePointerInfo(SV), false, false, 0);
11384 // gp_offset (0 - 6 * 8)
11385 // fp_offset (48 - 48 + 8 * 16)
11386 // overflow_arg_area (point to parameters coming in memory).
11388 SmallVector<SDValue, 8> MemOps;
11389 SDValue FIN = Op.getOperand(1);
11391 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11392 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11394 FIN, MachinePointerInfo(SV), false, false, 0);
11395 MemOps.push_back(Store);
11398 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11399 FIN, DAG.getIntPtrConstant(4));
11400 Store = DAG.getStore(Op.getOperand(0), DL,
11401 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11403 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11404 MemOps.push_back(Store);
11406 // Store ptr to overflow_arg_area
11407 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11408 FIN, DAG.getIntPtrConstant(4));
11409 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11411 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11412 MachinePointerInfo(SV, 8),
11414 MemOps.push_back(Store);
11416 // Store ptr to reg_save_area.
11417 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11418 FIN, DAG.getIntPtrConstant(8));
11419 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11421 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11422 MachinePointerInfo(SV, 16), false, false, 0);
11423 MemOps.push_back(Store);
11424 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11425 &MemOps[0], MemOps.size());
11428 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11429 assert(Subtarget->is64Bit() &&
11430 "LowerVAARG only handles 64-bit va_arg!");
11431 assert((Subtarget->isTargetLinux() ||
11432 Subtarget->isTargetDarwin()) &&
11433 "Unhandled target in LowerVAARG");
11434 assert(Op.getNode()->getNumOperands() == 4);
11435 SDValue Chain = Op.getOperand(0);
11436 SDValue SrcPtr = Op.getOperand(1);
11437 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11438 unsigned Align = Op.getConstantOperandVal(3);
11441 EVT ArgVT = Op.getNode()->getValueType(0);
11442 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11443 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11446 // Decide which area this value should be read from.
11447 // TODO: Implement the AMD64 ABI in its entirety. This simple
11448 // selection mechanism works only for the basic types.
11449 if (ArgVT == MVT::f80) {
11450 llvm_unreachable("va_arg for f80 not yet implemented");
11451 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11452 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11453 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11454 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11456 llvm_unreachable("Unhandled argument type in LowerVAARG");
11459 if (ArgMode == 2) {
11460 // Sanity Check: Make sure using fp_offset makes sense.
11461 assert(!getTargetMachine().Options.UseSoftFloat &&
11462 !(DAG.getMachineFunction()
11463 .getFunction()->getAttributes()
11464 .hasAttribute(AttributeSet::FunctionIndex,
11465 Attribute::NoImplicitFloat)) &&
11466 Subtarget->hasSSE1());
11469 // Insert VAARG_64 node into the DAG
11470 // VAARG_64 returns two values: Variable Argument Address, Chain
11471 SmallVector<SDValue, 11> InstOps;
11472 InstOps.push_back(Chain);
11473 InstOps.push_back(SrcPtr);
11474 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11475 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11476 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11477 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11478 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11479 VTs, &InstOps[0], InstOps.size(),
11481 MachinePointerInfo(SV),
11483 /*Volatile=*/false,
11485 /*WriteMem=*/true);
11486 Chain = VAARG.getValue(1);
11488 // Load the next argument and return it
11489 return DAG.getLoad(ArgVT, dl,
11492 MachinePointerInfo(),
11493 false, false, false, 0);
11496 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11497 SelectionDAG &DAG) {
11498 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11499 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11500 SDValue Chain = Op.getOperand(0);
11501 SDValue DstPtr = Op.getOperand(1);
11502 SDValue SrcPtr = Op.getOperand(2);
11503 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11504 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11507 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11508 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11510 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11513 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11514 // amount is a constant. Takes immediate version of shift as input.
11515 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11516 SDValue SrcOp, uint64_t ShiftAmt,
11517 SelectionDAG &DAG) {
11518 MVT ElementType = VT.getVectorElementType();
11520 // Check for ShiftAmt >= element width
11521 if (ShiftAmt >= ElementType.getSizeInBits()) {
11522 if (Opc == X86ISD::VSRAI)
11523 ShiftAmt = ElementType.getSizeInBits() - 1;
11525 return DAG.getConstant(0, VT);
11528 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11529 && "Unknown target vector shift-by-constant node");
11531 // Fold this packed vector shift into a build vector if SrcOp is a
11532 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11533 if (VT == SrcOp.getSimpleValueType() &&
11534 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11535 SmallVector<SDValue, 8> Elts;
11536 unsigned NumElts = SrcOp->getNumOperands();
11537 ConstantSDNode *ND;
11540 default: llvm_unreachable(0);
11541 case X86ISD::VSHLI:
11542 for (unsigned i=0; i!=NumElts; ++i) {
11543 SDValue CurrentOp = SrcOp->getOperand(i);
11544 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11545 Elts.push_back(CurrentOp);
11548 ND = cast<ConstantSDNode>(CurrentOp);
11549 const APInt &C = ND->getAPIntValue();
11550 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11553 case X86ISD::VSRLI:
11554 for (unsigned i=0; i!=NumElts; ++i) {
11555 SDValue CurrentOp = SrcOp->getOperand(i);
11556 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11557 Elts.push_back(CurrentOp);
11560 ND = cast<ConstantSDNode>(CurrentOp);
11561 const APInt &C = ND->getAPIntValue();
11562 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11565 case X86ISD::VSRAI:
11566 for (unsigned i=0; i!=NumElts; ++i) {
11567 SDValue CurrentOp = SrcOp->getOperand(i);
11568 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11569 Elts.push_back(CurrentOp);
11572 ND = cast<ConstantSDNode>(CurrentOp);
11573 const APInt &C = ND->getAPIntValue();
11574 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11579 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11582 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11585 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11586 // may or may not be a constant. Takes immediate version of shift as input.
11587 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11588 SDValue SrcOp, SDValue ShAmt,
11589 SelectionDAG &DAG) {
11590 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11592 // Catch shift-by-constant.
11593 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11594 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11595 CShAmt->getZExtValue(), DAG);
11597 // Change opcode to non-immediate version
11599 default: llvm_unreachable("Unknown target vector shift node");
11600 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11601 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11602 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11605 // Need to build a vector containing shift amount
11606 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11609 ShOps[1] = DAG.getConstant(0, MVT::i32);
11610 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11611 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11613 // The return type has to be a 128-bit type with the same element
11614 // type as the input type.
11615 MVT EltVT = VT.getVectorElementType();
11616 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11618 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11619 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11622 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11624 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11626 default: return SDValue(); // Don't custom lower most intrinsics.
11627 // Comparison intrinsics.
11628 case Intrinsic::x86_sse_comieq_ss:
11629 case Intrinsic::x86_sse_comilt_ss:
11630 case Intrinsic::x86_sse_comile_ss:
11631 case Intrinsic::x86_sse_comigt_ss:
11632 case Intrinsic::x86_sse_comige_ss:
11633 case Intrinsic::x86_sse_comineq_ss:
11634 case Intrinsic::x86_sse_ucomieq_ss:
11635 case Intrinsic::x86_sse_ucomilt_ss:
11636 case Intrinsic::x86_sse_ucomile_ss:
11637 case Intrinsic::x86_sse_ucomigt_ss:
11638 case Intrinsic::x86_sse_ucomige_ss:
11639 case Intrinsic::x86_sse_ucomineq_ss:
11640 case Intrinsic::x86_sse2_comieq_sd:
11641 case Intrinsic::x86_sse2_comilt_sd:
11642 case Intrinsic::x86_sse2_comile_sd:
11643 case Intrinsic::x86_sse2_comigt_sd:
11644 case Intrinsic::x86_sse2_comige_sd:
11645 case Intrinsic::x86_sse2_comineq_sd:
11646 case Intrinsic::x86_sse2_ucomieq_sd:
11647 case Intrinsic::x86_sse2_ucomilt_sd:
11648 case Intrinsic::x86_sse2_ucomile_sd:
11649 case Intrinsic::x86_sse2_ucomigt_sd:
11650 case Intrinsic::x86_sse2_ucomige_sd:
11651 case Intrinsic::x86_sse2_ucomineq_sd: {
11655 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11656 case Intrinsic::x86_sse_comieq_ss:
11657 case Intrinsic::x86_sse2_comieq_sd:
11658 Opc = X86ISD::COMI;
11661 case Intrinsic::x86_sse_comilt_ss:
11662 case Intrinsic::x86_sse2_comilt_sd:
11663 Opc = X86ISD::COMI;
11666 case Intrinsic::x86_sse_comile_ss:
11667 case Intrinsic::x86_sse2_comile_sd:
11668 Opc = X86ISD::COMI;
11671 case Intrinsic::x86_sse_comigt_ss:
11672 case Intrinsic::x86_sse2_comigt_sd:
11673 Opc = X86ISD::COMI;
11676 case Intrinsic::x86_sse_comige_ss:
11677 case Intrinsic::x86_sse2_comige_sd:
11678 Opc = X86ISD::COMI;
11681 case Intrinsic::x86_sse_comineq_ss:
11682 case Intrinsic::x86_sse2_comineq_sd:
11683 Opc = X86ISD::COMI;
11686 case Intrinsic::x86_sse_ucomieq_ss:
11687 case Intrinsic::x86_sse2_ucomieq_sd:
11688 Opc = X86ISD::UCOMI;
11691 case Intrinsic::x86_sse_ucomilt_ss:
11692 case Intrinsic::x86_sse2_ucomilt_sd:
11693 Opc = X86ISD::UCOMI;
11696 case Intrinsic::x86_sse_ucomile_ss:
11697 case Intrinsic::x86_sse2_ucomile_sd:
11698 Opc = X86ISD::UCOMI;
11701 case Intrinsic::x86_sse_ucomigt_ss:
11702 case Intrinsic::x86_sse2_ucomigt_sd:
11703 Opc = X86ISD::UCOMI;
11706 case Intrinsic::x86_sse_ucomige_ss:
11707 case Intrinsic::x86_sse2_ucomige_sd:
11708 Opc = X86ISD::UCOMI;
11711 case Intrinsic::x86_sse_ucomineq_ss:
11712 case Intrinsic::x86_sse2_ucomineq_sd:
11713 Opc = X86ISD::UCOMI;
11718 SDValue LHS = Op.getOperand(1);
11719 SDValue RHS = Op.getOperand(2);
11720 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11721 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11722 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11723 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11724 DAG.getConstant(X86CC, MVT::i8), Cond);
11725 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11728 // Arithmetic intrinsics.
11729 case Intrinsic::x86_sse2_pmulu_dq:
11730 case Intrinsic::x86_avx2_pmulu_dq:
11731 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11732 Op.getOperand(1), Op.getOperand(2));
11734 case Intrinsic::x86_sse41_pmuldq:
11735 case Intrinsic::x86_avx2_pmul_dq:
11736 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11737 Op.getOperand(1), Op.getOperand(2));
11739 case Intrinsic::x86_sse2_pmulhu_w:
11740 case Intrinsic::x86_avx2_pmulhu_w:
11741 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11742 Op.getOperand(1), Op.getOperand(2));
11744 case Intrinsic::x86_sse2_pmulh_w:
11745 case Intrinsic::x86_avx2_pmulh_w:
11746 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11747 Op.getOperand(1), Op.getOperand(2));
11749 // SSE2/AVX2 sub with unsigned saturation intrinsics
11750 case Intrinsic::x86_sse2_psubus_b:
11751 case Intrinsic::x86_sse2_psubus_w:
11752 case Intrinsic::x86_avx2_psubus_b:
11753 case Intrinsic::x86_avx2_psubus_w:
11754 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11755 Op.getOperand(1), Op.getOperand(2));
11757 // SSE3/AVX horizontal add/sub intrinsics
11758 case Intrinsic::x86_sse3_hadd_ps:
11759 case Intrinsic::x86_sse3_hadd_pd:
11760 case Intrinsic::x86_avx_hadd_ps_256:
11761 case Intrinsic::x86_avx_hadd_pd_256:
11762 case Intrinsic::x86_sse3_hsub_ps:
11763 case Intrinsic::x86_sse3_hsub_pd:
11764 case Intrinsic::x86_avx_hsub_ps_256:
11765 case Intrinsic::x86_avx_hsub_pd_256:
11766 case Intrinsic::x86_ssse3_phadd_w_128:
11767 case Intrinsic::x86_ssse3_phadd_d_128:
11768 case Intrinsic::x86_avx2_phadd_w:
11769 case Intrinsic::x86_avx2_phadd_d:
11770 case Intrinsic::x86_ssse3_phsub_w_128:
11771 case Intrinsic::x86_ssse3_phsub_d_128:
11772 case Intrinsic::x86_avx2_phsub_w:
11773 case Intrinsic::x86_avx2_phsub_d: {
11776 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11777 case Intrinsic::x86_sse3_hadd_ps:
11778 case Intrinsic::x86_sse3_hadd_pd:
11779 case Intrinsic::x86_avx_hadd_ps_256:
11780 case Intrinsic::x86_avx_hadd_pd_256:
11781 Opcode = X86ISD::FHADD;
11783 case Intrinsic::x86_sse3_hsub_ps:
11784 case Intrinsic::x86_sse3_hsub_pd:
11785 case Intrinsic::x86_avx_hsub_ps_256:
11786 case Intrinsic::x86_avx_hsub_pd_256:
11787 Opcode = X86ISD::FHSUB;
11789 case Intrinsic::x86_ssse3_phadd_w_128:
11790 case Intrinsic::x86_ssse3_phadd_d_128:
11791 case Intrinsic::x86_avx2_phadd_w:
11792 case Intrinsic::x86_avx2_phadd_d:
11793 Opcode = X86ISD::HADD;
11795 case Intrinsic::x86_ssse3_phsub_w_128:
11796 case Intrinsic::x86_ssse3_phsub_d_128:
11797 case Intrinsic::x86_avx2_phsub_w:
11798 case Intrinsic::x86_avx2_phsub_d:
11799 Opcode = X86ISD::HSUB;
11802 return DAG.getNode(Opcode, dl, Op.getValueType(),
11803 Op.getOperand(1), Op.getOperand(2));
11806 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11807 case Intrinsic::x86_sse2_pmaxu_b:
11808 case Intrinsic::x86_sse41_pmaxuw:
11809 case Intrinsic::x86_sse41_pmaxud:
11810 case Intrinsic::x86_avx2_pmaxu_b:
11811 case Intrinsic::x86_avx2_pmaxu_w:
11812 case Intrinsic::x86_avx2_pmaxu_d:
11813 case Intrinsic::x86_sse2_pminu_b:
11814 case Intrinsic::x86_sse41_pminuw:
11815 case Intrinsic::x86_sse41_pminud:
11816 case Intrinsic::x86_avx2_pminu_b:
11817 case Intrinsic::x86_avx2_pminu_w:
11818 case Intrinsic::x86_avx2_pminu_d:
11819 case Intrinsic::x86_sse41_pmaxsb:
11820 case Intrinsic::x86_sse2_pmaxs_w:
11821 case Intrinsic::x86_sse41_pmaxsd:
11822 case Intrinsic::x86_avx2_pmaxs_b:
11823 case Intrinsic::x86_avx2_pmaxs_w:
11824 case Intrinsic::x86_avx2_pmaxs_d:
11825 case Intrinsic::x86_sse41_pminsb:
11826 case Intrinsic::x86_sse2_pmins_w:
11827 case Intrinsic::x86_sse41_pminsd:
11828 case Intrinsic::x86_avx2_pmins_b:
11829 case Intrinsic::x86_avx2_pmins_w:
11830 case Intrinsic::x86_avx2_pmins_d: {
11833 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11834 case Intrinsic::x86_sse2_pmaxu_b:
11835 case Intrinsic::x86_sse41_pmaxuw:
11836 case Intrinsic::x86_sse41_pmaxud:
11837 case Intrinsic::x86_avx2_pmaxu_b:
11838 case Intrinsic::x86_avx2_pmaxu_w:
11839 case Intrinsic::x86_avx2_pmaxu_d:
11840 Opcode = X86ISD::UMAX;
11842 case Intrinsic::x86_sse2_pminu_b:
11843 case Intrinsic::x86_sse41_pminuw:
11844 case Intrinsic::x86_sse41_pminud:
11845 case Intrinsic::x86_avx2_pminu_b:
11846 case Intrinsic::x86_avx2_pminu_w:
11847 case Intrinsic::x86_avx2_pminu_d:
11848 Opcode = X86ISD::UMIN;
11850 case Intrinsic::x86_sse41_pmaxsb:
11851 case Intrinsic::x86_sse2_pmaxs_w:
11852 case Intrinsic::x86_sse41_pmaxsd:
11853 case Intrinsic::x86_avx2_pmaxs_b:
11854 case Intrinsic::x86_avx2_pmaxs_w:
11855 case Intrinsic::x86_avx2_pmaxs_d:
11856 Opcode = X86ISD::SMAX;
11858 case Intrinsic::x86_sse41_pminsb:
11859 case Intrinsic::x86_sse2_pmins_w:
11860 case Intrinsic::x86_sse41_pminsd:
11861 case Intrinsic::x86_avx2_pmins_b:
11862 case Intrinsic::x86_avx2_pmins_w:
11863 case Intrinsic::x86_avx2_pmins_d:
11864 Opcode = X86ISD::SMIN;
11867 return DAG.getNode(Opcode, dl, Op.getValueType(),
11868 Op.getOperand(1), Op.getOperand(2));
11871 // SSE/SSE2/AVX floating point max/min intrinsics.
11872 case Intrinsic::x86_sse_max_ps:
11873 case Intrinsic::x86_sse2_max_pd:
11874 case Intrinsic::x86_avx_max_ps_256:
11875 case Intrinsic::x86_avx_max_pd_256:
11876 case Intrinsic::x86_sse_min_ps:
11877 case Intrinsic::x86_sse2_min_pd:
11878 case Intrinsic::x86_avx_min_ps_256:
11879 case Intrinsic::x86_avx_min_pd_256: {
11882 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11883 case Intrinsic::x86_sse_max_ps:
11884 case Intrinsic::x86_sse2_max_pd:
11885 case Intrinsic::x86_avx_max_ps_256:
11886 case Intrinsic::x86_avx_max_pd_256:
11887 Opcode = X86ISD::FMAX;
11889 case Intrinsic::x86_sse_min_ps:
11890 case Intrinsic::x86_sse2_min_pd:
11891 case Intrinsic::x86_avx_min_ps_256:
11892 case Intrinsic::x86_avx_min_pd_256:
11893 Opcode = X86ISD::FMIN;
11896 return DAG.getNode(Opcode, dl, Op.getValueType(),
11897 Op.getOperand(1), Op.getOperand(2));
11900 // AVX2 variable shift intrinsics
11901 case Intrinsic::x86_avx2_psllv_d:
11902 case Intrinsic::x86_avx2_psllv_q:
11903 case Intrinsic::x86_avx2_psllv_d_256:
11904 case Intrinsic::x86_avx2_psllv_q_256:
11905 case Intrinsic::x86_avx2_psrlv_d:
11906 case Intrinsic::x86_avx2_psrlv_q:
11907 case Intrinsic::x86_avx2_psrlv_d_256:
11908 case Intrinsic::x86_avx2_psrlv_q_256:
11909 case Intrinsic::x86_avx2_psrav_d:
11910 case Intrinsic::x86_avx2_psrav_d_256: {
11913 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11914 case Intrinsic::x86_avx2_psllv_d:
11915 case Intrinsic::x86_avx2_psllv_q:
11916 case Intrinsic::x86_avx2_psllv_d_256:
11917 case Intrinsic::x86_avx2_psllv_q_256:
11920 case Intrinsic::x86_avx2_psrlv_d:
11921 case Intrinsic::x86_avx2_psrlv_q:
11922 case Intrinsic::x86_avx2_psrlv_d_256:
11923 case Intrinsic::x86_avx2_psrlv_q_256:
11926 case Intrinsic::x86_avx2_psrav_d:
11927 case Intrinsic::x86_avx2_psrav_d_256:
11931 return DAG.getNode(Opcode, dl, Op.getValueType(),
11932 Op.getOperand(1), Op.getOperand(2));
11935 case Intrinsic::x86_ssse3_pshuf_b_128:
11936 case Intrinsic::x86_avx2_pshuf_b:
11937 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11938 Op.getOperand(1), Op.getOperand(2));
11940 case Intrinsic::x86_ssse3_psign_b_128:
11941 case Intrinsic::x86_ssse3_psign_w_128:
11942 case Intrinsic::x86_ssse3_psign_d_128:
11943 case Intrinsic::x86_avx2_psign_b:
11944 case Intrinsic::x86_avx2_psign_w:
11945 case Intrinsic::x86_avx2_psign_d:
11946 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11947 Op.getOperand(1), Op.getOperand(2));
11949 case Intrinsic::x86_sse41_insertps:
11950 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11951 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11953 case Intrinsic::x86_avx_vperm2f128_ps_256:
11954 case Intrinsic::x86_avx_vperm2f128_pd_256:
11955 case Intrinsic::x86_avx_vperm2f128_si_256:
11956 case Intrinsic::x86_avx2_vperm2i128:
11957 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11958 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11960 case Intrinsic::x86_avx2_permd:
11961 case Intrinsic::x86_avx2_permps:
11962 // Operands intentionally swapped. Mask is last operand to intrinsic,
11963 // but second operand for node/instruction.
11964 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11965 Op.getOperand(2), Op.getOperand(1));
11967 case Intrinsic::x86_sse_sqrt_ps:
11968 case Intrinsic::x86_sse2_sqrt_pd:
11969 case Intrinsic::x86_avx_sqrt_ps_256:
11970 case Intrinsic::x86_avx_sqrt_pd_256:
11971 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11973 // ptest and testp intrinsics. The intrinsic these come from are designed to
11974 // return an integer value, not just an instruction so lower it to the ptest
11975 // or testp pattern and a setcc for the result.
11976 case Intrinsic::x86_sse41_ptestz:
11977 case Intrinsic::x86_sse41_ptestc:
11978 case Intrinsic::x86_sse41_ptestnzc:
11979 case Intrinsic::x86_avx_ptestz_256:
11980 case Intrinsic::x86_avx_ptestc_256:
11981 case Intrinsic::x86_avx_ptestnzc_256:
11982 case Intrinsic::x86_avx_vtestz_ps:
11983 case Intrinsic::x86_avx_vtestc_ps:
11984 case Intrinsic::x86_avx_vtestnzc_ps:
11985 case Intrinsic::x86_avx_vtestz_pd:
11986 case Intrinsic::x86_avx_vtestc_pd:
11987 case Intrinsic::x86_avx_vtestnzc_pd:
11988 case Intrinsic::x86_avx_vtestz_ps_256:
11989 case Intrinsic::x86_avx_vtestc_ps_256:
11990 case Intrinsic::x86_avx_vtestnzc_ps_256:
11991 case Intrinsic::x86_avx_vtestz_pd_256:
11992 case Intrinsic::x86_avx_vtestc_pd_256:
11993 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11994 bool IsTestPacked = false;
11997 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11998 case Intrinsic::x86_avx_vtestz_ps:
11999 case Intrinsic::x86_avx_vtestz_pd:
12000 case Intrinsic::x86_avx_vtestz_ps_256:
12001 case Intrinsic::x86_avx_vtestz_pd_256:
12002 IsTestPacked = true; // Fallthrough
12003 case Intrinsic::x86_sse41_ptestz:
12004 case Intrinsic::x86_avx_ptestz_256:
12006 X86CC = X86::COND_E;
12008 case Intrinsic::x86_avx_vtestc_ps:
12009 case Intrinsic::x86_avx_vtestc_pd:
12010 case Intrinsic::x86_avx_vtestc_ps_256:
12011 case Intrinsic::x86_avx_vtestc_pd_256:
12012 IsTestPacked = true; // Fallthrough
12013 case Intrinsic::x86_sse41_ptestc:
12014 case Intrinsic::x86_avx_ptestc_256:
12016 X86CC = X86::COND_B;
12018 case Intrinsic::x86_avx_vtestnzc_ps:
12019 case Intrinsic::x86_avx_vtestnzc_pd:
12020 case Intrinsic::x86_avx_vtestnzc_ps_256:
12021 case Intrinsic::x86_avx_vtestnzc_pd_256:
12022 IsTestPacked = true; // Fallthrough
12023 case Intrinsic::x86_sse41_ptestnzc:
12024 case Intrinsic::x86_avx_ptestnzc_256:
12026 X86CC = X86::COND_A;
12030 SDValue LHS = Op.getOperand(1);
12031 SDValue RHS = Op.getOperand(2);
12032 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12033 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12034 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12035 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12036 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12038 case Intrinsic::x86_avx512_kortestz_w:
12039 case Intrinsic::x86_avx512_kortestc_w: {
12040 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12041 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12042 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12043 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12044 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12045 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12046 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12049 // SSE/AVX shift intrinsics
12050 case Intrinsic::x86_sse2_psll_w:
12051 case Intrinsic::x86_sse2_psll_d:
12052 case Intrinsic::x86_sse2_psll_q:
12053 case Intrinsic::x86_avx2_psll_w:
12054 case Intrinsic::x86_avx2_psll_d:
12055 case Intrinsic::x86_avx2_psll_q:
12056 case Intrinsic::x86_sse2_psrl_w:
12057 case Intrinsic::x86_sse2_psrl_d:
12058 case Intrinsic::x86_sse2_psrl_q:
12059 case Intrinsic::x86_avx2_psrl_w:
12060 case Intrinsic::x86_avx2_psrl_d:
12061 case Intrinsic::x86_avx2_psrl_q:
12062 case Intrinsic::x86_sse2_psra_w:
12063 case Intrinsic::x86_sse2_psra_d:
12064 case Intrinsic::x86_avx2_psra_w:
12065 case Intrinsic::x86_avx2_psra_d: {
12068 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12069 case Intrinsic::x86_sse2_psll_w:
12070 case Intrinsic::x86_sse2_psll_d:
12071 case Intrinsic::x86_sse2_psll_q:
12072 case Intrinsic::x86_avx2_psll_w:
12073 case Intrinsic::x86_avx2_psll_d:
12074 case Intrinsic::x86_avx2_psll_q:
12075 Opcode = X86ISD::VSHL;
12077 case Intrinsic::x86_sse2_psrl_w:
12078 case Intrinsic::x86_sse2_psrl_d:
12079 case Intrinsic::x86_sse2_psrl_q:
12080 case Intrinsic::x86_avx2_psrl_w:
12081 case Intrinsic::x86_avx2_psrl_d:
12082 case Intrinsic::x86_avx2_psrl_q:
12083 Opcode = X86ISD::VSRL;
12085 case Intrinsic::x86_sse2_psra_w:
12086 case Intrinsic::x86_sse2_psra_d:
12087 case Intrinsic::x86_avx2_psra_w:
12088 case Intrinsic::x86_avx2_psra_d:
12089 Opcode = X86ISD::VSRA;
12092 return DAG.getNode(Opcode, dl, Op.getValueType(),
12093 Op.getOperand(1), Op.getOperand(2));
12096 // SSE/AVX immediate shift intrinsics
12097 case Intrinsic::x86_sse2_pslli_w:
12098 case Intrinsic::x86_sse2_pslli_d:
12099 case Intrinsic::x86_sse2_pslli_q:
12100 case Intrinsic::x86_avx2_pslli_w:
12101 case Intrinsic::x86_avx2_pslli_d:
12102 case Intrinsic::x86_avx2_pslli_q:
12103 case Intrinsic::x86_sse2_psrli_w:
12104 case Intrinsic::x86_sse2_psrli_d:
12105 case Intrinsic::x86_sse2_psrli_q:
12106 case Intrinsic::x86_avx2_psrli_w:
12107 case Intrinsic::x86_avx2_psrli_d:
12108 case Intrinsic::x86_avx2_psrli_q:
12109 case Intrinsic::x86_sse2_psrai_w:
12110 case Intrinsic::x86_sse2_psrai_d:
12111 case Intrinsic::x86_avx2_psrai_w:
12112 case Intrinsic::x86_avx2_psrai_d: {
12115 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12116 case Intrinsic::x86_sse2_pslli_w:
12117 case Intrinsic::x86_sse2_pslli_d:
12118 case Intrinsic::x86_sse2_pslli_q:
12119 case Intrinsic::x86_avx2_pslli_w:
12120 case Intrinsic::x86_avx2_pslli_d:
12121 case Intrinsic::x86_avx2_pslli_q:
12122 Opcode = X86ISD::VSHLI;
12124 case Intrinsic::x86_sse2_psrli_w:
12125 case Intrinsic::x86_sse2_psrli_d:
12126 case Intrinsic::x86_sse2_psrli_q:
12127 case Intrinsic::x86_avx2_psrli_w:
12128 case Intrinsic::x86_avx2_psrli_d:
12129 case Intrinsic::x86_avx2_psrli_q:
12130 Opcode = X86ISD::VSRLI;
12132 case Intrinsic::x86_sse2_psrai_w:
12133 case Intrinsic::x86_sse2_psrai_d:
12134 case Intrinsic::x86_avx2_psrai_w:
12135 case Intrinsic::x86_avx2_psrai_d:
12136 Opcode = X86ISD::VSRAI;
12139 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12140 Op.getOperand(1), Op.getOperand(2), DAG);
12143 case Intrinsic::x86_sse42_pcmpistria128:
12144 case Intrinsic::x86_sse42_pcmpestria128:
12145 case Intrinsic::x86_sse42_pcmpistric128:
12146 case Intrinsic::x86_sse42_pcmpestric128:
12147 case Intrinsic::x86_sse42_pcmpistrio128:
12148 case Intrinsic::x86_sse42_pcmpestrio128:
12149 case Intrinsic::x86_sse42_pcmpistris128:
12150 case Intrinsic::x86_sse42_pcmpestris128:
12151 case Intrinsic::x86_sse42_pcmpistriz128:
12152 case Intrinsic::x86_sse42_pcmpestriz128: {
12156 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12157 case Intrinsic::x86_sse42_pcmpistria128:
12158 Opcode = X86ISD::PCMPISTRI;
12159 X86CC = X86::COND_A;
12161 case Intrinsic::x86_sse42_pcmpestria128:
12162 Opcode = X86ISD::PCMPESTRI;
12163 X86CC = X86::COND_A;
12165 case Intrinsic::x86_sse42_pcmpistric128:
12166 Opcode = X86ISD::PCMPISTRI;
12167 X86CC = X86::COND_B;
12169 case Intrinsic::x86_sse42_pcmpestric128:
12170 Opcode = X86ISD::PCMPESTRI;
12171 X86CC = X86::COND_B;
12173 case Intrinsic::x86_sse42_pcmpistrio128:
12174 Opcode = X86ISD::PCMPISTRI;
12175 X86CC = X86::COND_O;
12177 case Intrinsic::x86_sse42_pcmpestrio128:
12178 Opcode = X86ISD::PCMPESTRI;
12179 X86CC = X86::COND_O;
12181 case Intrinsic::x86_sse42_pcmpistris128:
12182 Opcode = X86ISD::PCMPISTRI;
12183 X86CC = X86::COND_S;
12185 case Intrinsic::x86_sse42_pcmpestris128:
12186 Opcode = X86ISD::PCMPESTRI;
12187 X86CC = X86::COND_S;
12189 case Intrinsic::x86_sse42_pcmpistriz128:
12190 Opcode = X86ISD::PCMPISTRI;
12191 X86CC = X86::COND_E;
12193 case Intrinsic::x86_sse42_pcmpestriz128:
12194 Opcode = X86ISD::PCMPESTRI;
12195 X86CC = X86::COND_E;
12198 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12199 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12200 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12201 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12202 DAG.getConstant(X86CC, MVT::i8),
12203 SDValue(PCMP.getNode(), 1));
12204 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12207 case Intrinsic::x86_sse42_pcmpistri128:
12208 case Intrinsic::x86_sse42_pcmpestri128: {
12210 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12211 Opcode = X86ISD::PCMPISTRI;
12213 Opcode = X86ISD::PCMPESTRI;
12215 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12216 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12217 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12219 case Intrinsic::x86_fma_vfmadd_ps:
12220 case Intrinsic::x86_fma_vfmadd_pd:
12221 case Intrinsic::x86_fma_vfmsub_ps:
12222 case Intrinsic::x86_fma_vfmsub_pd:
12223 case Intrinsic::x86_fma_vfnmadd_ps:
12224 case Intrinsic::x86_fma_vfnmadd_pd:
12225 case Intrinsic::x86_fma_vfnmsub_ps:
12226 case Intrinsic::x86_fma_vfnmsub_pd:
12227 case Intrinsic::x86_fma_vfmaddsub_ps:
12228 case Intrinsic::x86_fma_vfmaddsub_pd:
12229 case Intrinsic::x86_fma_vfmsubadd_ps:
12230 case Intrinsic::x86_fma_vfmsubadd_pd:
12231 case Intrinsic::x86_fma_vfmadd_ps_256:
12232 case Intrinsic::x86_fma_vfmadd_pd_256:
12233 case Intrinsic::x86_fma_vfmsub_ps_256:
12234 case Intrinsic::x86_fma_vfmsub_pd_256:
12235 case Intrinsic::x86_fma_vfnmadd_ps_256:
12236 case Intrinsic::x86_fma_vfnmadd_pd_256:
12237 case Intrinsic::x86_fma_vfnmsub_ps_256:
12238 case Intrinsic::x86_fma_vfnmsub_pd_256:
12239 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12240 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12241 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12242 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12243 case Intrinsic::x86_fma_vfmadd_ps_512:
12244 case Intrinsic::x86_fma_vfmadd_pd_512:
12245 case Intrinsic::x86_fma_vfmsub_ps_512:
12246 case Intrinsic::x86_fma_vfmsub_pd_512:
12247 case Intrinsic::x86_fma_vfnmadd_ps_512:
12248 case Intrinsic::x86_fma_vfnmadd_pd_512:
12249 case Intrinsic::x86_fma_vfnmsub_ps_512:
12250 case Intrinsic::x86_fma_vfnmsub_pd_512:
12251 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12252 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12253 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12254 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12257 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12258 case Intrinsic::x86_fma_vfmadd_ps:
12259 case Intrinsic::x86_fma_vfmadd_pd:
12260 case Intrinsic::x86_fma_vfmadd_ps_256:
12261 case Intrinsic::x86_fma_vfmadd_pd_256:
12262 case Intrinsic::x86_fma_vfmadd_ps_512:
12263 case Intrinsic::x86_fma_vfmadd_pd_512:
12264 Opc = X86ISD::FMADD;
12266 case Intrinsic::x86_fma_vfmsub_ps:
12267 case Intrinsic::x86_fma_vfmsub_pd:
12268 case Intrinsic::x86_fma_vfmsub_ps_256:
12269 case Intrinsic::x86_fma_vfmsub_pd_256:
12270 case Intrinsic::x86_fma_vfmsub_ps_512:
12271 case Intrinsic::x86_fma_vfmsub_pd_512:
12272 Opc = X86ISD::FMSUB;
12274 case Intrinsic::x86_fma_vfnmadd_ps:
12275 case Intrinsic::x86_fma_vfnmadd_pd:
12276 case Intrinsic::x86_fma_vfnmadd_ps_256:
12277 case Intrinsic::x86_fma_vfnmadd_pd_256:
12278 case Intrinsic::x86_fma_vfnmadd_ps_512:
12279 case Intrinsic::x86_fma_vfnmadd_pd_512:
12280 Opc = X86ISD::FNMADD;
12282 case Intrinsic::x86_fma_vfnmsub_ps:
12283 case Intrinsic::x86_fma_vfnmsub_pd:
12284 case Intrinsic::x86_fma_vfnmsub_ps_256:
12285 case Intrinsic::x86_fma_vfnmsub_pd_256:
12286 case Intrinsic::x86_fma_vfnmsub_ps_512:
12287 case Intrinsic::x86_fma_vfnmsub_pd_512:
12288 Opc = X86ISD::FNMSUB;
12290 case Intrinsic::x86_fma_vfmaddsub_ps:
12291 case Intrinsic::x86_fma_vfmaddsub_pd:
12292 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12293 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12294 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12295 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12296 Opc = X86ISD::FMADDSUB;
12298 case Intrinsic::x86_fma_vfmsubadd_ps:
12299 case Intrinsic::x86_fma_vfmsubadd_pd:
12300 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12301 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12302 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12303 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12304 Opc = X86ISD::FMSUBADD;
12308 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12309 Op.getOperand(2), Op.getOperand(3));
12314 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12315 SDValue Base, SDValue Index,
12316 SDValue ScaleOp, SDValue Chain,
12317 const X86Subtarget * Subtarget) {
12319 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12320 assert(C && "Invalid scale type");
12321 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12322 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12323 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12324 Index.getSimpleValueType().getVectorNumElements());
12325 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12326 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12327 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12328 SDValue Segment = DAG.getRegister(0, MVT::i32);
12329 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12330 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12331 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12332 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12335 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12336 SDValue Src, SDValue Mask, SDValue Base,
12337 SDValue Index, SDValue ScaleOp, SDValue Chain,
12338 const X86Subtarget * Subtarget) {
12340 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12341 assert(C && "Invalid scale type");
12342 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12343 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12344 Index.getSimpleValueType().getVectorNumElements());
12345 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12346 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12347 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12348 SDValue Segment = DAG.getRegister(0, MVT::i32);
12349 if (Src.getOpcode() == ISD::UNDEF)
12350 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12351 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12352 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12353 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12354 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12357 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12358 SDValue Src, SDValue Base, SDValue Index,
12359 SDValue ScaleOp, SDValue Chain) {
12361 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12362 assert(C && "Invalid scale type");
12363 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12364 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12365 SDValue Segment = DAG.getRegister(0, MVT::i32);
12366 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12367 Index.getSimpleValueType().getVectorNumElements());
12368 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12369 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12370 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12371 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12372 return SDValue(Res, 1);
12375 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12376 SDValue Src, SDValue Mask, SDValue Base,
12377 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12379 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12380 assert(C && "Invalid scale type");
12381 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12382 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12383 SDValue Segment = DAG.getRegister(0, MVT::i32);
12384 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12385 Index.getSimpleValueType().getVectorNumElements());
12386 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12387 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12388 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12389 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12390 return SDValue(Res, 1);
12393 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12394 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12395 // also used to custom lower READCYCLECOUNTER nodes.
12396 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12397 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12398 SmallVectorImpl<SDValue> &Results) {
12399 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12400 SDValue TheChain = N->getOperand(0);
12401 SDValue rd = DAG.getNode(Opcode, DL, Tys, &TheChain, 1);
12404 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12405 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12406 // and the EAX register is loaded with the low-order 32 bits.
12407 if (Subtarget->is64Bit()) {
12408 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12409 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12412 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12413 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12416 SDValue Chain = HI.getValue(1);
12418 if (Opcode == X86ISD::RDTSCP_DAG) {
12419 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12421 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12422 // the ECX register. Add 'ecx' explicitly to the chain.
12423 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12425 // Explicitly store the content of ECX at the location passed in input
12426 // to the 'rdtscp' intrinsic.
12427 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12428 MachinePointerInfo(), false, false, 0);
12431 if (Subtarget->is64Bit()) {
12432 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12433 // the EAX register is loaded with the low-order 32 bits.
12434 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12435 DAG.getConstant(32, MVT::i8));
12436 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12437 Results.push_back(Chain);
12441 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12442 SDValue Ops[] = { LO, HI };
12443 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops,
12444 array_lengthof(Ops));
12445 Results.push_back(Pair);
12446 Results.push_back(Chain);
12449 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12450 SelectionDAG &DAG) {
12451 SmallVector<SDValue, 2> Results;
12453 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12455 return DAG.getMergeValues(&Results[0], Results.size(), DL);
12458 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12459 SelectionDAG &DAG) {
12461 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12463 default: return SDValue(); // Don't custom lower most intrinsics.
12465 // RDRAND/RDSEED intrinsics.
12466 case Intrinsic::x86_rdrand_16:
12467 case Intrinsic::x86_rdrand_32:
12468 case Intrinsic::x86_rdrand_64:
12469 case Intrinsic::x86_rdseed_16:
12470 case Intrinsic::x86_rdseed_32:
12471 case Intrinsic::x86_rdseed_64: {
12472 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12473 IntNo == Intrinsic::x86_rdseed_32 ||
12474 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12476 // Emit the node with the right value type.
12477 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12478 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12480 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12481 // Otherwise return the value from Rand, which is always 0, casted to i32.
12482 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12483 DAG.getConstant(1, Op->getValueType(1)),
12484 DAG.getConstant(X86::COND_B, MVT::i32),
12485 SDValue(Result.getNode(), 1) };
12486 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12487 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12488 Ops, array_lengthof(Ops));
12490 // Return { result, isValid, chain }.
12491 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12492 SDValue(Result.getNode(), 2));
12494 //int_gather(index, base, scale);
12495 case Intrinsic::x86_avx512_gather_qpd_512:
12496 case Intrinsic::x86_avx512_gather_qps_512:
12497 case Intrinsic::x86_avx512_gather_dpd_512:
12498 case Intrinsic::x86_avx512_gather_qpi_512:
12499 case Intrinsic::x86_avx512_gather_qpq_512:
12500 case Intrinsic::x86_avx512_gather_dpq_512:
12501 case Intrinsic::x86_avx512_gather_dps_512:
12502 case Intrinsic::x86_avx512_gather_dpi_512: {
12505 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12506 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12507 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12508 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12509 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12510 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12511 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12512 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12513 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12515 SDValue Chain = Op.getOperand(0);
12516 SDValue Index = Op.getOperand(2);
12517 SDValue Base = Op.getOperand(3);
12518 SDValue Scale = Op.getOperand(4);
12519 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12521 //int_gather_mask(v1, mask, index, base, scale);
12522 case Intrinsic::x86_avx512_gather_qps_mask_512:
12523 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12524 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12525 case Intrinsic::x86_avx512_gather_dps_mask_512:
12526 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12527 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12528 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12529 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12532 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12533 case Intrinsic::x86_avx512_gather_qps_mask_512:
12534 Opc = X86::VGATHERQPSZrm; break;
12535 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12536 Opc = X86::VGATHERQPDZrm; break;
12537 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12538 Opc = X86::VGATHERDPDZrm; break;
12539 case Intrinsic::x86_avx512_gather_dps_mask_512:
12540 Opc = X86::VGATHERDPSZrm; break;
12541 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12542 Opc = X86::VPGATHERQDZrm; break;
12543 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12544 Opc = X86::VPGATHERQQZrm; break;
12545 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12546 Opc = X86::VPGATHERDDZrm; break;
12547 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12548 Opc = X86::VPGATHERDQZrm; break;
12550 SDValue Chain = Op.getOperand(0);
12551 SDValue Src = Op.getOperand(2);
12552 SDValue Mask = Op.getOperand(3);
12553 SDValue Index = Op.getOperand(4);
12554 SDValue Base = Op.getOperand(5);
12555 SDValue Scale = Op.getOperand(6);
12556 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12559 //int_scatter(base, index, v1, scale);
12560 case Intrinsic::x86_avx512_scatter_qpd_512:
12561 case Intrinsic::x86_avx512_scatter_qps_512:
12562 case Intrinsic::x86_avx512_scatter_dpd_512:
12563 case Intrinsic::x86_avx512_scatter_qpi_512:
12564 case Intrinsic::x86_avx512_scatter_qpq_512:
12565 case Intrinsic::x86_avx512_scatter_dpq_512:
12566 case Intrinsic::x86_avx512_scatter_dps_512:
12567 case Intrinsic::x86_avx512_scatter_dpi_512: {
12570 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12571 case Intrinsic::x86_avx512_scatter_qpd_512:
12572 Opc = X86::VSCATTERQPDZmr; break;
12573 case Intrinsic::x86_avx512_scatter_qps_512:
12574 Opc = X86::VSCATTERQPSZmr; break;
12575 case Intrinsic::x86_avx512_scatter_dpd_512:
12576 Opc = X86::VSCATTERDPDZmr; break;
12577 case Intrinsic::x86_avx512_scatter_dps_512:
12578 Opc = X86::VSCATTERDPSZmr; break;
12579 case Intrinsic::x86_avx512_scatter_qpi_512:
12580 Opc = X86::VPSCATTERQDZmr; break;
12581 case Intrinsic::x86_avx512_scatter_qpq_512:
12582 Opc = X86::VPSCATTERQQZmr; break;
12583 case Intrinsic::x86_avx512_scatter_dpq_512:
12584 Opc = X86::VPSCATTERDQZmr; break;
12585 case Intrinsic::x86_avx512_scatter_dpi_512:
12586 Opc = X86::VPSCATTERDDZmr; break;
12588 SDValue Chain = Op.getOperand(0);
12589 SDValue Base = Op.getOperand(2);
12590 SDValue Index = Op.getOperand(3);
12591 SDValue Src = Op.getOperand(4);
12592 SDValue Scale = Op.getOperand(5);
12593 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12595 //int_scatter_mask(base, mask, index, v1, scale);
12596 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12597 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12598 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12599 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12600 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12601 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12602 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12603 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12606 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12607 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12608 Opc = X86::VSCATTERQPDZmr; break;
12609 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12610 Opc = X86::VSCATTERQPSZmr; break;
12611 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12612 Opc = X86::VSCATTERDPDZmr; break;
12613 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12614 Opc = X86::VSCATTERDPSZmr; break;
12615 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12616 Opc = X86::VPSCATTERQDZmr; break;
12617 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12618 Opc = X86::VPSCATTERQQZmr; break;
12619 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12620 Opc = X86::VPSCATTERDQZmr; break;
12621 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12622 Opc = X86::VPSCATTERDDZmr; break;
12624 SDValue Chain = Op.getOperand(0);
12625 SDValue Base = Op.getOperand(2);
12626 SDValue Mask = Op.getOperand(3);
12627 SDValue Index = Op.getOperand(4);
12628 SDValue Src = Op.getOperand(5);
12629 SDValue Scale = Op.getOperand(6);
12630 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12632 // Read Time Stamp Counter (RDTSC).
12633 case Intrinsic::x86_rdtsc:
12634 // Read Time Stamp Counter and Processor ID (RDTSCP).
12635 case Intrinsic::x86_rdtscp: {
12638 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12639 case Intrinsic::x86_rdtsc:
12640 Opc = X86ISD::RDTSC_DAG; break;
12641 case Intrinsic::x86_rdtscp:
12642 Opc = X86ISD::RDTSCP_DAG; break;
12644 SmallVector<SDValue, 2> Results;
12645 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12646 return DAG.getMergeValues(&Results[0], Results.size(), dl);
12648 // XTEST intrinsics.
12649 case Intrinsic::x86_xtest: {
12650 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12651 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12652 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12653 DAG.getConstant(X86::COND_NE, MVT::i8),
12655 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12656 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12657 Ret, SDValue(InTrans.getNode(), 1));
12662 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12663 SelectionDAG &DAG) const {
12664 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12665 MFI->setReturnAddressIsTaken(true);
12667 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12670 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12672 EVT PtrVT = getPointerTy();
12675 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12676 const X86RegisterInfo *RegInfo =
12677 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12678 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12679 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12680 DAG.getNode(ISD::ADD, dl, PtrVT,
12681 FrameAddr, Offset),
12682 MachinePointerInfo(), false, false, false, 0);
12685 // Just load the return address.
12686 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12687 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12688 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12691 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12692 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12693 MFI->setFrameAddressIsTaken(true);
12695 EVT VT = Op.getValueType();
12696 SDLoc dl(Op); // FIXME probably not meaningful
12697 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12698 const X86RegisterInfo *RegInfo =
12699 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12700 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12701 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12702 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12703 "Invalid Frame Register!");
12704 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12706 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12707 MachinePointerInfo(),
12708 false, false, false, 0);
12712 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12713 SelectionDAG &DAG) const {
12714 const X86RegisterInfo *RegInfo =
12715 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12716 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12719 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12720 SDValue Chain = Op.getOperand(0);
12721 SDValue Offset = Op.getOperand(1);
12722 SDValue Handler = Op.getOperand(2);
12725 EVT PtrVT = getPointerTy();
12726 const X86RegisterInfo *RegInfo =
12727 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12728 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12729 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12730 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12731 "Invalid Frame Register!");
12732 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12733 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12735 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12736 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12737 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12738 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12740 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12742 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12743 DAG.getRegister(StoreAddrReg, PtrVT));
12746 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12747 SelectionDAG &DAG) const {
12749 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12750 DAG.getVTList(MVT::i32, MVT::Other),
12751 Op.getOperand(0), Op.getOperand(1));
12754 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12755 SelectionDAG &DAG) const {
12757 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12758 Op.getOperand(0), Op.getOperand(1));
12761 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12762 return Op.getOperand(0);
12765 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12766 SelectionDAG &DAG) const {
12767 SDValue Root = Op.getOperand(0);
12768 SDValue Trmp = Op.getOperand(1); // trampoline
12769 SDValue FPtr = Op.getOperand(2); // nested function
12770 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12773 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12774 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12776 if (Subtarget->is64Bit()) {
12777 SDValue OutChains[6];
12779 // Large code-model.
12780 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12781 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12783 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12784 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12786 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12788 // Load the pointer to the nested function into R11.
12789 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12790 SDValue Addr = Trmp;
12791 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12792 Addr, MachinePointerInfo(TrmpAddr),
12795 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12796 DAG.getConstant(2, MVT::i64));
12797 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12798 MachinePointerInfo(TrmpAddr, 2),
12801 // Load the 'nest' parameter value into R10.
12802 // R10 is specified in X86CallingConv.td
12803 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12804 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12805 DAG.getConstant(10, MVT::i64));
12806 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12807 Addr, MachinePointerInfo(TrmpAddr, 10),
12810 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12811 DAG.getConstant(12, MVT::i64));
12812 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12813 MachinePointerInfo(TrmpAddr, 12),
12816 // Jump to the nested function.
12817 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12818 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12819 DAG.getConstant(20, MVT::i64));
12820 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12821 Addr, MachinePointerInfo(TrmpAddr, 20),
12824 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12825 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12826 DAG.getConstant(22, MVT::i64));
12827 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12828 MachinePointerInfo(TrmpAddr, 22),
12831 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12833 const Function *Func =
12834 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12835 CallingConv::ID CC = Func->getCallingConv();
12840 llvm_unreachable("Unsupported calling convention");
12841 case CallingConv::C:
12842 case CallingConv::X86_StdCall: {
12843 // Pass 'nest' parameter in ECX.
12844 // Must be kept in sync with X86CallingConv.td
12845 NestReg = X86::ECX;
12847 // Check that ECX wasn't needed by an 'inreg' parameter.
12848 FunctionType *FTy = Func->getFunctionType();
12849 const AttributeSet &Attrs = Func->getAttributes();
12851 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12852 unsigned InRegCount = 0;
12855 for (FunctionType::param_iterator I = FTy->param_begin(),
12856 E = FTy->param_end(); I != E; ++I, ++Idx)
12857 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12858 // FIXME: should only count parameters that are lowered to integers.
12859 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12861 if (InRegCount > 2) {
12862 report_fatal_error("Nest register in use - reduce number of inreg"
12868 case CallingConv::X86_FastCall:
12869 case CallingConv::X86_ThisCall:
12870 case CallingConv::Fast:
12871 // Pass 'nest' parameter in EAX.
12872 // Must be kept in sync with X86CallingConv.td
12873 NestReg = X86::EAX;
12877 SDValue OutChains[4];
12878 SDValue Addr, Disp;
12880 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12881 DAG.getConstant(10, MVT::i32));
12882 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12884 // This is storing the opcode for MOV32ri.
12885 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12886 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12887 OutChains[0] = DAG.getStore(Root, dl,
12888 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12889 Trmp, MachinePointerInfo(TrmpAddr),
12892 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12893 DAG.getConstant(1, MVT::i32));
12894 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12895 MachinePointerInfo(TrmpAddr, 1),
12898 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12899 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12900 DAG.getConstant(5, MVT::i32));
12901 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12902 MachinePointerInfo(TrmpAddr, 5),
12905 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12906 DAG.getConstant(6, MVT::i32));
12907 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12908 MachinePointerInfo(TrmpAddr, 6),
12911 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12915 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12916 SelectionDAG &DAG) const {
12918 The rounding mode is in bits 11:10 of FPSR, and has the following
12920 00 Round to nearest
12925 FLT_ROUNDS, on the other hand, expects the following:
12932 To perform the conversion, we do:
12933 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12936 MachineFunction &MF = DAG.getMachineFunction();
12937 const TargetMachine &TM = MF.getTarget();
12938 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12939 unsigned StackAlignment = TFI.getStackAlignment();
12940 MVT VT = Op.getSimpleValueType();
12943 // Save FP Control Word to stack slot
12944 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12945 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12947 MachineMemOperand *MMO =
12948 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12949 MachineMemOperand::MOStore, 2, 2);
12951 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12952 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12953 DAG.getVTList(MVT::Other),
12954 Ops, array_lengthof(Ops), MVT::i16,
12957 // Load FP Control Word from stack slot
12958 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12959 MachinePointerInfo(), false, false, false, 0);
12961 // Transform as necessary
12963 DAG.getNode(ISD::SRL, DL, MVT::i16,
12964 DAG.getNode(ISD::AND, DL, MVT::i16,
12965 CWD, DAG.getConstant(0x800, MVT::i16)),
12966 DAG.getConstant(11, MVT::i8));
12968 DAG.getNode(ISD::SRL, DL, MVT::i16,
12969 DAG.getNode(ISD::AND, DL, MVT::i16,
12970 CWD, DAG.getConstant(0x400, MVT::i16)),
12971 DAG.getConstant(9, MVT::i8));
12974 DAG.getNode(ISD::AND, DL, MVT::i16,
12975 DAG.getNode(ISD::ADD, DL, MVT::i16,
12976 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12977 DAG.getConstant(1, MVT::i16)),
12978 DAG.getConstant(3, MVT::i16));
12980 return DAG.getNode((VT.getSizeInBits() < 16 ?
12981 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12984 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12985 MVT VT = Op.getSimpleValueType();
12987 unsigned NumBits = VT.getSizeInBits();
12990 Op = Op.getOperand(0);
12991 if (VT == MVT::i8) {
12992 // Zero extend to i32 since there is not an i8 bsr.
12994 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12997 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12998 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12999 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13001 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13004 DAG.getConstant(NumBits+NumBits-1, OpVT),
13005 DAG.getConstant(X86::COND_E, MVT::i8),
13008 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
13010 // Finally xor with NumBits-1.
13011 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13014 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13018 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13019 MVT VT = Op.getSimpleValueType();
13021 unsigned NumBits = VT.getSizeInBits();
13024 Op = Op.getOperand(0);
13025 if (VT == MVT::i8) {
13026 // Zero extend to i32 since there is not an i8 bsr.
13028 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13031 // Issue a bsr (scan bits in reverse).
13032 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13033 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13035 // And xor with NumBits-1.
13036 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13039 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13043 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13044 MVT VT = Op.getSimpleValueType();
13045 unsigned NumBits = VT.getSizeInBits();
13047 Op = Op.getOperand(0);
13049 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13050 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13051 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13053 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13056 DAG.getConstant(NumBits, VT),
13057 DAG.getConstant(X86::COND_E, MVT::i8),
13060 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
13063 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13064 // ones, and then concatenate the result back.
13065 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13066 MVT VT = Op.getSimpleValueType();
13068 assert(VT.is256BitVector() && VT.isInteger() &&
13069 "Unsupported value type for operation");
13071 unsigned NumElems = VT.getVectorNumElements();
13074 // Extract the LHS vectors
13075 SDValue LHS = Op.getOperand(0);
13076 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13077 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13079 // Extract the RHS vectors
13080 SDValue RHS = Op.getOperand(1);
13081 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13082 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13084 MVT EltVT = VT.getVectorElementType();
13085 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13087 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13088 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13089 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13092 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13093 assert(Op.getSimpleValueType().is256BitVector() &&
13094 Op.getSimpleValueType().isInteger() &&
13095 "Only handle AVX 256-bit vector integer operation");
13096 return Lower256IntArith(Op, DAG);
13099 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13100 assert(Op.getSimpleValueType().is256BitVector() &&
13101 Op.getSimpleValueType().isInteger() &&
13102 "Only handle AVX 256-bit vector integer operation");
13103 return Lower256IntArith(Op, DAG);
13106 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13107 SelectionDAG &DAG) {
13109 MVT VT = Op.getSimpleValueType();
13111 // Decompose 256-bit ops into smaller 128-bit ops.
13112 if (VT.is256BitVector() && !Subtarget->hasInt256())
13113 return Lower256IntArith(Op, DAG);
13115 SDValue A = Op.getOperand(0);
13116 SDValue B = Op.getOperand(1);
13118 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13119 if (VT == MVT::v4i32) {
13120 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13121 "Should not custom lower when pmuldq is available!");
13123 // Extract the odd parts.
13124 static const int UnpackMask[] = { 1, -1, 3, -1 };
13125 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13126 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13128 // Multiply the even parts.
13129 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13130 // Now multiply odd parts.
13131 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13133 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13134 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13136 // Merge the two vectors back together with a shuffle. This expands into 2
13138 static const int ShufMask[] = { 0, 4, 2, 6 };
13139 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13142 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13143 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13145 // Ahi = psrlqi(a, 32);
13146 // Bhi = psrlqi(b, 32);
13148 // AloBlo = pmuludq(a, b);
13149 // AloBhi = pmuludq(a, Bhi);
13150 // AhiBlo = pmuludq(Ahi, b);
13152 // AloBhi = psllqi(AloBhi, 32);
13153 // AhiBlo = psllqi(AhiBlo, 32);
13154 // return AloBlo + AloBhi + AhiBlo;
13156 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13157 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13159 // Bit cast to 32-bit vectors for MULUDQ
13160 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13161 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13162 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13163 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13164 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13165 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13167 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13168 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13169 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13171 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13172 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13174 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13175 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13178 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13179 SelectionDAG &DAG) {
13180 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13181 EVT VT = Op0.getValueType();
13184 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13185 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13187 // Get the high parts.
13188 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13189 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13190 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13192 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13194 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13196 Op->getOpcode() == ISD::UMUL_LOHI ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13197 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13198 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13199 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13200 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13202 // Shuffle it back into the right order.
13203 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13204 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13205 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13206 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13208 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13211 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13212 const X86Subtarget *Subtarget) {
13213 MVT VT = Op.getSimpleValueType();
13215 SDValue R = Op.getOperand(0);
13216 SDValue Amt = Op.getOperand(1);
13218 // Optimize shl/srl/sra with constant shift amount.
13219 if (isSplatVector(Amt.getNode())) {
13220 SDValue SclrAmt = Amt->getOperand(0);
13221 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13222 uint64_t ShiftAmt = C->getZExtValue();
13224 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13225 (Subtarget->hasInt256() &&
13226 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13227 (Subtarget->hasAVX512() &&
13228 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13229 if (Op.getOpcode() == ISD::SHL)
13230 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13232 if (Op.getOpcode() == ISD::SRL)
13233 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13235 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13236 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13240 if (VT == MVT::v16i8) {
13241 if (Op.getOpcode() == ISD::SHL) {
13242 // Make a large shift.
13243 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13244 MVT::v8i16, R, ShiftAmt,
13246 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13247 // Zero out the rightmost bits.
13248 SmallVector<SDValue, 16> V(16,
13249 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13251 return DAG.getNode(ISD::AND, dl, VT, SHL,
13252 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13254 if (Op.getOpcode() == ISD::SRL) {
13255 // Make a large shift.
13256 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13257 MVT::v8i16, R, ShiftAmt,
13259 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13260 // Zero out the leftmost bits.
13261 SmallVector<SDValue, 16> V(16,
13262 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13264 return DAG.getNode(ISD::AND, dl, VT, SRL,
13265 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13267 if (Op.getOpcode() == ISD::SRA) {
13268 if (ShiftAmt == 7) {
13269 // R s>> 7 === R s< 0
13270 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13271 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13274 // R s>> a === ((R u>> a) ^ m) - m
13275 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13276 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13278 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13279 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13280 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13283 llvm_unreachable("Unknown shift opcode.");
13286 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13287 if (Op.getOpcode() == ISD::SHL) {
13288 // Make a large shift.
13289 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13290 MVT::v16i16, R, ShiftAmt,
13292 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13293 // Zero out the rightmost bits.
13294 SmallVector<SDValue, 32> V(32,
13295 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13297 return DAG.getNode(ISD::AND, dl, VT, SHL,
13298 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13300 if (Op.getOpcode() == ISD::SRL) {
13301 // Make a large shift.
13302 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13303 MVT::v16i16, R, ShiftAmt,
13305 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13306 // Zero out the leftmost bits.
13307 SmallVector<SDValue, 32> V(32,
13308 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13310 return DAG.getNode(ISD::AND, dl, VT, SRL,
13311 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13313 if (Op.getOpcode() == ISD::SRA) {
13314 if (ShiftAmt == 7) {
13315 // R s>> 7 === R s< 0
13316 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13317 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13320 // R s>> a === ((R u>> a) ^ m) - m
13321 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13322 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13324 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13325 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13326 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13329 llvm_unreachable("Unknown shift opcode.");
13334 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13335 if (!Subtarget->is64Bit() &&
13336 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13337 Amt.getOpcode() == ISD::BITCAST &&
13338 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13339 Amt = Amt.getOperand(0);
13340 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13341 VT.getVectorNumElements();
13342 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13343 uint64_t ShiftAmt = 0;
13344 for (unsigned i = 0; i != Ratio; ++i) {
13345 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13349 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13351 // Check remaining shift amounts.
13352 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13353 uint64_t ShAmt = 0;
13354 for (unsigned j = 0; j != Ratio; ++j) {
13355 ConstantSDNode *C =
13356 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13360 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13362 if (ShAmt != ShiftAmt)
13365 switch (Op.getOpcode()) {
13367 llvm_unreachable("Unknown shift opcode!");
13369 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13372 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13375 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13383 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13384 const X86Subtarget* Subtarget) {
13385 MVT VT = Op.getSimpleValueType();
13387 SDValue R = Op.getOperand(0);
13388 SDValue Amt = Op.getOperand(1);
13390 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13391 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13392 (Subtarget->hasInt256() &&
13393 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13394 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13395 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13397 EVT EltVT = VT.getVectorElementType();
13399 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13400 unsigned NumElts = VT.getVectorNumElements();
13402 for (i = 0; i != NumElts; ++i) {
13403 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13407 for (j = i; j != NumElts; ++j) {
13408 SDValue Arg = Amt.getOperand(j);
13409 if (Arg.getOpcode() == ISD::UNDEF) continue;
13410 if (Arg != Amt.getOperand(i))
13413 if (i != NumElts && j == NumElts)
13414 BaseShAmt = Amt.getOperand(i);
13416 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13417 Amt = Amt.getOperand(0);
13418 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13419 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13420 SDValue InVec = Amt.getOperand(0);
13421 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13422 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13424 for (; i != NumElts; ++i) {
13425 SDValue Arg = InVec.getOperand(i);
13426 if (Arg.getOpcode() == ISD::UNDEF) continue;
13430 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13431 if (ConstantSDNode *C =
13432 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13433 unsigned SplatIdx =
13434 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13435 if (C->getZExtValue() == SplatIdx)
13436 BaseShAmt = InVec.getOperand(1);
13439 if (!BaseShAmt.getNode())
13440 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13441 DAG.getIntPtrConstant(0));
13445 if (BaseShAmt.getNode()) {
13446 if (EltVT.bitsGT(MVT::i32))
13447 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13448 else if (EltVT.bitsLT(MVT::i32))
13449 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13451 switch (Op.getOpcode()) {
13453 llvm_unreachable("Unknown shift opcode!");
13455 switch (VT.SimpleTy) {
13456 default: return SDValue();
13465 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13468 switch (VT.SimpleTy) {
13469 default: return SDValue();
13476 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13479 switch (VT.SimpleTy) {
13480 default: return SDValue();
13489 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13495 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13496 if (!Subtarget->is64Bit() &&
13497 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13498 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13499 Amt.getOpcode() == ISD::BITCAST &&
13500 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13501 Amt = Amt.getOperand(0);
13502 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13503 VT.getVectorNumElements();
13504 std::vector<SDValue> Vals(Ratio);
13505 for (unsigned i = 0; i != Ratio; ++i)
13506 Vals[i] = Amt.getOperand(i);
13507 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13508 for (unsigned j = 0; j != Ratio; ++j)
13509 if (Vals[j] != Amt.getOperand(i + j))
13512 switch (Op.getOpcode()) {
13514 llvm_unreachable("Unknown shift opcode!");
13516 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13518 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13520 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13527 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13528 SelectionDAG &DAG) {
13530 MVT VT = Op.getSimpleValueType();
13532 SDValue R = Op.getOperand(0);
13533 SDValue Amt = Op.getOperand(1);
13536 if (!Subtarget->hasSSE2())
13539 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13543 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13547 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13549 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13550 if (Subtarget->hasInt256()) {
13551 if (Op.getOpcode() == ISD::SRL &&
13552 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13553 VT == MVT::v4i64 || VT == MVT::v8i32))
13555 if (Op.getOpcode() == ISD::SHL &&
13556 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13557 VT == MVT::v4i64 || VT == MVT::v8i32))
13559 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13563 // If possible, lower this packed shift into a vector multiply instead of
13564 // expanding it into a sequence of scalar shifts.
13565 // Do this only if the vector shift count is a constant build_vector.
13566 if (Op.getOpcode() == ISD::SHL &&
13567 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13568 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13569 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13570 SmallVector<SDValue, 8> Elts;
13571 EVT SVT = VT.getScalarType();
13572 unsigned SVTBits = SVT.getSizeInBits();
13573 const APInt &One = APInt(SVTBits, 1);
13574 unsigned NumElems = VT.getVectorNumElements();
13576 for (unsigned i=0; i !=NumElems; ++i) {
13577 SDValue Op = Amt->getOperand(i);
13578 if (Op->getOpcode() == ISD::UNDEF) {
13579 Elts.push_back(Op);
13583 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13584 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13585 uint64_t ShAmt = C.getZExtValue();
13586 if (ShAmt >= SVTBits) {
13587 Elts.push_back(DAG.getUNDEF(SVT));
13590 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13592 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13593 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13596 // Lower SHL with variable shift amount.
13597 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13598 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13600 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13601 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13602 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13603 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13606 // If possible, lower this shift as a sequence of two shifts by
13607 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13609 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13611 // Could be rewritten as:
13612 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13614 // The advantage is that the two shifts from the example would be
13615 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13616 // the vector shift into four scalar shifts plus four pairs of vector
13618 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13619 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13620 unsigned TargetOpcode = X86ISD::MOVSS;
13621 bool CanBeSimplified;
13622 // The splat value for the first packed shift (the 'X' from the example).
13623 SDValue Amt1 = Amt->getOperand(0);
13624 // The splat value for the second packed shift (the 'Y' from the example).
13625 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13626 Amt->getOperand(2);
13628 // See if it is possible to replace this node with a sequence of
13629 // two shifts followed by a MOVSS/MOVSD
13630 if (VT == MVT::v4i32) {
13631 // Check if it is legal to use a MOVSS.
13632 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13633 Amt2 == Amt->getOperand(3);
13634 if (!CanBeSimplified) {
13635 // Otherwise, check if we can still simplify this node using a MOVSD.
13636 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13637 Amt->getOperand(2) == Amt->getOperand(3);
13638 TargetOpcode = X86ISD::MOVSD;
13639 Amt2 = Amt->getOperand(2);
13642 // Do similar checks for the case where the machine value type
13644 CanBeSimplified = Amt1 == Amt->getOperand(1);
13645 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13646 CanBeSimplified = Amt2 == Amt->getOperand(i);
13648 if (!CanBeSimplified) {
13649 TargetOpcode = X86ISD::MOVSD;
13650 CanBeSimplified = true;
13651 Amt2 = Amt->getOperand(4);
13652 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13653 CanBeSimplified = Amt1 == Amt->getOperand(i);
13654 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13655 CanBeSimplified = Amt2 == Amt->getOperand(j);
13659 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13660 isa<ConstantSDNode>(Amt2)) {
13661 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13662 EVT CastVT = MVT::v4i32;
13664 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13665 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13667 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13668 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13669 if (TargetOpcode == X86ISD::MOVSD)
13670 CastVT = MVT::v2i64;
13671 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13672 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13673 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13675 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13679 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13680 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13683 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13684 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13686 // Turn 'a' into a mask suitable for VSELECT
13687 SDValue VSelM = DAG.getConstant(0x80, VT);
13688 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13689 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13691 SDValue CM1 = DAG.getConstant(0x0f, VT);
13692 SDValue CM2 = DAG.getConstant(0x3f, VT);
13694 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13695 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13696 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13697 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13698 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13701 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13702 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13703 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13705 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13706 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13707 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13708 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13709 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13712 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13713 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13714 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13716 // return VSELECT(r, r+r, a);
13717 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13718 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13722 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13723 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13724 // solution better.
13725 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13726 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13728 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13729 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13730 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13731 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13732 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13735 // Decompose 256-bit shifts into smaller 128-bit shifts.
13736 if (VT.is256BitVector()) {
13737 unsigned NumElems = VT.getVectorNumElements();
13738 MVT EltVT = VT.getVectorElementType();
13739 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13741 // Extract the two vectors
13742 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13743 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13745 // Recreate the shift amount vectors
13746 SDValue Amt1, Amt2;
13747 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13748 // Constant shift amount
13749 SmallVector<SDValue, 4> Amt1Csts;
13750 SmallVector<SDValue, 4> Amt2Csts;
13751 for (unsigned i = 0; i != NumElems/2; ++i)
13752 Amt1Csts.push_back(Amt->getOperand(i));
13753 for (unsigned i = NumElems/2; i != NumElems; ++i)
13754 Amt2Csts.push_back(Amt->getOperand(i));
13756 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13757 &Amt1Csts[0], NumElems/2);
13758 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13759 &Amt2Csts[0], NumElems/2);
13761 // Variable shift amount
13762 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13763 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13766 // Issue new vector shifts for the smaller types
13767 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13768 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13770 // Concatenate the result back
13771 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13777 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13778 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13779 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13780 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13781 // has only one use.
13782 SDNode *N = Op.getNode();
13783 SDValue LHS = N->getOperand(0);
13784 SDValue RHS = N->getOperand(1);
13785 unsigned BaseOp = 0;
13788 switch (Op.getOpcode()) {
13789 default: llvm_unreachable("Unknown ovf instruction!");
13791 // A subtract of one will be selected as a INC. Note that INC doesn't
13792 // set CF, so we can't do this for UADDO.
13793 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13795 BaseOp = X86ISD::INC;
13796 Cond = X86::COND_O;
13799 BaseOp = X86ISD::ADD;
13800 Cond = X86::COND_O;
13803 BaseOp = X86ISD::ADD;
13804 Cond = X86::COND_B;
13807 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13808 // set CF, so we can't do this for USUBO.
13809 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13811 BaseOp = X86ISD::DEC;
13812 Cond = X86::COND_O;
13815 BaseOp = X86ISD::SUB;
13816 Cond = X86::COND_O;
13819 BaseOp = X86ISD::SUB;
13820 Cond = X86::COND_B;
13823 BaseOp = X86ISD::SMUL;
13824 Cond = X86::COND_O;
13826 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13827 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13829 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13832 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13833 DAG.getConstant(X86::COND_O, MVT::i32),
13834 SDValue(Sum.getNode(), 2));
13836 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13840 // Also sets EFLAGS.
13841 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13842 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13845 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13846 DAG.getConstant(Cond, MVT::i32),
13847 SDValue(Sum.getNode(), 1));
13849 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13852 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13853 SelectionDAG &DAG) const {
13855 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13856 MVT VT = Op.getSimpleValueType();
13858 if (!Subtarget->hasSSE2() || !VT.isVector())
13861 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13862 ExtraVT.getScalarType().getSizeInBits();
13864 switch (VT.SimpleTy) {
13865 default: return SDValue();
13868 if (!Subtarget->hasFp256())
13870 if (!Subtarget->hasInt256()) {
13871 // needs to be split
13872 unsigned NumElems = VT.getVectorNumElements();
13874 // Extract the LHS vectors
13875 SDValue LHS = Op.getOperand(0);
13876 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13877 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13879 MVT EltVT = VT.getVectorElementType();
13880 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13882 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13883 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13884 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13886 SDValue Extra = DAG.getValueType(ExtraVT);
13888 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13889 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13891 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13896 SDValue Op0 = Op.getOperand(0);
13897 SDValue Op00 = Op0.getOperand(0);
13899 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13900 if (Op0.getOpcode() == ISD::BITCAST &&
13901 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13902 // (sext (vzext x)) -> (vsext x)
13903 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13904 if (Tmp1.getNode()) {
13905 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13906 // This folding is only valid when the in-reg type is a vector of i8,
13908 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13909 ExtraEltVT == MVT::i32) {
13910 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13911 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13912 "This optimization is invalid without a VZEXT.");
13913 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13919 // If the above didn't work, then just use Shift-Left + Shift-Right.
13920 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13922 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13928 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13929 SelectionDAG &DAG) {
13931 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13932 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13933 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13934 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13936 // The only fence that needs an instruction is a sequentially-consistent
13937 // cross-thread fence.
13938 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13939 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13940 // no-sse2). There isn't any reason to disable it if the target processor
13942 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13943 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13945 SDValue Chain = Op.getOperand(0);
13946 SDValue Zero = DAG.getConstant(0, MVT::i32);
13948 DAG.getRegister(X86::ESP, MVT::i32), // Base
13949 DAG.getTargetConstant(1, MVT::i8), // Scale
13950 DAG.getRegister(0, MVT::i32), // Index
13951 DAG.getTargetConstant(0, MVT::i32), // Disp
13952 DAG.getRegister(0, MVT::i32), // Segment.
13956 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13957 return SDValue(Res, 0);
13960 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13961 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13964 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13965 SelectionDAG &DAG) {
13966 MVT T = Op.getSimpleValueType();
13970 switch(T.SimpleTy) {
13971 default: llvm_unreachable("Invalid value type!");
13972 case MVT::i8: Reg = X86::AL; size = 1; break;
13973 case MVT::i16: Reg = X86::AX; size = 2; break;
13974 case MVT::i32: Reg = X86::EAX; size = 4; break;
13976 assert(Subtarget->is64Bit() && "Node not type legal!");
13977 Reg = X86::RAX; size = 8;
13980 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13981 Op.getOperand(2), SDValue());
13982 SDValue Ops[] = { cpIn.getValue(0),
13985 DAG.getTargetConstant(size, MVT::i8),
13986 cpIn.getValue(1) };
13987 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13988 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13989 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13990 Ops, array_lengthof(Ops), T, MMO);
13992 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13996 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13997 SelectionDAG &DAG) {
13998 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13999 MVT DstVT = Op.getSimpleValueType();
14000 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14001 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14002 assert((DstVT == MVT::i64 ||
14003 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14004 "Unexpected custom BITCAST");
14005 // i64 <=> MMX conversions are Legal.
14006 if (SrcVT==MVT::i64 && DstVT.isVector())
14008 if (DstVT==MVT::i64 && SrcVT.isVector())
14010 // MMX <=> MMX conversions are Legal.
14011 if (SrcVT.isVector() && DstVT.isVector())
14013 // All other conversions need to be expanded.
14017 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14018 SDNode *Node = Op.getNode();
14020 EVT T = Node->getValueType(0);
14021 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14022 DAG.getConstant(0, T), Node->getOperand(2));
14023 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14024 cast<AtomicSDNode>(Node)->getMemoryVT(),
14025 Node->getOperand(0),
14026 Node->getOperand(1), negOp,
14027 cast<AtomicSDNode>(Node)->getMemOperand(),
14028 cast<AtomicSDNode>(Node)->getOrdering(),
14029 cast<AtomicSDNode>(Node)->getSynchScope());
14032 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14033 SDNode *Node = Op.getNode();
14035 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14037 // Convert seq_cst store -> xchg
14038 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14039 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14040 // (The only way to get a 16-byte store is cmpxchg16b)
14041 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14042 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14043 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14044 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14045 cast<AtomicSDNode>(Node)->getMemoryVT(),
14046 Node->getOperand(0),
14047 Node->getOperand(1), Node->getOperand(2),
14048 cast<AtomicSDNode>(Node)->getMemOperand(),
14049 cast<AtomicSDNode>(Node)->getOrdering(),
14050 cast<AtomicSDNode>(Node)->getSynchScope());
14051 return Swap.getValue(1);
14053 // Other atomic stores have a simple pattern.
14057 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14058 EVT VT = Op.getNode()->getSimpleValueType(0);
14060 // Let legalize expand this if it isn't a legal type yet.
14061 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14064 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14067 bool ExtraOp = false;
14068 switch (Op.getOpcode()) {
14069 default: llvm_unreachable("Invalid code");
14070 case ISD::ADDC: Opc = X86ISD::ADD; break;
14071 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14072 case ISD::SUBC: Opc = X86ISD::SUB; break;
14073 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14077 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14079 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14080 Op.getOperand(1), Op.getOperand(2));
14083 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14084 SelectionDAG &DAG) {
14085 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14087 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14088 // which returns the values as { float, float } (in XMM0) or
14089 // { double, double } (which is returned in XMM0, XMM1).
14091 SDValue Arg = Op.getOperand(0);
14092 EVT ArgVT = Arg.getValueType();
14093 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14095 TargetLowering::ArgListTy Args;
14096 TargetLowering::ArgListEntry Entry;
14100 Entry.isSExt = false;
14101 Entry.isZExt = false;
14102 Args.push_back(Entry);
14104 bool isF64 = ArgVT == MVT::f64;
14105 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14106 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14107 // the results are returned via SRet in memory.
14108 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14109 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14110 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14112 Type *RetTy = isF64
14113 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14114 : (Type*)VectorType::get(ArgTy, 4);
14116 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14117 false, false, false, false, 0,
14118 CallingConv::C, /*isTaillCall=*/false,
14119 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14120 Callee, Args, DAG, dl);
14121 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14124 // Returned in xmm0 and xmm1.
14125 return CallResult.first;
14127 // Returned in bits 0:31 and 32:64 xmm0.
14128 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14129 CallResult.first, DAG.getIntPtrConstant(0));
14130 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14131 CallResult.first, DAG.getIntPtrConstant(1));
14132 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14133 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14136 /// LowerOperation - Provide custom lowering hooks for some operations.
14138 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14139 switch (Op.getOpcode()) {
14140 default: llvm_unreachable("Should not custom lower this!");
14141 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14142 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14143 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14144 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14145 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14146 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14147 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14148 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14149 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14150 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14151 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14152 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14153 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14154 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14155 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14156 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14157 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14158 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14159 case ISD::SHL_PARTS:
14160 case ISD::SRA_PARTS:
14161 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14162 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14163 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14164 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14165 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14166 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14167 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14168 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14169 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14170 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14171 case ISD::FABS: return LowerFABS(Op, DAG);
14172 case ISD::FNEG: return LowerFNEG(Op, DAG);
14173 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14174 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14175 case ISD::SETCC: return LowerSETCC(Op, DAG);
14176 case ISD::SELECT: return LowerSELECT(Op, DAG);
14177 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14178 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14179 case ISD::VASTART: return LowerVASTART(Op, DAG);
14180 case ISD::VAARG: return LowerVAARG(Op, DAG);
14181 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14182 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14183 case ISD::INTRINSIC_VOID:
14184 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14185 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14186 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14187 case ISD::FRAME_TO_ARGS_OFFSET:
14188 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14189 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14190 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14191 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14192 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14193 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14194 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14195 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14196 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14197 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14198 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14199 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14200 case ISD::UMUL_LOHI:
14201 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14204 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14210 case ISD::UMULO: return LowerXALUO(Op, DAG);
14211 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14212 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14216 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14217 case ISD::ADD: return LowerADD(Op, DAG);
14218 case ISD::SUB: return LowerSUB(Op, DAG);
14219 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14223 static void ReplaceATOMIC_LOAD(SDNode *Node,
14224 SmallVectorImpl<SDValue> &Results,
14225 SelectionDAG &DAG) {
14227 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14229 // Convert wide load -> cmpxchg8b/cmpxchg16b
14230 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14231 // (The only way to get a 16-byte load is cmpxchg16b)
14232 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14233 SDValue Zero = DAG.getConstant(0, VT);
14234 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14235 Node->getOperand(0),
14236 Node->getOperand(1), Zero, Zero,
14237 cast<AtomicSDNode>(Node)->getMemOperand(),
14238 cast<AtomicSDNode>(Node)->getOrdering(),
14239 cast<AtomicSDNode>(Node)->getOrdering(),
14240 cast<AtomicSDNode>(Node)->getSynchScope());
14241 Results.push_back(Swap.getValue(0));
14242 Results.push_back(Swap.getValue(1));
14246 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14247 SelectionDAG &DAG, unsigned NewOp) {
14249 assert (Node->getValueType(0) == MVT::i64 &&
14250 "Only know how to expand i64 atomics");
14252 SDValue Chain = Node->getOperand(0);
14253 SDValue In1 = Node->getOperand(1);
14254 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14255 Node->getOperand(2), DAG.getIntPtrConstant(0));
14256 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14257 Node->getOperand(2), DAG.getIntPtrConstant(1));
14258 SDValue Ops[] = { Chain, In1, In2L, In2H };
14259 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14261 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14262 cast<MemSDNode>(Node)->getMemOperand());
14263 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14264 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
14265 Results.push_back(Result.getValue(2));
14268 /// ReplaceNodeResults - Replace a node with an illegal result type
14269 /// with a new node built out of custom code.
14270 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14271 SmallVectorImpl<SDValue>&Results,
14272 SelectionDAG &DAG) const {
14274 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14275 switch (N->getOpcode()) {
14277 llvm_unreachable("Do not know how to custom type legalize this operation!");
14278 case ISD::SIGN_EXTEND_INREG:
14283 // We don't want to expand or promote these.
14285 case ISD::FP_TO_SINT:
14286 case ISD::FP_TO_UINT: {
14287 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14289 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14292 std::pair<SDValue,SDValue> Vals =
14293 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14294 SDValue FIST = Vals.first, StackSlot = Vals.second;
14295 if (FIST.getNode()) {
14296 EVT VT = N->getValueType(0);
14297 // Return a load from the stack slot.
14298 if (StackSlot.getNode())
14299 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14300 MachinePointerInfo(),
14301 false, false, false, 0));
14303 Results.push_back(FIST);
14307 case ISD::UINT_TO_FP: {
14308 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14309 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14310 N->getValueType(0) != MVT::v2f32)
14312 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14314 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14316 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14317 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14318 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14319 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14320 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14321 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14324 case ISD::FP_ROUND: {
14325 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14327 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14328 Results.push_back(V);
14331 case ISD::INTRINSIC_W_CHAIN: {
14332 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14334 default : llvm_unreachable("Do not know how to custom type "
14335 "legalize this intrinsic operation!");
14336 case Intrinsic::x86_rdtsc:
14337 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14339 case Intrinsic::x86_rdtscp:
14340 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14344 case ISD::READCYCLECOUNTER: {
14345 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14348 case ISD::ATOMIC_CMP_SWAP: {
14349 EVT T = N->getValueType(0);
14350 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14351 bool Regs64bit = T == MVT::i128;
14352 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14353 SDValue cpInL, cpInH;
14354 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14355 DAG.getConstant(0, HalfT));
14356 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14357 DAG.getConstant(1, HalfT));
14358 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14359 Regs64bit ? X86::RAX : X86::EAX,
14361 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14362 Regs64bit ? X86::RDX : X86::EDX,
14363 cpInH, cpInL.getValue(1));
14364 SDValue swapInL, swapInH;
14365 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14366 DAG.getConstant(0, HalfT));
14367 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14368 DAG.getConstant(1, HalfT));
14369 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14370 Regs64bit ? X86::RBX : X86::EBX,
14371 swapInL, cpInH.getValue(1));
14372 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14373 Regs64bit ? X86::RCX : X86::ECX,
14374 swapInH, swapInL.getValue(1));
14375 SDValue Ops[] = { swapInH.getValue(0),
14377 swapInH.getValue(1) };
14378 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14379 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14380 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14381 X86ISD::LCMPXCHG8_DAG;
14382 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14383 Ops, array_lengthof(Ops), T, MMO);
14384 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14385 Regs64bit ? X86::RAX : X86::EAX,
14386 HalfT, Result.getValue(1));
14387 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14388 Regs64bit ? X86::RDX : X86::EDX,
14389 HalfT, cpOutL.getValue(2));
14390 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14391 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14392 Results.push_back(cpOutH.getValue(1));
14395 case ISD::ATOMIC_LOAD_ADD:
14396 case ISD::ATOMIC_LOAD_AND:
14397 case ISD::ATOMIC_LOAD_NAND:
14398 case ISD::ATOMIC_LOAD_OR:
14399 case ISD::ATOMIC_LOAD_SUB:
14400 case ISD::ATOMIC_LOAD_XOR:
14401 case ISD::ATOMIC_LOAD_MAX:
14402 case ISD::ATOMIC_LOAD_MIN:
14403 case ISD::ATOMIC_LOAD_UMAX:
14404 case ISD::ATOMIC_LOAD_UMIN:
14405 case ISD::ATOMIC_SWAP: {
14407 switch (N->getOpcode()) {
14408 default: llvm_unreachable("Unexpected opcode");
14409 case ISD::ATOMIC_LOAD_ADD:
14410 Opc = X86ISD::ATOMADD64_DAG;
14412 case ISD::ATOMIC_LOAD_AND:
14413 Opc = X86ISD::ATOMAND64_DAG;
14415 case ISD::ATOMIC_LOAD_NAND:
14416 Opc = X86ISD::ATOMNAND64_DAG;
14418 case ISD::ATOMIC_LOAD_OR:
14419 Opc = X86ISD::ATOMOR64_DAG;
14421 case ISD::ATOMIC_LOAD_SUB:
14422 Opc = X86ISD::ATOMSUB64_DAG;
14424 case ISD::ATOMIC_LOAD_XOR:
14425 Opc = X86ISD::ATOMXOR64_DAG;
14427 case ISD::ATOMIC_LOAD_MAX:
14428 Opc = X86ISD::ATOMMAX64_DAG;
14430 case ISD::ATOMIC_LOAD_MIN:
14431 Opc = X86ISD::ATOMMIN64_DAG;
14433 case ISD::ATOMIC_LOAD_UMAX:
14434 Opc = X86ISD::ATOMUMAX64_DAG;
14436 case ISD::ATOMIC_LOAD_UMIN:
14437 Opc = X86ISD::ATOMUMIN64_DAG;
14439 case ISD::ATOMIC_SWAP:
14440 Opc = X86ISD::ATOMSWAP64_DAG;
14443 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14446 case ISD::ATOMIC_LOAD:
14447 ReplaceATOMIC_LOAD(N, Results, DAG);
14451 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14453 default: return nullptr;
14454 case X86ISD::BSF: return "X86ISD::BSF";
14455 case X86ISD::BSR: return "X86ISD::BSR";
14456 case X86ISD::SHLD: return "X86ISD::SHLD";
14457 case X86ISD::SHRD: return "X86ISD::SHRD";
14458 case X86ISD::FAND: return "X86ISD::FAND";
14459 case X86ISD::FANDN: return "X86ISD::FANDN";
14460 case X86ISD::FOR: return "X86ISD::FOR";
14461 case X86ISD::FXOR: return "X86ISD::FXOR";
14462 case X86ISD::FSRL: return "X86ISD::FSRL";
14463 case X86ISD::FILD: return "X86ISD::FILD";
14464 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14465 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14466 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14467 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14468 case X86ISD::FLD: return "X86ISD::FLD";
14469 case X86ISD::FST: return "X86ISD::FST";
14470 case X86ISD::CALL: return "X86ISD::CALL";
14471 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14472 case X86ISD::BT: return "X86ISD::BT";
14473 case X86ISD::CMP: return "X86ISD::CMP";
14474 case X86ISD::COMI: return "X86ISD::COMI";
14475 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14476 case X86ISD::CMPM: return "X86ISD::CMPM";
14477 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14478 case X86ISD::SETCC: return "X86ISD::SETCC";
14479 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14480 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14481 case X86ISD::CMOV: return "X86ISD::CMOV";
14482 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14483 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14484 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14485 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14486 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14487 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14488 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14489 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14490 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14491 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14492 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14493 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14494 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14495 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14496 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14497 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14498 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14499 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14500 case X86ISD::HADD: return "X86ISD::HADD";
14501 case X86ISD::HSUB: return "X86ISD::HSUB";
14502 case X86ISD::FHADD: return "X86ISD::FHADD";
14503 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14504 case X86ISD::UMAX: return "X86ISD::UMAX";
14505 case X86ISD::UMIN: return "X86ISD::UMIN";
14506 case X86ISD::SMAX: return "X86ISD::SMAX";
14507 case X86ISD::SMIN: return "X86ISD::SMIN";
14508 case X86ISD::FMAX: return "X86ISD::FMAX";
14509 case X86ISD::FMIN: return "X86ISD::FMIN";
14510 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14511 case X86ISD::FMINC: return "X86ISD::FMINC";
14512 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14513 case X86ISD::FRCP: return "X86ISD::FRCP";
14514 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14515 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14516 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14517 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14518 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14519 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14520 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14521 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14522 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14523 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14524 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14525 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14526 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14527 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14528 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14529 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14530 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14531 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14532 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14533 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14534 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14535 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14536 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14537 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14538 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14539 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14540 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14541 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14542 case X86ISD::VSHL: return "X86ISD::VSHL";
14543 case X86ISD::VSRL: return "X86ISD::VSRL";
14544 case X86ISD::VSRA: return "X86ISD::VSRA";
14545 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14546 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14547 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14548 case X86ISD::CMPP: return "X86ISD::CMPP";
14549 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14550 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14551 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14552 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14553 case X86ISD::ADD: return "X86ISD::ADD";
14554 case X86ISD::SUB: return "X86ISD::SUB";
14555 case X86ISD::ADC: return "X86ISD::ADC";
14556 case X86ISD::SBB: return "X86ISD::SBB";
14557 case X86ISD::SMUL: return "X86ISD::SMUL";
14558 case X86ISD::UMUL: return "X86ISD::UMUL";
14559 case X86ISD::INC: return "X86ISD::INC";
14560 case X86ISD::DEC: return "X86ISD::DEC";
14561 case X86ISD::OR: return "X86ISD::OR";
14562 case X86ISD::XOR: return "X86ISD::XOR";
14563 case X86ISD::AND: return "X86ISD::AND";
14564 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14565 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14566 case X86ISD::PTEST: return "X86ISD::PTEST";
14567 case X86ISD::TESTP: return "X86ISD::TESTP";
14568 case X86ISD::TESTM: return "X86ISD::TESTM";
14569 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14570 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14571 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14572 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14573 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14574 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14575 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14576 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14577 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14578 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14579 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14580 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14581 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14582 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14583 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14584 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14585 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14586 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14587 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14588 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14589 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14590 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14591 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14592 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14593 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14594 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14595 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14596 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14597 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14598 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14599 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14600 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14601 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14602 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14603 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14604 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14605 case X86ISD::SAHF: return "X86ISD::SAHF";
14606 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14607 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14608 case X86ISD::FMADD: return "X86ISD::FMADD";
14609 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14610 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14611 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14612 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14613 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14614 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14615 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14616 case X86ISD::XTEST: return "X86ISD::XTEST";
14620 // isLegalAddressingMode - Return true if the addressing mode represented
14621 // by AM is legal for this target, for a load/store of the specified type.
14622 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14624 // X86 supports extremely general addressing modes.
14625 CodeModel::Model M = getTargetMachine().getCodeModel();
14626 Reloc::Model R = getTargetMachine().getRelocationModel();
14628 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14629 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14634 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14636 // If a reference to this global requires an extra load, we can't fold it.
14637 if (isGlobalStubReference(GVFlags))
14640 // If BaseGV requires a register for the PIC base, we cannot also have a
14641 // BaseReg specified.
14642 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14645 // If lower 4G is not available, then we must use rip-relative addressing.
14646 if ((M != CodeModel::Small || R != Reloc::Static) &&
14647 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14651 switch (AM.Scale) {
14657 // These scales always work.
14662 // These scales are formed with basereg+scalereg. Only accept if there is
14667 default: // Other stuff never works.
14674 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14675 unsigned Bits = Ty->getScalarSizeInBits();
14677 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14678 // particularly cheaper than those without.
14682 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14683 // variable shifts just as cheap as scalar ones.
14684 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14687 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14688 // fully general vector.
14692 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14693 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14695 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14696 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14697 return NumBits1 > NumBits2;
14700 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14701 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14704 if (!isTypeLegal(EVT::getEVT(Ty1)))
14707 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14709 // Assuming the caller doesn't have a zeroext or signext return parameter,
14710 // truncation all the way down to i1 is valid.
14714 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14715 return isInt<32>(Imm);
14718 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14719 // Can also use sub to handle negated immediates.
14720 return isInt<32>(Imm);
14723 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14724 if (!VT1.isInteger() || !VT2.isInteger())
14726 unsigned NumBits1 = VT1.getSizeInBits();
14727 unsigned NumBits2 = VT2.getSizeInBits();
14728 return NumBits1 > NumBits2;
14731 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14732 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14733 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14736 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14737 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14738 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14741 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14742 EVT VT1 = Val.getValueType();
14743 if (isZExtFree(VT1, VT2))
14746 if (Val.getOpcode() != ISD::LOAD)
14749 if (!VT1.isSimple() || !VT1.isInteger() ||
14750 !VT2.isSimple() || !VT2.isInteger())
14753 switch (VT1.getSimpleVT().SimpleTy) {
14758 // X86 has 8, 16, and 32-bit zero-extending loads.
14766 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14767 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14770 VT = VT.getScalarType();
14772 if (!VT.isSimple())
14775 switch (VT.getSimpleVT().SimpleTy) {
14786 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14787 // i16 instructions are longer (0x66 prefix) and potentially slower.
14788 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14791 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14792 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14793 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14794 /// are assumed to be legal.
14796 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14798 if (!VT.isSimple())
14801 MVT SVT = VT.getSimpleVT();
14803 // Very little shuffling can be done for 64-bit vectors right now.
14804 if (VT.getSizeInBits() == 64)
14807 // FIXME: pshufb, blends, shifts.
14808 return (SVT.getVectorNumElements() == 2 ||
14809 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14810 isMOVLMask(M, SVT) ||
14811 isSHUFPMask(M, SVT) ||
14812 isPSHUFDMask(M, SVT) ||
14813 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14814 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14815 isPALIGNRMask(M, SVT, Subtarget) ||
14816 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14817 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14818 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14819 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14823 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14825 if (!VT.isSimple())
14828 MVT SVT = VT.getSimpleVT();
14829 unsigned NumElts = SVT.getVectorNumElements();
14830 // FIXME: This collection of masks seems suspect.
14833 if (NumElts == 4 && SVT.is128BitVector()) {
14834 return (isMOVLMask(Mask, SVT) ||
14835 isCommutedMOVLMask(Mask, SVT, true) ||
14836 isSHUFPMask(Mask, SVT) ||
14837 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14842 //===----------------------------------------------------------------------===//
14843 // X86 Scheduler Hooks
14844 //===----------------------------------------------------------------------===//
14846 /// Utility function to emit xbegin specifying the start of an RTM region.
14847 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14848 const TargetInstrInfo *TII) {
14849 DebugLoc DL = MI->getDebugLoc();
14851 const BasicBlock *BB = MBB->getBasicBlock();
14852 MachineFunction::iterator I = MBB;
14855 // For the v = xbegin(), we generate
14866 MachineBasicBlock *thisMBB = MBB;
14867 MachineFunction *MF = MBB->getParent();
14868 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14869 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14870 MF->insert(I, mainMBB);
14871 MF->insert(I, sinkMBB);
14873 // Transfer the remainder of BB and its successor edges to sinkMBB.
14874 sinkMBB->splice(sinkMBB->begin(), MBB,
14875 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14876 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14880 // # fallthrough to mainMBB
14881 // # abortion to sinkMBB
14882 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14883 thisMBB->addSuccessor(mainMBB);
14884 thisMBB->addSuccessor(sinkMBB);
14888 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14889 mainMBB->addSuccessor(sinkMBB);
14892 // EAX is live into the sinkMBB
14893 sinkMBB->addLiveIn(X86::EAX);
14894 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14895 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14898 MI->eraseFromParent();
14902 // Get CMPXCHG opcode for the specified data type.
14903 static unsigned getCmpXChgOpcode(EVT VT) {
14904 switch (VT.getSimpleVT().SimpleTy) {
14905 case MVT::i8: return X86::LCMPXCHG8;
14906 case MVT::i16: return X86::LCMPXCHG16;
14907 case MVT::i32: return X86::LCMPXCHG32;
14908 case MVT::i64: return X86::LCMPXCHG64;
14912 llvm_unreachable("Invalid operand size!");
14915 // Get LOAD opcode for the specified data type.
14916 static unsigned getLoadOpcode(EVT VT) {
14917 switch (VT.getSimpleVT().SimpleTy) {
14918 case MVT::i8: return X86::MOV8rm;
14919 case MVT::i16: return X86::MOV16rm;
14920 case MVT::i32: return X86::MOV32rm;
14921 case MVT::i64: return X86::MOV64rm;
14925 llvm_unreachable("Invalid operand size!");
14928 // Get opcode of the non-atomic one from the specified atomic instruction.
14929 static unsigned getNonAtomicOpcode(unsigned Opc) {
14931 case X86::ATOMAND8: return X86::AND8rr;
14932 case X86::ATOMAND16: return X86::AND16rr;
14933 case X86::ATOMAND32: return X86::AND32rr;
14934 case X86::ATOMAND64: return X86::AND64rr;
14935 case X86::ATOMOR8: return X86::OR8rr;
14936 case X86::ATOMOR16: return X86::OR16rr;
14937 case X86::ATOMOR32: return X86::OR32rr;
14938 case X86::ATOMOR64: return X86::OR64rr;
14939 case X86::ATOMXOR8: return X86::XOR8rr;
14940 case X86::ATOMXOR16: return X86::XOR16rr;
14941 case X86::ATOMXOR32: return X86::XOR32rr;
14942 case X86::ATOMXOR64: return X86::XOR64rr;
14944 llvm_unreachable("Unhandled atomic-load-op opcode!");
14947 // Get opcode of the non-atomic one from the specified atomic instruction with
14949 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14950 unsigned &ExtraOpc) {
14952 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14953 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14954 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14955 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14956 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14957 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14958 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14959 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14960 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14961 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14962 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14963 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14964 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14965 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14966 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14967 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14968 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14969 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14970 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14971 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14973 llvm_unreachable("Unhandled atomic-load-op opcode!");
14976 // Get opcode of the non-atomic one from the specified atomic instruction for
14977 // 64-bit data type on 32-bit target.
14978 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14980 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14981 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14982 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14983 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14984 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14985 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14986 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14987 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14988 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14989 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14991 llvm_unreachable("Unhandled atomic-load-op opcode!");
14994 // Get opcode of the non-atomic one from the specified atomic instruction for
14995 // 64-bit data type on 32-bit target with extra opcode.
14996 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14998 unsigned &ExtraOpc) {
15000 case X86::ATOMNAND6432:
15001 ExtraOpc = X86::NOT32r;
15002 HiOpc = X86::AND32rr;
15003 return X86::AND32rr;
15005 llvm_unreachable("Unhandled atomic-load-op opcode!");
15008 // Get pseudo CMOV opcode from the specified data type.
15009 static unsigned getPseudoCMOVOpc(EVT VT) {
15010 switch (VT.getSimpleVT().SimpleTy) {
15011 case MVT::i8: return X86::CMOV_GR8;
15012 case MVT::i16: return X86::CMOV_GR16;
15013 case MVT::i32: return X86::CMOV_GR32;
15017 llvm_unreachable("Unknown CMOV opcode!");
15020 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15021 // They will be translated into a spin-loop or compare-exchange loop from
15024 // dst = atomic-fetch-op MI.addr, MI.val
15030 // t1 = LOAD MI.addr
15032 // t4 = phi(t1, t3 / loop)
15033 // t2 = OP MI.val, t4
15035 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15041 MachineBasicBlock *
15042 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15043 MachineBasicBlock *MBB) const {
15044 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15045 DebugLoc DL = MI->getDebugLoc();
15047 MachineFunction *MF = MBB->getParent();
15048 MachineRegisterInfo &MRI = MF->getRegInfo();
15050 const BasicBlock *BB = MBB->getBasicBlock();
15051 MachineFunction::iterator I = MBB;
15054 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15055 "Unexpected number of operands");
15057 assert(MI->hasOneMemOperand() &&
15058 "Expected atomic-load-op to have one memoperand");
15060 // Memory Reference
15061 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15062 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15064 unsigned DstReg, SrcReg;
15065 unsigned MemOpndSlot;
15067 unsigned CurOp = 0;
15069 DstReg = MI->getOperand(CurOp++).getReg();
15070 MemOpndSlot = CurOp;
15071 CurOp += X86::AddrNumOperands;
15072 SrcReg = MI->getOperand(CurOp++).getReg();
15074 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15075 MVT::SimpleValueType VT = *RC->vt_begin();
15076 unsigned t1 = MRI.createVirtualRegister(RC);
15077 unsigned t2 = MRI.createVirtualRegister(RC);
15078 unsigned t3 = MRI.createVirtualRegister(RC);
15079 unsigned t4 = MRI.createVirtualRegister(RC);
15080 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15082 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15083 unsigned LOADOpc = getLoadOpcode(VT);
15085 // For the atomic load-arith operator, we generate
15088 // t1 = LOAD [MI.addr]
15090 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15091 // t1 = OP MI.val, EAX
15093 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15099 MachineBasicBlock *thisMBB = MBB;
15100 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15101 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15102 MF->insert(I, mainMBB);
15103 MF->insert(I, sinkMBB);
15105 MachineInstrBuilder MIB;
15107 // Transfer the remainder of BB and its successor edges to sinkMBB.
15108 sinkMBB->splice(sinkMBB->begin(), MBB,
15109 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15110 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15113 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15114 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15115 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15117 NewMO.setIsKill(false);
15118 MIB.addOperand(NewMO);
15120 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15121 unsigned flags = (*MMOI)->getFlags();
15122 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15123 MachineMemOperand *MMO =
15124 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15125 (*MMOI)->getSize(),
15126 (*MMOI)->getBaseAlignment(),
15127 (*MMOI)->getTBAAInfo(),
15128 (*MMOI)->getRanges());
15129 MIB.addMemOperand(MMO);
15132 thisMBB->addSuccessor(mainMBB);
15135 MachineBasicBlock *origMainMBB = mainMBB;
15138 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15139 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15141 unsigned Opc = MI->getOpcode();
15144 llvm_unreachable("Unhandled atomic-load-op opcode!");
15145 case X86::ATOMAND8:
15146 case X86::ATOMAND16:
15147 case X86::ATOMAND32:
15148 case X86::ATOMAND64:
15150 case X86::ATOMOR16:
15151 case X86::ATOMOR32:
15152 case X86::ATOMOR64:
15153 case X86::ATOMXOR8:
15154 case X86::ATOMXOR16:
15155 case X86::ATOMXOR32:
15156 case X86::ATOMXOR64: {
15157 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15158 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15162 case X86::ATOMNAND8:
15163 case X86::ATOMNAND16:
15164 case X86::ATOMNAND32:
15165 case X86::ATOMNAND64: {
15166 unsigned Tmp = MRI.createVirtualRegister(RC);
15168 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15169 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15171 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15174 case X86::ATOMMAX8:
15175 case X86::ATOMMAX16:
15176 case X86::ATOMMAX32:
15177 case X86::ATOMMAX64:
15178 case X86::ATOMMIN8:
15179 case X86::ATOMMIN16:
15180 case X86::ATOMMIN32:
15181 case X86::ATOMMIN64:
15182 case X86::ATOMUMAX8:
15183 case X86::ATOMUMAX16:
15184 case X86::ATOMUMAX32:
15185 case X86::ATOMUMAX64:
15186 case X86::ATOMUMIN8:
15187 case X86::ATOMUMIN16:
15188 case X86::ATOMUMIN32:
15189 case X86::ATOMUMIN64: {
15191 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15193 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15197 if (Subtarget->hasCMov()) {
15198 if (VT != MVT::i8) {
15200 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15204 // Promote i8 to i32 to use CMOV32
15205 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15206 const TargetRegisterClass *RC32 =
15207 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15208 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15209 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15210 unsigned Tmp = MRI.createVirtualRegister(RC32);
15212 unsigned Undef = MRI.createVirtualRegister(RC32);
15213 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15215 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15218 .addImm(X86::sub_8bit);
15219 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15222 .addImm(X86::sub_8bit);
15224 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15228 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15229 .addReg(Tmp, 0, X86::sub_8bit);
15232 // Use pseudo select and lower them.
15233 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15234 "Invalid atomic-load-op transformation!");
15235 unsigned SelOpc = getPseudoCMOVOpc(VT);
15236 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15237 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15238 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15239 .addReg(SrcReg).addReg(t4)
15241 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15242 // Replace the original PHI node as mainMBB is changed after CMOV
15244 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15245 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15246 Phi->eraseFromParent();
15252 // Copy PhyReg back from virtual register.
15253 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15256 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15257 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15258 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15260 NewMO.setIsKill(false);
15261 MIB.addOperand(NewMO);
15264 MIB.setMemRefs(MMOBegin, MMOEnd);
15266 // Copy PhyReg back to virtual register.
15267 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15270 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15272 mainMBB->addSuccessor(origMainMBB);
15273 mainMBB->addSuccessor(sinkMBB);
15276 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15277 TII->get(TargetOpcode::COPY), DstReg)
15280 MI->eraseFromParent();
15284 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15285 // instructions. They will be translated into a spin-loop or compare-exchange
15289 // dst = atomic-fetch-op MI.addr, MI.val
15295 // t1L = LOAD [MI.addr + 0]
15296 // t1H = LOAD [MI.addr + 4]
15298 // t4L = phi(t1L, t3L / loop)
15299 // t4H = phi(t1H, t3H / loop)
15300 // t2L = OP MI.val.lo, t4L
15301 // t2H = OP MI.val.hi, t4H
15306 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15314 MachineBasicBlock *
15315 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15316 MachineBasicBlock *MBB) const {
15317 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15318 DebugLoc DL = MI->getDebugLoc();
15320 MachineFunction *MF = MBB->getParent();
15321 MachineRegisterInfo &MRI = MF->getRegInfo();
15323 const BasicBlock *BB = MBB->getBasicBlock();
15324 MachineFunction::iterator I = MBB;
15327 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15328 "Unexpected number of operands");
15330 assert(MI->hasOneMemOperand() &&
15331 "Expected atomic-load-op32 to have one memoperand");
15333 // Memory Reference
15334 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15335 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15337 unsigned DstLoReg, DstHiReg;
15338 unsigned SrcLoReg, SrcHiReg;
15339 unsigned MemOpndSlot;
15341 unsigned CurOp = 0;
15343 DstLoReg = MI->getOperand(CurOp++).getReg();
15344 DstHiReg = MI->getOperand(CurOp++).getReg();
15345 MemOpndSlot = CurOp;
15346 CurOp += X86::AddrNumOperands;
15347 SrcLoReg = MI->getOperand(CurOp++).getReg();
15348 SrcHiReg = MI->getOperand(CurOp++).getReg();
15350 const TargetRegisterClass *RC = &X86::GR32RegClass;
15351 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15353 unsigned t1L = MRI.createVirtualRegister(RC);
15354 unsigned t1H = MRI.createVirtualRegister(RC);
15355 unsigned t2L = MRI.createVirtualRegister(RC);
15356 unsigned t2H = MRI.createVirtualRegister(RC);
15357 unsigned t3L = MRI.createVirtualRegister(RC);
15358 unsigned t3H = MRI.createVirtualRegister(RC);
15359 unsigned t4L = MRI.createVirtualRegister(RC);
15360 unsigned t4H = MRI.createVirtualRegister(RC);
15362 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15363 unsigned LOADOpc = X86::MOV32rm;
15365 // For the atomic load-arith operator, we generate
15368 // t1L = LOAD [MI.addr + 0]
15369 // t1H = LOAD [MI.addr + 4]
15371 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15372 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15373 // t2L = OP MI.val.lo, t4L
15374 // t2H = OP MI.val.hi, t4H
15377 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15385 MachineBasicBlock *thisMBB = MBB;
15386 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15387 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15388 MF->insert(I, mainMBB);
15389 MF->insert(I, sinkMBB);
15391 MachineInstrBuilder MIB;
15393 // Transfer the remainder of BB and its successor edges to sinkMBB.
15394 sinkMBB->splice(sinkMBB->begin(), MBB,
15395 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15396 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15400 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15401 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15402 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15404 NewMO.setIsKill(false);
15405 MIB.addOperand(NewMO);
15407 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15408 unsigned flags = (*MMOI)->getFlags();
15409 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15410 MachineMemOperand *MMO =
15411 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15412 (*MMOI)->getSize(),
15413 (*MMOI)->getBaseAlignment(),
15414 (*MMOI)->getTBAAInfo(),
15415 (*MMOI)->getRanges());
15416 MIB.addMemOperand(MMO);
15418 MachineInstr *LowMI = MIB;
15421 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15422 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15423 if (i == X86::AddrDisp) {
15424 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15426 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15428 NewMO.setIsKill(false);
15429 MIB.addOperand(NewMO);
15432 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15434 thisMBB->addSuccessor(mainMBB);
15437 MachineBasicBlock *origMainMBB = mainMBB;
15440 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15441 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15442 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15443 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15445 unsigned Opc = MI->getOpcode();
15448 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15449 case X86::ATOMAND6432:
15450 case X86::ATOMOR6432:
15451 case X86::ATOMXOR6432:
15452 case X86::ATOMADD6432:
15453 case X86::ATOMSUB6432: {
15455 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15456 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15458 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15462 case X86::ATOMNAND6432: {
15463 unsigned HiOpc, NOTOpc;
15464 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15465 unsigned TmpL = MRI.createVirtualRegister(RC);
15466 unsigned TmpH = MRI.createVirtualRegister(RC);
15467 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15469 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15471 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15472 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15475 case X86::ATOMMAX6432:
15476 case X86::ATOMMIN6432:
15477 case X86::ATOMUMAX6432:
15478 case X86::ATOMUMIN6432: {
15480 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15481 unsigned cL = MRI.createVirtualRegister(RC8);
15482 unsigned cH = MRI.createVirtualRegister(RC8);
15483 unsigned cL32 = MRI.createVirtualRegister(RC);
15484 unsigned cH32 = MRI.createVirtualRegister(RC);
15485 unsigned cc = MRI.createVirtualRegister(RC);
15486 // cl := cmp src_lo, lo
15487 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15488 .addReg(SrcLoReg).addReg(t4L);
15489 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15490 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15491 // ch := cmp src_hi, hi
15492 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15493 .addReg(SrcHiReg).addReg(t4H);
15494 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15495 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15496 // cc := if (src_hi == hi) ? cl : ch;
15497 if (Subtarget->hasCMov()) {
15498 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15499 .addReg(cH32).addReg(cL32);
15501 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15502 .addReg(cH32).addReg(cL32)
15503 .addImm(X86::COND_E);
15504 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15506 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15507 if (Subtarget->hasCMov()) {
15508 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15509 .addReg(SrcLoReg).addReg(t4L);
15510 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15511 .addReg(SrcHiReg).addReg(t4H);
15513 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15514 .addReg(SrcLoReg).addReg(t4L)
15515 .addImm(X86::COND_NE);
15516 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15517 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15518 // 2nd CMOV lowering.
15519 mainMBB->addLiveIn(X86::EFLAGS);
15520 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15521 .addReg(SrcHiReg).addReg(t4H)
15522 .addImm(X86::COND_NE);
15523 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15524 // Replace the original PHI node as mainMBB is changed after CMOV
15526 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15527 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15528 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15529 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15530 PhiL->eraseFromParent();
15531 PhiH->eraseFromParent();
15535 case X86::ATOMSWAP6432: {
15537 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15538 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15539 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15544 // Copy EDX:EAX back from HiReg:LoReg
15545 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15546 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15547 // Copy ECX:EBX from t1H:t1L
15548 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15549 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15551 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15552 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15553 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15555 NewMO.setIsKill(false);
15556 MIB.addOperand(NewMO);
15558 MIB.setMemRefs(MMOBegin, MMOEnd);
15560 // Copy EDX:EAX back to t3H:t3L
15561 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15562 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15564 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15566 mainMBB->addSuccessor(origMainMBB);
15567 mainMBB->addSuccessor(sinkMBB);
15570 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15571 TII->get(TargetOpcode::COPY), DstLoReg)
15573 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15574 TII->get(TargetOpcode::COPY), DstHiReg)
15577 MI->eraseFromParent();
15581 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15582 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15583 // in the .td file.
15584 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15585 const TargetInstrInfo *TII) {
15587 switch (MI->getOpcode()) {
15588 default: llvm_unreachable("illegal opcode!");
15589 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15590 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15591 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15592 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15593 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15594 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15595 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15596 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15599 DebugLoc dl = MI->getDebugLoc();
15600 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15602 unsigned NumArgs = MI->getNumOperands();
15603 for (unsigned i = 1; i < NumArgs; ++i) {
15604 MachineOperand &Op = MI->getOperand(i);
15605 if (!(Op.isReg() && Op.isImplicit()))
15606 MIB.addOperand(Op);
15608 if (MI->hasOneMemOperand())
15609 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15611 BuildMI(*BB, MI, dl,
15612 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15613 .addReg(X86::XMM0);
15615 MI->eraseFromParent();
15619 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15620 // defs in an instruction pattern
15621 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15622 const TargetInstrInfo *TII) {
15624 switch (MI->getOpcode()) {
15625 default: llvm_unreachable("illegal opcode!");
15626 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15627 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15628 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15629 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15630 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15631 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15632 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15633 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15636 DebugLoc dl = MI->getDebugLoc();
15637 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15639 unsigned NumArgs = MI->getNumOperands(); // remove the results
15640 for (unsigned i = 1; i < NumArgs; ++i) {
15641 MachineOperand &Op = MI->getOperand(i);
15642 if (!(Op.isReg() && Op.isImplicit()))
15643 MIB.addOperand(Op);
15645 if (MI->hasOneMemOperand())
15646 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15648 BuildMI(*BB, MI, dl,
15649 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15652 MI->eraseFromParent();
15656 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15657 const TargetInstrInfo *TII,
15658 const X86Subtarget* Subtarget) {
15659 DebugLoc dl = MI->getDebugLoc();
15661 // Address into RAX/EAX, other two args into ECX, EDX.
15662 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15663 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15664 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15665 for (int i = 0; i < X86::AddrNumOperands; ++i)
15666 MIB.addOperand(MI->getOperand(i));
15668 unsigned ValOps = X86::AddrNumOperands;
15669 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15670 .addReg(MI->getOperand(ValOps).getReg());
15671 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15672 .addReg(MI->getOperand(ValOps+1).getReg());
15674 // The instruction doesn't actually take any operands though.
15675 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15677 MI->eraseFromParent(); // The pseudo is gone now.
15681 MachineBasicBlock *
15682 X86TargetLowering::EmitVAARG64WithCustomInserter(
15684 MachineBasicBlock *MBB) const {
15685 // Emit va_arg instruction on X86-64.
15687 // Operands to this pseudo-instruction:
15688 // 0 ) Output : destination address (reg)
15689 // 1-5) Input : va_list address (addr, i64mem)
15690 // 6 ) ArgSize : Size (in bytes) of vararg type
15691 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15692 // 8 ) Align : Alignment of type
15693 // 9 ) EFLAGS (implicit-def)
15695 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15696 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15698 unsigned DestReg = MI->getOperand(0).getReg();
15699 MachineOperand &Base = MI->getOperand(1);
15700 MachineOperand &Scale = MI->getOperand(2);
15701 MachineOperand &Index = MI->getOperand(3);
15702 MachineOperand &Disp = MI->getOperand(4);
15703 MachineOperand &Segment = MI->getOperand(5);
15704 unsigned ArgSize = MI->getOperand(6).getImm();
15705 unsigned ArgMode = MI->getOperand(7).getImm();
15706 unsigned Align = MI->getOperand(8).getImm();
15708 // Memory Reference
15709 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15710 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15711 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15713 // Machine Information
15714 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15715 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15716 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15717 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15718 DebugLoc DL = MI->getDebugLoc();
15720 // struct va_list {
15723 // i64 overflow_area (address)
15724 // i64 reg_save_area (address)
15726 // sizeof(va_list) = 24
15727 // alignment(va_list) = 8
15729 unsigned TotalNumIntRegs = 6;
15730 unsigned TotalNumXMMRegs = 8;
15731 bool UseGPOffset = (ArgMode == 1);
15732 bool UseFPOffset = (ArgMode == 2);
15733 unsigned MaxOffset = TotalNumIntRegs * 8 +
15734 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15736 /* Align ArgSize to a multiple of 8 */
15737 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15738 bool NeedsAlign = (Align > 8);
15740 MachineBasicBlock *thisMBB = MBB;
15741 MachineBasicBlock *overflowMBB;
15742 MachineBasicBlock *offsetMBB;
15743 MachineBasicBlock *endMBB;
15745 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15746 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15747 unsigned OffsetReg = 0;
15749 if (!UseGPOffset && !UseFPOffset) {
15750 // If we only pull from the overflow region, we don't create a branch.
15751 // We don't need to alter control flow.
15752 OffsetDestReg = 0; // unused
15753 OverflowDestReg = DestReg;
15755 offsetMBB = nullptr;
15756 overflowMBB = thisMBB;
15759 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15760 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15761 // If not, pull from overflow_area. (branch to overflowMBB)
15766 // offsetMBB overflowMBB
15771 // Registers for the PHI in endMBB
15772 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15773 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15775 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15776 MachineFunction *MF = MBB->getParent();
15777 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15778 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15779 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15781 MachineFunction::iterator MBBIter = MBB;
15784 // Insert the new basic blocks
15785 MF->insert(MBBIter, offsetMBB);
15786 MF->insert(MBBIter, overflowMBB);
15787 MF->insert(MBBIter, endMBB);
15789 // Transfer the remainder of MBB and its successor edges to endMBB.
15790 endMBB->splice(endMBB->begin(), thisMBB,
15791 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15792 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15794 // Make offsetMBB and overflowMBB successors of thisMBB
15795 thisMBB->addSuccessor(offsetMBB);
15796 thisMBB->addSuccessor(overflowMBB);
15798 // endMBB is a successor of both offsetMBB and overflowMBB
15799 offsetMBB->addSuccessor(endMBB);
15800 overflowMBB->addSuccessor(endMBB);
15802 // Load the offset value into a register
15803 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15804 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15808 .addDisp(Disp, UseFPOffset ? 4 : 0)
15809 .addOperand(Segment)
15810 .setMemRefs(MMOBegin, MMOEnd);
15812 // Check if there is enough room left to pull this argument.
15813 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15815 .addImm(MaxOffset + 8 - ArgSizeA8);
15817 // Branch to "overflowMBB" if offset >= max
15818 // Fall through to "offsetMBB" otherwise
15819 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15820 .addMBB(overflowMBB);
15823 // In offsetMBB, emit code to use the reg_save_area.
15825 assert(OffsetReg != 0);
15827 // Read the reg_save_area address.
15828 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15829 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15834 .addOperand(Segment)
15835 .setMemRefs(MMOBegin, MMOEnd);
15837 // Zero-extend the offset
15838 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15839 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15842 .addImm(X86::sub_32bit);
15844 // Add the offset to the reg_save_area to get the final address.
15845 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15846 .addReg(OffsetReg64)
15847 .addReg(RegSaveReg);
15849 // Compute the offset for the next argument
15850 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15851 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15853 .addImm(UseFPOffset ? 16 : 8);
15855 // Store it back into the va_list.
15856 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15860 .addDisp(Disp, UseFPOffset ? 4 : 0)
15861 .addOperand(Segment)
15862 .addReg(NextOffsetReg)
15863 .setMemRefs(MMOBegin, MMOEnd);
15866 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15871 // Emit code to use overflow area
15874 // Load the overflow_area address into a register.
15875 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15876 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15881 .addOperand(Segment)
15882 .setMemRefs(MMOBegin, MMOEnd);
15884 // If we need to align it, do so. Otherwise, just copy the address
15885 // to OverflowDestReg.
15887 // Align the overflow address
15888 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15889 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15891 // aligned_addr = (addr + (align-1)) & ~(align-1)
15892 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15893 .addReg(OverflowAddrReg)
15896 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15898 .addImm(~(uint64_t)(Align-1));
15900 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15901 .addReg(OverflowAddrReg);
15904 // Compute the next overflow address after this argument.
15905 // (the overflow address should be kept 8-byte aligned)
15906 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15907 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15908 .addReg(OverflowDestReg)
15909 .addImm(ArgSizeA8);
15911 // Store the new overflow address.
15912 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15917 .addOperand(Segment)
15918 .addReg(NextAddrReg)
15919 .setMemRefs(MMOBegin, MMOEnd);
15921 // If we branched, emit the PHI to the front of endMBB.
15923 BuildMI(*endMBB, endMBB->begin(), DL,
15924 TII->get(X86::PHI), DestReg)
15925 .addReg(OffsetDestReg).addMBB(offsetMBB)
15926 .addReg(OverflowDestReg).addMBB(overflowMBB);
15929 // Erase the pseudo instruction
15930 MI->eraseFromParent();
15935 MachineBasicBlock *
15936 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15938 MachineBasicBlock *MBB) const {
15939 // Emit code to save XMM registers to the stack. The ABI says that the
15940 // number of registers to save is given in %al, so it's theoretically
15941 // possible to do an indirect jump trick to avoid saving all of them,
15942 // however this code takes a simpler approach and just executes all
15943 // of the stores if %al is non-zero. It's less code, and it's probably
15944 // easier on the hardware branch predictor, and stores aren't all that
15945 // expensive anyway.
15947 // Create the new basic blocks. One block contains all the XMM stores,
15948 // and one block is the final destination regardless of whether any
15949 // stores were performed.
15950 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15951 MachineFunction *F = MBB->getParent();
15952 MachineFunction::iterator MBBIter = MBB;
15954 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15955 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15956 F->insert(MBBIter, XMMSaveMBB);
15957 F->insert(MBBIter, EndMBB);
15959 // Transfer the remainder of MBB and its successor edges to EndMBB.
15960 EndMBB->splice(EndMBB->begin(), MBB,
15961 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15962 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15964 // The original block will now fall through to the XMM save block.
15965 MBB->addSuccessor(XMMSaveMBB);
15966 // The XMMSaveMBB will fall through to the end block.
15967 XMMSaveMBB->addSuccessor(EndMBB);
15969 // Now add the instructions.
15970 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15971 DebugLoc DL = MI->getDebugLoc();
15973 unsigned CountReg = MI->getOperand(0).getReg();
15974 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15975 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15977 if (!Subtarget->isTargetWin64()) {
15978 // If %al is 0, branch around the XMM save block.
15979 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15980 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15981 MBB->addSuccessor(EndMBB);
15984 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15985 // that was just emitted, but clearly shouldn't be "saved".
15986 assert((MI->getNumOperands() <= 3 ||
15987 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15988 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15989 && "Expected last argument to be EFLAGS");
15990 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15991 // In the XMM save block, save all the XMM argument registers.
15992 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15993 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15994 MachineMemOperand *MMO =
15995 F->getMachineMemOperand(
15996 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15997 MachineMemOperand::MOStore,
15998 /*Size=*/16, /*Align=*/16);
15999 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16000 .addFrameIndex(RegSaveFrameIndex)
16001 .addImm(/*Scale=*/1)
16002 .addReg(/*IndexReg=*/0)
16003 .addImm(/*Disp=*/Offset)
16004 .addReg(/*Segment=*/0)
16005 .addReg(MI->getOperand(i).getReg())
16006 .addMemOperand(MMO);
16009 MI->eraseFromParent(); // The pseudo instruction is gone now.
16014 // The EFLAGS operand of SelectItr might be missing a kill marker
16015 // because there were multiple uses of EFLAGS, and ISel didn't know
16016 // which to mark. Figure out whether SelectItr should have had a
16017 // kill marker, and set it if it should. Returns the correct kill
16019 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16020 MachineBasicBlock* BB,
16021 const TargetRegisterInfo* TRI) {
16022 // Scan forward through BB for a use/def of EFLAGS.
16023 MachineBasicBlock::iterator miI(std::next(SelectItr));
16024 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16025 const MachineInstr& mi = *miI;
16026 if (mi.readsRegister(X86::EFLAGS))
16028 if (mi.definesRegister(X86::EFLAGS))
16029 break; // Should have kill-flag - update below.
16032 // If we hit the end of the block, check whether EFLAGS is live into a
16034 if (miI == BB->end()) {
16035 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16036 sEnd = BB->succ_end();
16037 sItr != sEnd; ++sItr) {
16038 MachineBasicBlock* succ = *sItr;
16039 if (succ->isLiveIn(X86::EFLAGS))
16044 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16045 // out. SelectMI should have a kill flag on EFLAGS.
16046 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16050 MachineBasicBlock *
16051 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16052 MachineBasicBlock *BB) const {
16053 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16054 DebugLoc DL = MI->getDebugLoc();
16056 // To "insert" a SELECT_CC instruction, we actually have to insert the
16057 // diamond control-flow pattern. The incoming instruction knows the
16058 // destination vreg to set, the condition code register to branch on, the
16059 // true/false values to select between, and a branch opcode to use.
16060 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16061 MachineFunction::iterator It = BB;
16067 // cmpTY ccX, r1, r2
16069 // fallthrough --> copy0MBB
16070 MachineBasicBlock *thisMBB = BB;
16071 MachineFunction *F = BB->getParent();
16072 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16073 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16074 F->insert(It, copy0MBB);
16075 F->insert(It, sinkMBB);
16077 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16078 // live into the sink and copy blocks.
16079 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16080 if (!MI->killsRegister(X86::EFLAGS) &&
16081 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16082 copy0MBB->addLiveIn(X86::EFLAGS);
16083 sinkMBB->addLiveIn(X86::EFLAGS);
16086 // Transfer the remainder of BB and its successor edges to sinkMBB.
16087 sinkMBB->splice(sinkMBB->begin(), BB,
16088 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16089 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16091 // Add the true and fallthrough blocks as its successors.
16092 BB->addSuccessor(copy0MBB);
16093 BB->addSuccessor(sinkMBB);
16095 // Create the conditional branch instruction.
16097 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16098 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16101 // %FalseValue = ...
16102 // # fallthrough to sinkMBB
16103 copy0MBB->addSuccessor(sinkMBB);
16106 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16108 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16109 TII->get(X86::PHI), MI->getOperand(0).getReg())
16110 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16111 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16113 MI->eraseFromParent(); // The pseudo instruction is gone now.
16117 MachineBasicBlock *
16118 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16119 bool Is64Bit) const {
16120 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16121 DebugLoc DL = MI->getDebugLoc();
16122 MachineFunction *MF = BB->getParent();
16123 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16125 assert(MF->shouldSplitStack());
16127 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16128 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16131 // ... [Till the alloca]
16132 // If stacklet is not large enough, jump to mallocMBB
16135 // Allocate by subtracting from RSP
16136 // Jump to continueMBB
16139 // Allocate by call to runtime
16143 // [rest of original BB]
16146 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16147 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16148 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16150 MachineRegisterInfo &MRI = MF->getRegInfo();
16151 const TargetRegisterClass *AddrRegClass =
16152 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16154 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16155 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16156 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16157 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16158 sizeVReg = MI->getOperand(1).getReg(),
16159 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16161 MachineFunction::iterator MBBIter = BB;
16164 MF->insert(MBBIter, bumpMBB);
16165 MF->insert(MBBIter, mallocMBB);
16166 MF->insert(MBBIter, continueMBB);
16168 continueMBB->splice(continueMBB->begin(), BB,
16169 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16170 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16172 // Add code to the main basic block to check if the stack limit has been hit,
16173 // and if so, jump to mallocMBB otherwise to bumpMBB.
16174 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16175 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16176 .addReg(tmpSPVReg).addReg(sizeVReg);
16177 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16178 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16179 .addReg(SPLimitVReg);
16180 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16182 // bumpMBB simply decreases the stack pointer, since we know the current
16183 // stacklet has enough space.
16184 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16185 .addReg(SPLimitVReg);
16186 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16187 .addReg(SPLimitVReg);
16188 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16190 // Calls into a routine in libgcc to allocate more space from the heap.
16191 const uint32_t *RegMask =
16192 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16194 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16196 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16197 .addExternalSymbol("__morestack_allocate_stack_space")
16198 .addRegMask(RegMask)
16199 .addReg(X86::RDI, RegState::Implicit)
16200 .addReg(X86::RAX, RegState::ImplicitDefine);
16202 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16204 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16205 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16206 .addExternalSymbol("__morestack_allocate_stack_space")
16207 .addRegMask(RegMask)
16208 .addReg(X86::EAX, RegState::ImplicitDefine);
16212 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16215 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16216 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16217 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16219 // Set up the CFG correctly.
16220 BB->addSuccessor(bumpMBB);
16221 BB->addSuccessor(mallocMBB);
16222 mallocMBB->addSuccessor(continueMBB);
16223 bumpMBB->addSuccessor(continueMBB);
16225 // Take care of the PHI nodes.
16226 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16227 MI->getOperand(0).getReg())
16228 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16229 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16231 // Delete the original pseudo instruction.
16232 MI->eraseFromParent();
16235 return continueMBB;
16238 MachineBasicBlock *
16239 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16240 MachineBasicBlock *BB) const {
16241 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16242 DebugLoc DL = MI->getDebugLoc();
16244 assert(!Subtarget->isTargetMacho());
16246 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16247 // non-trivial part is impdef of ESP.
16249 if (Subtarget->isTargetWin64()) {
16250 if (Subtarget->isTargetCygMing()) {
16251 // ___chkstk(Mingw64):
16252 // Clobbers R10, R11, RAX and EFLAGS.
16254 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16255 .addExternalSymbol("___chkstk")
16256 .addReg(X86::RAX, RegState::Implicit)
16257 .addReg(X86::RSP, RegState::Implicit)
16258 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16259 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16260 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16262 // __chkstk(MSVCRT): does not update stack pointer.
16263 // Clobbers R10, R11 and EFLAGS.
16264 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16265 .addExternalSymbol("__chkstk")
16266 .addReg(X86::RAX, RegState::Implicit)
16267 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16268 // RAX has the offset to be subtracted from RSP.
16269 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16274 const char *StackProbeSymbol =
16275 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16277 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16278 .addExternalSymbol(StackProbeSymbol)
16279 .addReg(X86::EAX, RegState::Implicit)
16280 .addReg(X86::ESP, RegState::Implicit)
16281 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16282 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16283 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16286 MI->eraseFromParent(); // The pseudo instruction is gone now.
16290 MachineBasicBlock *
16291 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16292 MachineBasicBlock *BB) const {
16293 // This is pretty easy. We're taking the value that we received from
16294 // our load from the relocation, sticking it in either RDI (x86-64)
16295 // or EAX and doing an indirect call. The return value will then
16296 // be in the normal return register.
16297 const X86InstrInfo *TII
16298 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16299 DebugLoc DL = MI->getDebugLoc();
16300 MachineFunction *F = BB->getParent();
16302 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16303 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16305 // Get a register mask for the lowered call.
16306 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16307 // proper register mask.
16308 const uint32_t *RegMask =
16309 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16310 if (Subtarget->is64Bit()) {
16311 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16312 TII->get(X86::MOV64rm), X86::RDI)
16314 .addImm(0).addReg(0)
16315 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16316 MI->getOperand(3).getTargetFlags())
16318 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16319 addDirectMem(MIB, X86::RDI);
16320 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16321 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16322 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16323 TII->get(X86::MOV32rm), X86::EAX)
16325 .addImm(0).addReg(0)
16326 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16327 MI->getOperand(3).getTargetFlags())
16329 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16330 addDirectMem(MIB, X86::EAX);
16331 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16333 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16334 TII->get(X86::MOV32rm), X86::EAX)
16335 .addReg(TII->getGlobalBaseReg(F))
16336 .addImm(0).addReg(0)
16337 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16338 MI->getOperand(3).getTargetFlags())
16340 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16341 addDirectMem(MIB, X86::EAX);
16342 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16345 MI->eraseFromParent(); // The pseudo instruction is gone now.
16349 MachineBasicBlock *
16350 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16351 MachineBasicBlock *MBB) const {
16352 DebugLoc DL = MI->getDebugLoc();
16353 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16355 MachineFunction *MF = MBB->getParent();
16356 MachineRegisterInfo &MRI = MF->getRegInfo();
16358 const BasicBlock *BB = MBB->getBasicBlock();
16359 MachineFunction::iterator I = MBB;
16362 // Memory Reference
16363 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16364 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16367 unsigned MemOpndSlot = 0;
16369 unsigned CurOp = 0;
16371 DstReg = MI->getOperand(CurOp++).getReg();
16372 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16373 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16374 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16375 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16377 MemOpndSlot = CurOp;
16379 MVT PVT = getPointerTy();
16380 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16381 "Invalid Pointer Size!");
16383 // For v = setjmp(buf), we generate
16386 // buf[LabelOffset] = restoreMBB
16387 // SjLjSetup restoreMBB
16393 // v = phi(main, restore)
16398 MachineBasicBlock *thisMBB = MBB;
16399 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16400 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16401 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16402 MF->insert(I, mainMBB);
16403 MF->insert(I, sinkMBB);
16404 MF->push_back(restoreMBB);
16406 MachineInstrBuilder MIB;
16408 // Transfer the remainder of BB and its successor edges to sinkMBB.
16409 sinkMBB->splice(sinkMBB->begin(), MBB,
16410 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16411 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16414 unsigned PtrStoreOpc = 0;
16415 unsigned LabelReg = 0;
16416 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16417 Reloc::Model RM = getTargetMachine().getRelocationModel();
16418 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16419 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16421 // Prepare IP either in reg or imm.
16422 if (!UseImmLabel) {
16423 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16424 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16425 LabelReg = MRI.createVirtualRegister(PtrRC);
16426 if (Subtarget->is64Bit()) {
16427 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16431 .addMBB(restoreMBB)
16434 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16435 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16436 .addReg(XII->getGlobalBaseReg(MF))
16439 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16443 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16445 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16446 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16447 if (i == X86::AddrDisp)
16448 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16450 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16453 MIB.addReg(LabelReg);
16455 MIB.addMBB(restoreMBB);
16456 MIB.setMemRefs(MMOBegin, MMOEnd);
16458 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16459 .addMBB(restoreMBB);
16461 const X86RegisterInfo *RegInfo =
16462 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16463 MIB.addRegMask(RegInfo->getNoPreservedMask());
16464 thisMBB->addSuccessor(mainMBB);
16465 thisMBB->addSuccessor(restoreMBB);
16469 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16470 mainMBB->addSuccessor(sinkMBB);
16473 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16474 TII->get(X86::PHI), DstReg)
16475 .addReg(mainDstReg).addMBB(mainMBB)
16476 .addReg(restoreDstReg).addMBB(restoreMBB);
16479 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16480 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16481 restoreMBB->addSuccessor(sinkMBB);
16483 MI->eraseFromParent();
16487 MachineBasicBlock *
16488 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16489 MachineBasicBlock *MBB) const {
16490 DebugLoc DL = MI->getDebugLoc();
16491 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16493 MachineFunction *MF = MBB->getParent();
16494 MachineRegisterInfo &MRI = MF->getRegInfo();
16496 // Memory Reference
16497 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16498 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16500 MVT PVT = getPointerTy();
16501 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16502 "Invalid Pointer Size!");
16504 const TargetRegisterClass *RC =
16505 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16506 unsigned Tmp = MRI.createVirtualRegister(RC);
16507 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16508 const X86RegisterInfo *RegInfo =
16509 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16510 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16511 unsigned SP = RegInfo->getStackRegister();
16513 MachineInstrBuilder MIB;
16515 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16516 const int64_t SPOffset = 2 * PVT.getStoreSize();
16518 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16519 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16522 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16523 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16524 MIB.addOperand(MI->getOperand(i));
16525 MIB.setMemRefs(MMOBegin, MMOEnd);
16527 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16528 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16529 if (i == X86::AddrDisp)
16530 MIB.addDisp(MI->getOperand(i), LabelOffset);
16532 MIB.addOperand(MI->getOperand(i));
16534 MIB.setMemRefs(MMOBegin, MMOEnd);
16536 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16537 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16538 if (i == X86::AddrDisp)
16539 MIB.addDisp(MI->getOperand(i), SPOffset);
16541 MIB.addOperand(MI->getOperand(i));
16543 MIB.setMemRefs(MMOBegin, MMOEnd);
16545 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16547 MI->eraseFromParent();
16551 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16552 // accumulator loops. Writing back to the accumulator allows the coalescer
16553 // to remove extra copies in the loop.
16554 MachineBasicBlock *
16555 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16556 MachineBasicBlock *MBB) const {
16557 MachineOperand &AddendOp = MI->getOperand(3);
16559 // Bail out early if the addend isn't a register - we can't switch these.
16560 if (!AddendOp.isReg())
16563 MachineFunction &MF = *MBB->getParent();
16564 MachineRegisterInfo &MRI = MF.getRegInfo();
16566 // Check whether the addend is defined by a PHI:
16567 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16568 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16569 if (!AddendDef.isPHI())
16572 // Look for the following pattern:
16574 // %addend = phi [%entry, 0], [%loop, %result]
16576 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16580 // %addend = phi [%entry, 0], [%loop, %result]
16582 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16584 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16585 assert(AddendDef.getOperand(i).isReg());
16586 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16587 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16588 if (&PHISrcInst == MI) {
16589 // Found a matching instruction.
16590 unsigned NewFMAOpc = 0;
16591 switch (MI->getOpcode()) {
16592 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16593 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16594 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16595 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16596 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16597 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16598 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16599 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16600 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16601 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16602 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16603 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16604 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16605 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16606 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16607 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16608 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16609 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16610 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16611 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16612 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16613 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16614 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16615 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16616 default: llvm_unreachable("Unrecognized FMA variant.");
16619 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16620 MachineInstrBuilder MIB =
16621 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16622 .addOperand(MI->getOperand(0))
16623 .addOperand(MI->getOperand(3))
16624 .addOperand(MI->getOperand(2))
16625 .addOperand(MI->getOperand(1));
16626 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16627 MI->eraseFromParent();
16634 MachineBasicBlock *
16635 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16636 MachineBasicBlock *BB) const {
16637 switch (MI->getOpcode()) {
16638 default: llvm_unreachable("Unexpected instr type to insert");
16639 case X86::TAILJMPd64:
16640 case X86::TAILJMPr64:
16641 case X86::TAILJMPm64:
16642 llvm_unreachable("TAILJMP64 would not be touched here.");
16643 case X86::TCRETURNdi64:
16644 case X86::TCRETURNri64:
16645 case X86::TCRETURNmi64:
16647 case X86::WIN_ALLOCA:
16648 return EmitLoweredWinAlloca(MI, BB);
16649 case X86::SEG_ALLOCA_32:
16650 return EmitLoweredSegAlloca(MI, BB, false);
16651 case X86::SEG_ALLOCA_64:
16652 return EmitLoweredSegAlloca(MI, BB, true);
16653 case X86::TLSCall_32:
16654 case X86::TLSCall_64:
16655 return EmitLoweredTLSCall(MI, BB);
16656 case X86::CMOV_GR8:
16657 case X86::CMOV_FR32:
16658 case X86::CMOV_FR64:
16659 case X86::CMOV_V4F32:
16660 case X86::CMOV_V2F64:
16661 case X86::CMOV_V2I64:
16662 case X86::CMOV_V8F32:
16663 case X86::CMOV_V4F64:
16664 case X86::CMOV_V4I64:
16665 case X86::CMOV_V16F32:
16666 case X86::CMOV_V8F64:
16667 case X86::CMOV_V8I64:
16668 case X86::CMOV_GR16:
16669 case X86::CMOV_GR32:
16670 case X86::CMOV_RFP32:
16671 case X86::CMOV_RFP64:
16672 case X86::CMOV_RFP80:
16673 return EmitLoweredSelect(MI, BB);
16675 case X86::FP32_TO_INT16_IN_MEM:
16676 case X86::FP32_TO_INT32_IN_MEM:
16677 case X86::FP32_TO_INT64_IN_MEM:
16678 case X86::FP64_TO_INT16_IN_MEM:
16679 case X86::FP64_TO_INT32_IN_MEM:
16680 case X86::FP64_TO_INT64_IN_MEM:
16681 case X86::FP80_TO_INT16_IN_MEM:
16682 case X86::FP80_TO_INT32_IN_MEM:
16683 case X86::FP80_TO_INT64_IN_MEM: {
16684 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16685 DebugLoc DL = MI->getDebugLoc();
16687 // Change the floating point control register to use "round towards zero"
16688 // mode when truncating to an integer value.
16689 MachineFunction *F = BB->getParent();
16690 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16691 addFrameReference(BuildMI(*BB, MI, DL,
16692 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16694 // Load the old value of the high byte of the control word...
16696 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16697 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16700 // Set the high part to be round to zero...
16701 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16704 // Reload the modified control word now...
16705 addFrameReference(BuildMI(*BB, MI, DL,
16706 TII->get(X86::FLDCW16m)), CWFrameIdx);
16708 // Restore the memory image of control word to original value
16709 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16712 // Get the X86 opcode to use.
16714 switch (MI->getOpcode()) {
16715 default: llvm_unreachable("illegal opcode!");
16716 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16717 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16718 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16719 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16720 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16721 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16722 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16723 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16724 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16728 MachineOperand &Op = MI->getOperand(0);
16730 AM.BaseType = X86AddressMode::RegBase;
16731 AM.Base.Reg = Op.getReg();
16733 AM.BaseType = X86AddressMode::FrameIndexBase;
16734 AM.Base.FrameIndex = Op.getIndex();
16736 Op = MI->getOperand(1);
16738 AM.Scale = Op.getImm();
16739 Op = MI->getOperand(2);
16741 AM.IndexReg = Op.getImm();
16742 Op = MI->getOperand(3);
16743 if (Op.isGlobal()) {
16744 AM.GV = Op.getGlobal();
16746 AM.Disp = Op.getImm();
16748 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16749 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16751 // Reload the original control word now.
16752 addFrameReference(BuildMI(*BB, MI, DL,
16753 TII->get(X86::FLDCW16m)), CWFrameIdx);
16755 MI->eraseFromParent(); // The pseudo instruction is gone now.
16758 // String/text processing lowering.
16759 case X86::PCMPISTRM128REG:
16760 case X86::VPCMPISTRM128REG:
16761 case X86::PCMPISTRM128MEM:
16762 case X86::VPCMPISTRM128MEM:
16763 case X86::PCMPESTRM128REG:
16764 case X86::VPCMPESTRM128REG:
16765 case X86::PCMPESTRM128MEM:
16766 case X86::VPCMPESTRM128MEM:
16767 assert(Subtarget->hasSSE42() &&
16768 "Target must have SSE4.2 or AVX features enabled");
16769 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16771 // String/text processing lowering.
16772 case X86::PCMPISTRIREG:
16773 case X86::VPCMPISTRIREG:
16774 case X86::PCMPISTRIMEM:
16775 case X86::VPCMPISTRIMEM:
16776 case X86::PCMPESTRIREG:
16777 case X86::VPCMPESTRIREG:
16778 case X86::PCMPESTRIMEM:
16779 case X86::VPCMPESTRIMEM:
16780 assert(Subtarget->hasSSE42() &&
16781 "Target must have SSE4.2 or AVX features enabled");
16782 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16784 // Thread synchronization.
16786 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16790 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16792 // Atomic Lowering.
16793 case X86::ATOMAND8:
16794 case X86::ATOMAND16:
16795 case X86::ATOMAND32:
16796 case X86::ATOMAND64:
16799 case X86::ATOMOR16:
16800 case X86::ATOMOR32:
16801 case X86::ATOMOR64:
16803 case X86::ATOMXOR16:
16804 case X86::ATOMXOR8:
16805 case X86::ATOMXOR32:
16806 case X86::ATOMXOR64:
16808 case X86::ATOMNAND8:
16809 case X86::ATOMNAND16:
16810 case X86::ATOMNAND32:
16811 case X86::ATOMNAND64:
16813 case X86::ATOMMAX8:
16814 case X86::ATOMMAX16:
16815 case X86::ATOMMAX32:
16816 case X86::ATOMMAX64:
16818 case X86::ATOMMIN8:
16819 case X86::ATOMMIN16:
16820 case X86::ATOMMIN32:
16821 case X86::ATOMMIN64:
16823 case X86::ATOMUMAX8:
16824 case X86::ATOMUMAX16:
16825 case X86::ATOMUMAX32:
16826 case X86::ATOMUMAX64:
16828 case X86::ATOMUMIN8:
16829 case X86::ATOMUMIN16:
16830 case X86::ATOMUMIN32:
16831 case X86::ATOMUMIN64:
16832 return EmitAtomicLoadArith(MI, BB);
16834 // This group does 64-bit operations on a 32-bit host.
16835 case X86::ATOMAND6432:
16836 case X86::ATOMOR6432:
16837 case X86::ATOMXOR6432:
16838 case X86::ATOMNAND6432:
16839 case X86::ATOMADD6432:
16840 case X86::ATOMSUB6432:
16841 case X86::ATOMMAX6432:
16842 case X86::ATOMMIN6432:
16843 case X86::ATOMUMAX6432:
16844 case X86::ATOMUMIN6432:
16845 case X86::ATOMSWAP6432:
16846 return EmitAtomicLoadArith6432(MI, BB);
16848 case X86::VASTART_SAVE_XMM_REGS:
16849 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16851 case X86::VAARG_64:
16852 return EmitVAARG64WithCustomInserter(MI, BB);
16854 case X86::EH_SjLj_SetJmp32:
16855 case X86::EH_SjLj_SetJmp64:
16856 return emitEHSjLjSetJmp(MI, BB);
16858 case X86::EH_SjLj_LongJmp32:
16859 case X86::EH_SjLj_LongJmp64:
16860 return emitEHSjLjLongJmp(MI, BB);
16862 case TargetOpcode::STACKMAP:
16863 case TargetOpcode::PATCHPOINT:
16864 return emitPatchPoint(MI, BB);
16866 case X86::VFMADDPDr213r:
16867 case X86::VFMADDPSr213r:
16868 case X86::VFMADDSDr213r:
16869 case X86::VFMADDSSr213r:
16870 case X86::VFMSUBPDr213r:
16871 case X86::VFMSUBPSr213r:
16872 case X86::VFMSUBSDr213r:
16873 case X86::VFMSUBSSr213r:
16874 case X86::VFNMADDPDr213r:
16875 case X86::VFNMADDPSr213r:
16876 case X86::VFNMADDSDr213r:
16877 case X86::VFNMADDSSr213r:
16878 case X86::VFNMSUBPDr213r:
16879 case X86::VFNMSUBPSr213r:
16880 case X86::VFNMSUBSDr213r:
16881 case X86::VFNMSUBSSr213r:
16882 case X86::VFMADDPDr213rY:
16883 case X86::VFMADDPSr213rY:
16884 case X86::VFMSUBPDr213rY:
16885 case X86::VFMSUBPSr213rY:
16886 case X86::VFNMADDPDr213rY:
16887 case X86::VFNMADDPSr213rY:
16888 case X86::VFNMSUBPDr213rY:
16889 case X86::VFNMSUBPSr213rY:
16890 return emitFMA3Instr(MI, BB);
16894 //===----------------------------------------------------------------------===//
16895 // X86 Optimization Hooks
16896 //===----------------------------------------------------------------------===//
16898 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16901 const SelectionDAG &DAG,
16902 unsigned Depth) const {
16903 unsigned BitWidth = KnownZero.getBitWidth();
16904 unsigned Opc = Op.getOpcode();
16905 assert((Opc >= ISD::BUILTIN_OP_END ||
16906 Opc == ISD::INTRINSIC_WO_CHAIN ||
16907 Opc == ISD::INTRINSIC_W_CHAIN ||
16908 Opc == ISD::INTRINSIC_VOID) &&
16909 "Should use MaskedValueIsZero if you don't know whether Op"
16910 " is a target node!");
16912 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16926 // These nodes' second result is a boolean.
16927 if (Op.getResNo() == 0)
16930 case X86ISD::SETCC:
16931 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16933 case ISD::INTRINSIC_WO_CHAIN: {
16934 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16935 unsigned NumLoBits = 0;
16938 case Intrinsic::x86_sse_movmsk_ps:
16939 case Intrinsic::x86_avx_movmsk_ps_256:
16940 case Intrinsic::x86_sse2_movmsk_pd:
16941 case Intrinsic::x86_avx_movmsk_pd_256:
16942 case Intrinsic::x86_mmx_pmovmskb:
16943 case Intrinsic::x86_sse2_pmovmskb_128:
16944 case Intrinsic::x86_avx2_pmovmskb: {
16945 // High bits of movmskp{s|d}, pmovmskb are known zero.
16947 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16948 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16949 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16950 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16951 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16952 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16953 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16954 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16956 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16965 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16967 const SelectionDAG &,
16968 unsigned Depth) const {
16969 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16970 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16971 return Op.getValueType().getScalarType().getSizeInBits();
16977 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16978 /// node is a GlobalAddress + offset.
16979 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16980 const GlobalValue* &GA,
16981 int64_t &Offset) const {
16982 if (N->getOpcode() == X86ISD::Wrapper) {
16983 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16984 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16985 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16989 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16992 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16993 /// same as extracting the high 128-bit part of 256-bit vector and then
16994 /// inserting the result into the low part of a new 256-bit vector
16995 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16996 EVT VT = SVOp->getValueType(0);
16997 unsigned NumElems = VT.getVectorNumElements();
16999 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17000 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17001 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17002 SVOp->getMaskElt(j) >= 0)
17008 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17009 /// same as extracting the low 128-bit part of 256-bit vector and then
17010 /// inserting the result into the high part of a new 256-bit vector
17011 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17012 EVT VT = SVOp->getValueType(0);
17013 unsigned NumElems = VT.getVectorNumElements();
17015 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17016 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17017 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17018 SVOp->getMaskElt(j) >= 0)
17024 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17025 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17026 TargetLowering::DAGCombinerInfo &DCI,
17027 const X86Subtarget* Subtarget) {
17029 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17030 SDValue V1 = SVOp->getOperand(0);
17031 SDValue V2 = SVOp->getOperand(1);
17032 EVT VT = SVOp->getValueType(0);
17033 unsigned NumElems = VT.getVectorNumElements();
17035 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17036 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17040 // V UNDEF BUILD_VECTOR UNDEF
17042 // CONCAT_VECTOR CONCAT_VECTOR
17045 // RESULT: V + zero extended
17047 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17048 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17049 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17052 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17055 // To match the shuffle mask, the first half of the mask should
17056 // be exactly the first vector, and all the rest a splat with the
17057 // first element of the second one.
17058 for (unsigned i = 0; i != NumElems/2; ++i)
17059 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17060 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17063 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17064 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17065 if (Ld->hasNUsesOfValue(1, 0)) {
17066 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17067 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17069 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17070 array_lengthof(Ops),
17072 Ld->getPointerInfo(),
17073 Ld->getAlignment(),
17074 false/*isVolatile*/, true/*ReadMem*/,
17075 false/*WriteMem*/);
17077 // Make sure the newly-created LOAD is in the same position as Ld in
17078 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17079 // and update uses of Ld's output chain to use the TokenFactor.
17080 if (Ld->hasAnyUseOfValue(1)) {
17081 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17082 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17083 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17084 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17085 SDValue(ResNode.getNode(), 1));
17088 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17092 // Emit a zeroed vector and insert the desired subvector on its
17094 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17095 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17096 return DCI.CombineTo(N, InsV);
17099 //===--------------------------------------------------------------------===//
17100 // Combine some shuffles into subvector extracts and inserts:
17103 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17104 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17105 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17106 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17107 return DCI.CombineTo(N, InsV);
17110 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17111 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17112 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17113 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17114 return DCI.CombineTo(N, InsV);
17120 /// PerformShuffleCombine - Performs several different shuffle combines.
17121 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17122 TargetLowering::DAGCombinerInfo &DCI,
17123 const X86Subtarget *Subtarget) {
17125 EVT VT = N->getValueType(0);
17127 // Don't create instructions with illegal types after legalize types has run.
17128 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17129 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17132 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17133 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17134 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17135 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17137 // Only handle 128 wide vector from here on.
17138 if (!VT.is128BitVector())
17141 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17142 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17143 // consecutive, non-overlapping, and in the right order.
17144 SmallVector<SDValue, 16> Elts;
17145 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17146 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17148 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17151 /// PerformTruncateCombine - Converts truncate operation to
17152 /// a sequence of vector shuffle operations.
17153 /// It is possible when we truncate 256-bit vector to 128-bit vector
17154 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17155 TargetLowering::DAGCombinerInfo &DCI,
17156 const X86Subtarget *Subtarget) {
17160 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17161 /// specific shuffle of a load can be folded into a single element load.
17162 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17163 /// shuffles have been customed lowered so we need to handle those here.
17164 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17165 TargetLowering::DAGCombinerInfo &DCI) {
17166 if (DCI.isBeforeLegalizeOps())
17169 SDValue InVec = N->getOperand(0);
17170 SDValue EltNo = N->getOperand(1);
17172 if (!isa<ConstantSDNode>(EltNo))
17175 EVT VT = InVec.getValueType();
17177 bool HasShuffleIntoBitcast = false;
17178 if (InVec.getOpcode() == ISD::BITCAST) {
17179 // Don't duplicate a load with other uses.
17180 if (!InVec.hasOneUse())
17182 EVT BCVT = InVec.getOperand(0).getValueType();
17183 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17185 InVec = InVec.getOperand(0);
17186 HasShuffleIntoBitcast = true;
17189 if (!isTargetShuffle(InVec.getOpcode()))
17192 // Don't duplicate a load with other uses.
17193 if (!InVec.hasOneUse())
17196 SmallVector<int, 16> ShuffleMask;
17198 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17202 // Select the input vector, guarding against out of range extract vector.
17203 unsigned NumElems = VT.getVectorNumElements();
17204 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17205 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17206 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17207 : InVec.getOperand(1);
17209 // If inputs to shuffle are the same for both ops, then allow 2 uses
17210 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17212 if (LdNode.getOpcode() == ISD::BITCAST) {
17213 // Don't duplicate a load with other uses.
17214 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17217 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17218 LdNode = LdNode.getOperand(0);
17221 if (!ISD::isNormalLoad(LdNode.getNode()))
17224 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17226 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17229 if (HasShuffleIntoBitcast) {
17230 // If there's a bitcast before the shuffle, check if the load type and
17231 // alignment is valid.
17232 unsigned Align = LN0->getAlignment();
17233 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17234 unsigned NewAlign = TLI.getDataLayout()->
17235 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17237 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17241 // All checks match so transform back to vector_shuffle so that DAG combiner
17242 // can finish the job
17245 // Create shuffle node taking into account the case that its a unary shuffle
17246 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17247 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17248 InVec.getOperand(0), Shuffle,
17250 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17251 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17255 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17256 /// generation and convert it from being a bunch of shuffles and extracts
17257 /// to a simple store and scalar loads to extract the elements.
17258 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17259 TargetLowering::DAGCombinerInfo &DCI) {
17260 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17261 if (NewOp.getNode())
17264 SDValue InputVector = N->getOperand(0);
17266 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17267 // from mmx to v2i32 has a single usage.
17268 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17269 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17270 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17271 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17272 N->getValueType(0),
17273 InputVector.getNode()->getOperand(0));
17275 // Only operate on vectors of 4 elements, where the alternative shuffling
17276 // gets to be more expensive.
17277 if (InputVector.getValueType() != MVT::v4i32)
17280 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17281 // single use which is a sign-extend or zero-extend, and all elements are
17283 SmallVector<SDNode *, 4> Uses;
17284 unsigned ExtractedElements = 0;
17285 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17286 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17287 if (UI.getUse().getResNo() != InputVector.getResNo())
17290 SDNode *Extract = *UI;
17291 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17294 if (Extract->getValueType(0) != MVT::i32)
17296 if (!Extract->hasOneUse())
17298 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17299 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17301 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17304 // Record which element was extracted.
17305 ExtractedElements |=
17306 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17308 Uses.push_back(Extract);
17311 // If not all the elements were used, this may not be worthwhile.
17312 if (ExtractedElements != 15)
17315 // Ok, we've now decided to do the transformation.
17316 SDLoc dl(InputVector);
17318 // Store the value to a temporary stack slot.
17319 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17320 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17321 MachinePointerInfo(), false, false, 0);
17323 // Replace each use (extract) with a load of the appropriate element.
17324 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17325 UE = Uses.end(); UI != UE; ++UI) {
17326 SDNode *Extract = *UI;
17328 // cOMpute the element's address.
17329 SDValue Idx = Extract->getOperand(1);
17331 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17332 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17333 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17334 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17336 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17337 StackPtr, OffsetVal);
17339 // Load the scalar.
17340 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17341 ScalarAddr, MachinePointerInfo(),
17342 false, false, false, 0);
17344 // Replace the exact with the load.
17345 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17348 // The replacement was made in place; don't return anything.
17352 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17353 static std::pair<unsigned, bool>
17354 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17355 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17356 if (!VT.isVector())
17357 return std::make_pair(0, false);
17359 bool NeedSplit = false;
17360 switch (VT.getSimpleVT().SimpleTy) {
17361 default: return std::make_pair(0, false);
17365 if (!Subtarget->hasAVX2())
17367 if (!Subtarget->hasAVX())
17368 return std::make_pair(0, false);
17373 if (!Subtarget->hasSSE2())
17374 return std::make_pair(0, false);
17377 // SSE2 has only a small subset of the operations.
17378 bool hasUnsigned = Subtarget->hasSSE41() ||
17379 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17380 bool hasSigned = Subtarget->hasSSE41() ||
17381 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17383 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17386 // Check for x CC y ? x : y.
17387 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17388 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17393 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17396 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17399 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17402 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17404 // Check for x CC y ? y : x -- a min/max with reversed arms.
17405 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17406 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17411 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17414 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17417 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17420 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17424 return std::make_pair(Opc, NeedSplit);
17427 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17429 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17430 TargetLowering::DAGCombinerInfo &DCI,
17431 const X86Subtarget *Subtarget) {
17433 SDValue Cond = N->getOperand(0);
17434 // Get the LHS/RHS of the select.
17435 SDValue LHS = N->getOperand(1);
17436 SDValue RHS = N->getOperand(2);
17437 EVT VT = LHS.getValueType();
17438 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17440 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17441 // instructions match the semantics of the common C idiom x<y?x:y but not
17442 // x<=y?x:y, because of how they handle negative zero (which can be
17443 // ignored in unsafe-math mode).
17444 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17445 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17446 (Subtarget->hasSSE2() ||
17447 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17448 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17450 unsigned Opcode = 0;
17451 // Check for x CC y ? x : y.
17452 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17453 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17457 // Converting this to a min would handle NaNs incorrectly, and swapping
17458 // the operands would cause it to handle comparisons between positive
17459 // and negative zero incorrectly.
17460 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17461 if (!DAG.getTarget().Options.UnsafeFPMath &&
17462 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17464 std::swap(LHS, RHS);
17466 Opcode = X86ISD::FMIN;
17469 // Converting this to a min would handle comparisons between positive
17470 // and negative zero incorrectly.
17471 if (!DAG.getTarget().Options.UnsafeFPMath &&
17472 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17474 Opcode = X86ISD::FMIN;
17477 // Converting this to a min would handle both negative zeros and NaNs
17478 // incorrectly, but we can swap the operands to fix both.
17479 std::swap(LHS, RHS);
17483 Opcode = X86ISD::FMIN;
17487 // Converting this to a max would handle comparisons between positive
17488 // and negative zero incorrectly.
17489 if (!DAG.getTarget().Options.UnsafeFPMath &&
17490 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17492 Opcode = X86ISD::FMAX;
17495 // Converting this to a max would handle NaNs incorrectly, and swapping
17496 // the operands would cause it to handle comparisons between positive
17497 // and negative zero incorrectly.
17498 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17499 if (!DAG.getTarget().Options.UnsafeFPMath &&
17500 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17502 std::swap(LHS, RHS);
17504 Opcode = X86ISD::FMAX;
17507 // Converting this to a max would handle both negative zeros and NaNs
17508 // incorrectly, but we can swap the operands to fix both.
17509 std::swap(LHS, RHS);
17513 Opcode = X86ISD::FMAX;
17516 // Check for x CC y ? y : x -- a min/max with reversed arms.
17517 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17518 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17522 // Converting this to a min would handle comparisons between positive
17523 // and negative zero incorrectly, and swapping the operands would
17524 // cause it to handle NaNs incorrectly.
17525 if (!DAG.getTarget().Options.UnsafeFPMath &&
17526 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17527 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17529 std::swap(LHS, RHS);
17531 Opcode = X86ISD::FMIN;
17534 // Converting this to a min would handle NaNs incorrectly.
17535 if (!DAG.getTarget().Options.UnsafeFPMath &&
17536 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17538 Opcode = X86ISD::FMIN;
17541 // Converting this to a min would handle both negative zeros and NaNs
17542 // incorrectly, but we can swap the operands to fix both.
17543 std::swap(LHS, RHS);
17547 Opcode = X86ISD::FMIN;
17551 // Converting this to a max would handle NaNs incorrectly.
17552 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17554 Opcode = X86ISD::FMAX;
17557 // Converting this to a max would handle comparisons between positive
17558 // and negative zero incorrectly, and swapping the operands would
17559 // cause it to handle NaNs incorrectly.
17560 if (!DAG.getTarget().Options.UnsafeFPMath &&
17561 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17562 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17564 std::swap(LHS, RHS);
17566 Opcode = X86ISD::FMAX;
17569 // Converting this to a max would handle both negative zeros and NaNs
17570 // incorrectly, but we can swap the operands to fix both.
17571 std::swap(LHS, RHS);
17575 Opcode = X86ISD::FMAX;
17581 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17584 EVT CondVT = Cond.getValueType();
17585 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17586 CondVT.getVectorElementType() == MVT::i1) {
17587 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17588 // lowering on AVX-512. In this case we convert it to
17589 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17590 // The same situation for all 128 and 256-bit vectors of i8 and i16
17591 EVT OpVT = LHS.getValueType();
17592 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17593 (OpVT.getVectorElementType() == MVT::i8 ||
17594 OpVT.getVectorElementType() == MVT::i16)) {
17595 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17596 DCI.AddToWorklist(Cond.getNode());
17597 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17600 // If this is a select between two integer constants, try to do some
17602 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17603 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17604 // Don't do this for crazy integer types.
17605 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17606 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17607 // so that TrueC (the true value) is larger than FalseC.
17608 bool NeedsCondInvert = false;
17610 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17611 // Efficiently invertible.
17612 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17613 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17614 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17615 NeedsCondInvert = true;
17616 std::swap(TrueC, FalseC);
17619 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17620 if (FalseC->getAPIntValue() == 0 &&
17621 TrueC->getAPIntValue().isPowerOf2()) {
17622 if (NeedsCondInvert) // Invert the condition if needed.
17623 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17624 DAG.getConstant(1, Cond.getValueType()));
17626 // Zero extend the condition if needed.
17627 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17629 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17630 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17631 DAG.getConstant(ShAmt, MVT::i8));
17634 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17635 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17636 if (NeedsCondInvert) // Invert the condition if needed.
17637 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17638 DAG.getConstant(1, Cond.getValueType()));
17640 // Zero extend the condition if needed.
17641 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17642 FalseC->getValueType(0), Cond);
17643 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17644 SDValue(FalseC, 0));
17647 // Optimize cases that will turn into an LEA instruction. This requires
17648 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17649 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17650 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17651 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17653 bool isFastMultiplier = false;
17655 switch ((unsigned char)Diff) {
17657 case 1: // result = add base, cond
17658 case 2: // result = lea base( , cond*2)
17659 case 3: // result = lea base(cond, cond*2)
17660 case 4: // result = lea base( , cond*4)
17661 case 5: // result = lea base(cond, cond*4)
17662 case 8: // result = lea base( , cond*8)
17663 case 9: // result = lea base(cond, cond*8)
17664 isFastMultiplier = true;
17669 if (isFastMultiplier) {
17670 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17671 if (NeedsCondInvert) // Invert the condition if needed.
17672 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17673 DAG.getConstant(1, Cond.getValueType()));
17675 // Zero extend the condition if needed.
17676 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17678 // Scale the condition by the difference.
17680 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17681 DAG.getConstant(Diff, Cond.getValueType()));
17683 // Add the base if non-zero.
17684 if (FalseC->getAPIntValue() != 0)
17685 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17686 SDValue(FalseC, 0));
17693 // Canonicalize max and min:
17694 // (x > y) ? x : y -> (x >= y) ? x : y
17695 // (x < y) ? x : y -> (x <= y) ? x : y
17696 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17697 // the need for an extra compare
17698 // against zero. e.g.
17699 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17701 // testl %edi, %edi
17703 // cmovgl %edi, %eax
17707 // cmovsl %eax, %edi
17708 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17709 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17710 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17711 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17716 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17717 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17718 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17719 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17724 // Early exit check
17725 if (!TLI.isTypeLegal(VT))
17728 // Match VSELECTs into subs with unsigned saturation.
17729 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17730 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17731 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17732 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17733 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17735 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17736 // left side invert the predicate to simplify logic below.
17738 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17740 CC = ISD::getSetCCInverse(CC, true);
17741 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17745 if (Other.getNode() && Other->getNumOperands() == 2 &&
17746 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17747 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17748 SDValue CondRHS = Cond->getOperand(1);
17750 // Look for a general sub with unsigned saturation first.
17751 // x >= y ? x-y : 0 --> subus x, y
17752 // x > y ? x-y : 0 --> subus x, y
17753 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17754 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17755 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17757 // If the RHS is a constant we have to reverse the const canonicalization.
17758 // x > C-1 ? x+-C : 0 --> subus x, C
17759 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17760 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17761 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17762 if (CondRHS.getConstantOperandVal(0) == -A-1)
17763 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17764 DAG.getConstant(-A, VT));
17767 // Another special case: If C was a sign bit, the sub has been
17768 // canonicalized into a xor.
17769 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17770 // it's safe to decanonicalize the xor?
17771 // x s< 0 ? x^C : 0 --> subus x, C
17772 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17773 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17774 isSplatVector(OpRHS.getNode())) {
17775 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17777 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17782 // Try to match a min/max vector operation.
17783 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17784 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17785 unsigned Opc = ret.first;
17786 bool NeedSplit = ret.second;
17788 if (Opc && NeedSplit) {
17789 unsigned NumElems = VT.getVectorNumElements();
17790 // Extract the LHS vectors
17791 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17792 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17794 // Extract the RHS vectors
17795 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17796 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17798 // Create min/max for each subvector
17799 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17800 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17802 // Merge the result
17803 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17805 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17808 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17809 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17810 // Check if SETCC has already been promoted
17811 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17812 // Check that condition value type matches vselect operand type
17815 assert(Cond.getValueType().isVector() &&
17816 "vector select expects a vector selector!");
17818 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17819 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17821 if (!TValIsAllOnes && !FValIsAllZeros) {
17822 // Try invert the condition if true value is not all 1s and false value
17824 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17825 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17827 if (TValIsAllZeros || FValIsAllOnes) {
17828 SDValue CC = Cond.getOperand(2);
17829 ISD::CondCode NewCC =
17830 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17831 Cond.getOperand(0).getValueType().isInteger());
17832 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17833 std::swap(LHS, RHS);
17834 TValIsAllOnes = FValIsAllOnes;
17835 FValIsAllZeros = TValIsAllZeros;
17839 if (TValIsAllOnes || FValIsAllZeros) {
17842 if (TValIsAllOnes && FValIsAllZeros)
17844 else if (TValIsAllOnes)
17845 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17846 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17847 else if (FValIsAllZeros)
17848 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17849 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17851 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17855 // Try to fold this VSELECT into a MOVSS/MOVSD
17856 if (N->getOpcode() == ISD::VSELECT &&
17857 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17858 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17859 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17860 bool CanFold = false;
17861 unsigned NumElems = Cond.getNumOperands();
17865 if (isZero(Cond.getOperand(0))) {
17868 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17869 // fold (vselect <0,-1> -> (movsd A, B)
17870 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17871 CanFold = isAllOnes(Cond.getOperand(i));
17872 } else if (isAllOnes(Cond.getOperand(0))) {
17876 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17877 // fold (vselect <-1,0> -> (movsd B, A)
17878 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17879 CanFold = isZero(Cond.getOperand(i));
17883 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17884 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17885 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17888 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17889 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17890 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17891 // (v2i64 (bitcast B)))))
17893 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17894 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17895 // (v2f64 (bitcast B)))))
17897 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17898 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17899 // (v2i64 (bitcast A)))))
17901 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17902 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17903 // (v2f64 (bitcast A)))))
17905 CanFold = (isZero(Cond.getOperand(0)) &&
17906 isZero(Cond.getOperand(1)) &&
17907 isAllOnes(Cond.getOperand(2)) &&
17908 isAllOnes(Cond.getOperand(3)));
17910 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17911 isAllOnes(Cond.getOperand(1)) &&
17912 isZero(Cond.getOperand(2)) &&
17913 isZero(Cond.getOperand(3))) {
17915 std::swap(LHS, RHS);
17919 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17920 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17921 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17922 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17924 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17930 // If we know that this node is legal then we know that it is going to be
17931 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17932 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17933 // to simplify previous instructions.
17934 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17935 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17936 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17938 // Don't optimize vector selects that map to mask-registers.
17942 // Check all uses of that condition operand to check whether it will be
17943 // consumed by non-BLEND instructions, which may depend on all bits are set
17945 for (SDNode::use_iterator I = Cond->use_begin(),
17946 E = Cond->use_end(); I != E; ++I)
17947 if (I->getOpcode() != ISD::VSELECT)
17948 // TODO: Add other opcodes eventually lowered into BLEND.
17951 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17952 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17954 APInt KnownZero, KnownOne;
17955 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17956 DCI.isBeforeLegalizeOps());
17957 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17958 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17959 DCI.CommitTargetLoweringOpt(TLO);
17965 // Check whether a boolean test is testing a boolean value generated by
17966 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17969 // Simplify the following patterns:
17970 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17971 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17972 // to (Op EFLAGS Cond)
17974 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17975 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17976 // to (Op EFLAGS !Cond)
17978 // where Op could be BRCOND or CMOV.
17980 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17981 // Quit if not CMP and SUB with its value result used.
17982 if (Cmp.getOpcode() != X86ISD::CMP &&
17983 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17986 // Quit if not used as a boolean value.
17987 if (CC != X86::COND_E && CC != X86::COND_NE)
17990 // Check CMP operands. One of them should be 0 or 1 and the other should be
17991 // an SetCC or extended from it.
17992 SDValue Op1 = Cmp.getOperand(0);
17993 SDValue Op2 = Cmp.getOperand(1);
17996 const ConstantSDNode* C = nullptr;
17997 bool needOppositeCond = (CC == X86::COND_E);
17998 bool checkAgainstTrue = false; // Is it a comparison against 1?
18000 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18002 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18004 else // Quit if all operands are not constants.
18007 if (C->getZExtValue() == 1) {
18008 needOppositeCond = !needOppositeCond;
18009 checkAgainstTrue = true;
18010 } else if (C->getZExtValue() != 0)
18011 // Quit if the constant is neither 0 or 1.
18014 bool truncatedToBoolWithAnd = false;
18015 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18016 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18017 SetCC.getOpcode() == ISD::TRUNCATE ||
18018 SetCC.getOpcode() == ISD::AND) {
18019 if (SetCC.getOpcode() == ISD::AND) {
18021 ConstantSDNode *CS;
18022 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18023 CS->getZExtValue() == 1)
18025 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18026 CS->getZExtValue() == 1)
18030 SetCC = SetCC.getOperand(OpIdx);
18031 truncatedToBoolWithAnd = true;
18033 SetCC = SetCC.getOperand(0);
18036 switch (SetCC.getOpcode()) {
18037 case X86ISD::SETCC_CARRY:
18038 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18039 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18040 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18041 // truncated to i1 using 'and'.
18042 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18044 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18045 "Invalid use of SETCC_CARRY!");
18047 case X86ISD::SETCC:
18048 // Set the condition code or opposite one if necessary.
18049 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18050 if (needOppositeCond)
18051 CC = X86::GetOppositeBranchCondition(CC);
18052 return SetCC.getOperand(1);
18053 case X86ISD::CMOV: {
18054 // Check whether false/true value has canonical one, i.e. 0 or 1.
18055 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18056 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18057 // Quit if true value is not a constant.
18060 // Quit if false value is not a constant.
18062 SDValue Op = SetCC.getOperand(0);
18063 // Skip 'zext' or 'trunc' node.
18064 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18065 Op.getOpcode() == ISD::TRUNCATE)
18066 Op = Op.getOperand(0);
18067 // A special case for rdrand/rdseed, where 0 is set if false cond is
18069 if ((Op.getOpcode() != X86ISD::RDRAND &&
18070 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18073 // Quit if false value is not the constant 0 or 1.
18074 bool FValIsFalse = true;
18075 if (FVal && FVal->getZExtValue() != 0) {
18076 if (FVal->getZExtValue() != 1)
18078 // If FVal is 1, opposite cond is needed.
18079 needOppositeCond = !needOppositeCond;
18080 FValIsFalse = false;
18082 // Quit if TVal is not the constant opposite of FVal.
18083 if (FValIsFalse && TVal->getZExtValue() != 1)
18085 if (!FValIsFalse && TVal->getZExtValue() != 0)
18087 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18088 if (needOppositeCond)
18089 CC = X86::GetOppositeBranchCondition(CC);
18090 return SetCC.getOperand(3);
18097 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18098 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18099 TargetLowering::DAGCombinerInfo &DCI,
18100 const X86Subtarget *Subtarget) {
18103 // If the flag operand isn't dead, don't touch this CMOV.
18104 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18107 SDValue FalseOp = N->getOperand(0);
18108 SDValue TrueOp = N->getOperand(1);
18109 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18110 SDValue Cond = N->getOperand(3);
18112 if (CC == X86::COND_E || CC == X86::COND_NE) {
18113 switch (Cond.getOpcode()) {
18117 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18118 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18119 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18125 Flags = checkBoolTestSetCCCombine(Cond, CC);
18126 if (Flags.getNode() &&
18127 // Extra check as FCMOV only supports a subset of X86 cond.
18128 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18129 SDValue Ops[] = { FalseOp, TrueOp,
18130 DAG.getConstant(CC, MVT::i8), Flags };
18131 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
18132 Ops, array_lengthof(Ops));
18135 // If this is a select between two integer constants, try to do some
18136 // optimizations. Note that the operands are ordered the opposite of SELECT
18138 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18139 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18140 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18141 // larger than FalseC (the false value).
18142 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18143 CC = X86::GetOppositeBranchCondition(CC);
18144 std::swap(TrueC, FalseC);
18145 std::swap(TrueOp, FalseOp);
18148 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18149 // This is efficient for any integer data type (including i8/i16) and
18151 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18152 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18153 DAG.getConstant(CC, MVT::i8), Cond);
18155 // Zero extend the condition if needed.
18156 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18158 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18159 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18160 DAG.getConstant(ShAmt, MVT::i8));
18161 if (N->getNumValues() == 2) // Dead flag value?
18162 return DCI.CombineTo(N, Cond, SDValue());
18166 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18167 // for any integer data type, including i8/i16.
18168 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18169 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18170 DAG.getConstant(CC, MVT::i8), Cond);
18172 // Zero extend the condition if needed.
18173 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18174 FalseC->getValueType(0), Cond);
18175 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18176 SDValue(FalseC, 0));
18178 if (N->getNumValues() == 2) // Dead flag value?
18179 return DCI.CombineTo(N, Cond, SDValue());
18183 // Optimize cases that will turn into an LEA instruction. This requires
18184 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18185 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18186 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18187 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18189 bool isFastMultiplier = false;
18191 switch ((unsigned char)Diff) {
18193 case 1: // result = add base, cond
18194 case 2: // result = lea base( , cond*2)
18195 case 3: // result = lea base(cond, cond*2)
18196 case 4: // result = lea base( , cond*4)
18197 case 5: // result = lea base(cond, cond*4)
18198 case 8: // result = lea base( , cond*8)
18199 case 9: // result = lea base(cond, cond*8)
18200 isFastMultiplier = true;
18205 if (isFastMultiplier) {
18206 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18207 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18208 DAG.getConstant(CC, MVT::i8), Cond);
18209 // Zero extend the condition if needed.
18210 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18212 // Scale the condition by the difference.
18214 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18215 DAG.getConstant(Diff, Cond.getValueType()));
18217 // Add the base if non-zero.
18218 if (FalseC->getAPIntValue() != 0)
18219 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18220 SDValue(FalseC, 0));
18221 if (N->getNumValues() == 2) // Dead flag value?
18222 return DCI.CombineTo(N, Cond, SDValue());
18229 // Handle these cases:
18230 // (select (x != c), e, c) -> select (x != c), e, x),
18231 // (select (x == c), c, e) -> select (x == c), x, e)
18232 // where the c is an integer constant, and the "select" is the combination
18233 // of CMOV and CMP.
18235 // The rationale for this change is that the conditional-move from a constant
18236 // needs two instructions, however, conditional-move from a register needs
18237 // only one instruction.
18239 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18240 // some instruction-combining opportunities. This opt needs to be
18241 // postponed as late as possible.
18243 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18244 // the DCI.xxxx conditions are provided to postpone the optimization as
18245 // late as possible.
18247 ConstantSDNode *CmpAgainst = nullptr;
18248 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18249 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18250 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18252 if (CC == X86::COND_NE &&
18253 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18254 CC = X86::GetOppositeBranchCondition(CC);
18255 std::swap(TrueOp, FalseOp);
18258 if (CC == X86::COND_E &&
18259 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18260 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18261 DAG.getConstant(CC, MVT::i8), Cond };
18262 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
18263 array_lengthof(Ops));
18271 /// PerformMulCombine - Optimize a single multiply with constant into two
18272 /// in order to implement it with two cheaper instructions, e.g.
18273 /// LEA + SHL, LEA + LEA.
18274 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18275 TargetLowering::DAGCombinerInfo &DCI) {
18276 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18279 EVT VT = N->getValueType(0);
18280 if (VT != MVT::i64)
18283 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18286 uint64_t MulAmt = C->getZExtValue();
18287 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18290 uint64_t MulAmt1 = 0;
18291 uint64_t MulAmt2 = 0;
18292 if ((MulAmt % 9) == 0) {
18294 MulAmt2 = MulAmt / 9;
18295 } else if ((MulAmt % 5) == 0) {
18297 MulAmt2 = MulAmt / 5;
18298 } else if ((MulAmt % 3) == 0) {
18300 MulAmt2 = MulAmt / 3;
18303 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18306 if (isPowerOf2_64(MulAmt2) &&
18307 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18308 // If second multiplifer is pow2, issue it first. We want the multiply by
18309 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18311 std::swap(MulAmt1, MulAmt2);
18314 if (isPowerOf2_64(MulAmt1))
18315 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18316 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18318 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18319 DAG.getConstant(MulAmt1, VT));
18321 if (isPowerOf2_64(MulAmt2))
18322 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18323 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18325 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18326 DAG.getConstant(MulAmt2, VT));
18328 // Do not add new nodes to DAG combiner worklist.
18329 DCI.CombineTo(N, NewMul, false);
18334 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18335 SDValue N0 = N->getOperand(0);
18336 SDValue N1 = N->getOperand(1);
18337 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18338 EVT VT = N0.getValueType();
18340 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18341 // since the result of setcc_c is all zero's or all ones.
18342 if (VT.isInteger() && !VT.isVector() &&
18343 N1C && N0.getOpcode() == ISD::AND &&
18344 N0.getOperand(1).getOpcode() == ISD::Constant) {
18345 SDValue N00 = N0.getOperand(0);
18346 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18347 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18348 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18349 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18350 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18351 APInt ShAmt = N1C->getAPIntValue();
18352 Mask = Mask.shl(ShAmt);
18354 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18355 N00, DAG.getConstant(Mask, VT));
18359 // Hardware support for vector shifts is sparse which makes us scalarize the
18360 // vector operations in many cases. Also, on sandybridge ADD is faster than
18362 // (shl V, 1) -> add V,V
18363 if (isSplatVector(N1.getNode())) {
18364 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18365 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18366 // We shift all of the values by one. In many cases we do not have
18367 // hardware support for this operation. This is better expressed as an ADD
18369 if (N1C && (1 == N1C->getZExtValue())) {
18370 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18377 /// \brief Returns a vector of 0s if the node in input is a vector logical
18378 /// shift by a constant amount which is known to be bigger than or equal
18379 /// to the vector element size in bits.
18380 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18381 const X86Subtarget *Subtarget) {
18382 EVT VT = N->getValueType(0);
18384 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18385 (!Subtarget->hasInt256() ||
18386 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18389 SDValue Amt = N->getOperand(1);
18391 if (isSplatVector(Amt.getNode())) {
18392 SDValue SclrAmt = Amt->getOperand(0);
18393 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18394 APInt ShiftAmt = C->getAPIntValue();
18395 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18397 // SSE2/AVX2 logical shifts always return a vector of 0s
18398 // if the shift amount is bigger than or equal to
18399 // the element size. The constant shift amount will be
18400 // encoded as a 8-bit immediate.
18401 if (ShiftAmt.trunc(8).uge(MaxAmount))
18402 return getZeroVector(VT, Subtarget, DAG, DL);
18409 /// PerformShiftCombine - Combine shifts.
18410 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18411 TargetLowering::DAGCombinerInfo &DCI,
18412 const X86Subtarget *Subtarget) {
18413 if (N->getOpcode() == ISD::SHL) {
18414 SDValue V = PerformSHLCombine(N, DAG);
18415 if (V.getNode()) return V;
18418 if (N->getOpcode() != ISD::SRA) {
18419 // Try to fold this logical shift into a zero vector.
18420 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18421 if (V.getNode()) return V;
18427 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18428 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18429 // and friends. Likewise for OR -> CMPNEQSS.
18430 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18431 TargetLowering::DAGCombinerInfo &DCI,
18432 const X86Subtarget *Subtarget) {
18435 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18436 // we're requiring SSE2 for both.
18437 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18438 SDValue N0 = N->getOperand(0);
18439 SDValue N1 = N->getOperand(1);
18440 SDValue CMP0 = N0->getOperand(1);
18441 SDValue CMP1 = N1->getOperand(1);
18444 // The SETCCs should both refer to the same CMP.
18445 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18448 SDValue CMP00 = CMP0->getOperand(0);
18449 SDValue CMP01 = CMP0->getOperand(1);
18450 EVT VT = CMP00.getValueType();
18452 if (VT == MVT::f32 || VT == MVT::f64) {
18453 bool ExpectingFlags = false;
18454 // Check for any users that want flags:
18455 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18456 !ExpectingFlags && UI != UE; ++UI)
18457 switch (UI->getOpcode()) {
18462 ExpectingFlags = true;
18464 case ISD::CopyToReg:
18465 case ISD::SIGN_EXTEND:
18466 case ISD::ZERO_EXTEND:
18467 case ISD::ANY_EXTEND:
18471 if (!ExpectingFlags) {
18472 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18473 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18475 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18476 X86::CondCode tmp = cc0;
18481 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18482 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18483 // FIXME: need symbolic constants for these magic numbers.
18484 // See X86ATTInstPrinter.cpp:printSSECC().
18485 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18486 if (Subtarget->hasAVX512()) {
18487 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18488 CMP01, DAG.getConstant(x86cc, MVT::i8));
18489 if (N->getValueType(0) != MVT::i1)
18490 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18494 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18495 CMP00.getValueType(), CMP00, CMP01,
18496 DAG.getConstant(x86cc, MVT::i8));
18498 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18499 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18501 if (is64BitFP && !Subtarget->is64Bit()) {
18502 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18503 // 64-bit integer, since that's not a legal type. Since
18504 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18505 // bits, but can do this little dance to extract the lowest 32 bits
18506 // and work with those going forward.
18507 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18509 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18511 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18512 Vector32, DAG.getIntPtrConstant(0));
18516 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18517 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18518 DAG.getConstant(1, IntVT));
18519 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18520 return OneBitOfTruth;
18528 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18529 /// so it can be folded inside ANDNP.
18530 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18531 EVT VT = N->getValueType(0);
18533 // Match direct AllOnes for 128 and 256-bit vectors
18534 if (ISD::isBuildVectorAllOnes(N))
18537 // Look through a bit convert.
18538 if (N->getOpcode() == ISD::BITCAST)
18539 N = N->getOperand(0).getNode();
18541 // Sometimes the operand may come from a insert_subvector building a 256-bit
18543 if (VT.is256BitVector() &&
18544 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18545 SDValue V1 = N->getOperand(0);
18546 SDValue V2 = N->getOperand(1);
18548 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18549 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18550 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18551 ISD::isBuildVectorAllOnes(V2.getNode()))
18558 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18559 // register. In most cases we actually compare or select YMM-sized registers
18560 // and mixing the two types creates horrible code. This method optimizes
18561 // some of the transition sequences.
18562 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18563 TargetLowering::DAGCombinerInfo &DCI,
18564 const X86Subtarget *Subtarget) {
18565 EVT VT = N->getValueType(0);
18566 if (!VT.is256BitVector())
18569 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18570 N->getOpcode() == ISD::ZERO_EXTEND ||
18571 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18573 SDValue Narrow = N->getOperand(0);
18574 EVT NarrowVT = Narrow->getValueType(0);
18575 if (!NarrowVT.is128BitVector())
18578 if (Narrow->getOpcode() != ISD::XOR &&
18579 Narrow->getOpcode() != ISD::AND &&
18580 Narrow->getOpcode() != ISD::OR)
18583 SDValue N0 = Narrow->getOperand(0);
18584 SDValue N1 = Narrow->getOperand(1);
18587 // The Left side has to be a trunc.
18588 if (N0.getOpcode() != ISD::TRUNCATE)
18591 // The type of the truncated inputs.
18592 EVT WideVT = N0->getOperand(0)->getValueType(0);
18596 // The right side has to be a 'trunc' or a constant vector.
18597 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18598 bool RHSConst = (isSplatVector(N1.getNode()) &&
18599 isa<ConstantSDNode>(N1->getOperand(0)));
18600 if (!RHSTrunc && !RHSConst)
18603 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18605 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18608 // Set N0 and N1 to hold the inputs to the new wide operation.
18609 N0 = N0->getOperand(0);
18611 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18612 N1->getOperand(0));
18613 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18614 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18615 } else if (RHSTrunc) {
18616 N1 = N1->getOperand(0);
18619 // Generate the wide operation.
18620 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18621 unsigned Opcode = N->getOpcode();
18623 case ISD::ANY_EXTEND:
18625 case ISD::ZERO_EXTEND: {
18626 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18627 APInt Mask = APInt::getAllOnesValue(InBits);
18628 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18629 return DAG.getNode(ISD::AND, DL, VT,
18630 Op, DAG.getConstant(Mask, VT));
18632 case ISD::SIGN_EXTEND:
18633 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18634 Op, DAG.getValueType(NarrowVT));
18636 llvm_unreachable("Unexpected opcode");
18640 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18641 TargetLowering::DAGCombinerInfo &DCI,
18642 const X86Subtarget *Subtarget) {
18643 EVT VT = N->getValueType(0);
18644 if (DCI.isBeforeLegalizeOps())
18647 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18651 // Create BEXTR instructions
18652 // BEXTR is ((X >> imm) & (2**size-1))
18653 if (VT == MVT::i32 || VT == MVT::i64) {
18654 SDValue N0 = N->getOperand(0);
18655 SDValue N1 = N->getOperand(1);
18658 // Check for BEXTR.
18659 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18660 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18661 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18662 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18663 if (MaskNode && ShiftNode) {
18664 uint64_t Mask = MaskNode->getZExtValue();
18665 uint64_t Shift = ShiftNode->getZExtValue();
18666 if (isMask_64(Mask)) {
18667 uint64_t MaskSize = CountPopulation_64(Mask);
18668 if (Shift + MaskSize <= VT.getSizeInBits())
18669 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18670 DAG.getConstant(Shift | (MaskSize << 8), VT));
18678 // Want to form ANDNP nodes:
18679 // 1) In the hopes of then easily combining them with OR and AND nodes
18680 // to form PBLEND/PSIGN.
18681 // 2) To match ANDN packed intrinsics
18682 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18685 SDValue N0 = N->getOperand(0);
18686 SDValue N1 = N->getOperand(1);
18689 // Check LHS for vnot
18690 if (N0.getOpcode() == ISD::XOR &&
18691 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18692 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18693 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18695 // Check RHS for vnot
18696 if (N1.getOpcode() == ISD::XOR &&
18697 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18698 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18699 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18704 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18705 TargetLowering::DAGCombinerInfo &DCI,
18706 const X86Subtarget *Subtarget) {
18707 if (DCI.isBeforeLegalizeOps())
18710 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18714 SDValue N0 = N->getOperand(0);
18715 SDValue N1 = N->getOperand(1);
18716 EVT VT = N->getValueType(0);
18718 // look for psign/blend
18719 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18720 if (!Subtarget->hasSSSE3() ||
18721 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18724 // Canonicalize pandn to RHS
18725 if (N0.getOpcode() == X86ISD::ANDNP)
18727 // or (and (m, y), (pandn m, x))
18728 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18729 SDValue Mask = N1.getOperand(0);
18730 SDValue X = N1.getOperand(1);
18732 if (N0.getOperand(0) == Mask)
18733 Y = N0.getOperand(1);
18734 if (N0.getOperand(1) == Mask)
18735 Y = N0.getOperand(0);
18737 // Check to see if the mask appeared in both the AND and ANDNP and
18741 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18742 // Look through mask bitcast.
18743 if (Mask.getOpcode() == ISD::BITCAST)
18744 Mask = Mask.getOperand(0);
18745 if (X.getOpcode() == ISD::BITCAST)
18746 X = X.getOperand(0);
18747 if (Y.getOpcode() == ISD::BITCAST)
18748 Y = Y.getOperand(0);
18750 EVT MaskVT = Mask.getValueType();
18752 // Validate that the Mask operand is a vector sra node.
18753 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18754 // there is no psrai.b
18755 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18756 unsigned SraAmt = ~0;
18757 if (Mask.getOpcode() == ISD::SRA) {
18758 SDValue Amt = Mask.getOperand(1);
18759 if (isSplatVector(Amt.getNode())) {
18760 SDValue SclrAmt = Amt->getOperand(0);
18761 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18762 SraAmt = C->getZExtValue();
18764 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18765 SDValue SraC = Mask.getOperand(1);
18766 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18768 if ((SraAmt + 1) != EltBits)
18773 // Now we know we at least have a plendvb with the mask val. See if
18774 // we can form a psignb/w/d.
18775 // psign = x.type == y.type == mask.type && y = sub(0, x);
18776 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18777 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18778 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18779 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18780 "Unsupported VT for PSIGN");
18781 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18782 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18784 // PBLENDVB only available on SSE 4.1
18785 if (!Subtarget->hasSSE41())
18788 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18790 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18791 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18792 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18793 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18794 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18798 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18801 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18802 MachineFunction &MF = DAG.getMachineFunction();
18803 bool OptForSize = MF.getFunction()->getAttributes().
18804 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18806 // SHLD/SHRD instructions have lower register pressure, but on some
18807 // platforms they have higher latency than the equivalent
18808 // series of shifts/or that would otherwise be generated.
18809 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18810 // have higher latencies and we are not optimizing for size.
18811 if (!OptForSize && Subtarget->isSHLDSlow())
18814 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18816 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18818 if (!N0.hasOneUse() || !N1.hasOneUse())
18821 SDValue ShAmt0 = N0.getOperand(1);
18822 if (ShAmt0.getValueType() != MVT::i8)
18824 SDValue ShAmt1 = N1.getOperand(1);
18825 if (ShAmt1.getValueType() != MVT::i8)
18827 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18828 ShAmt0 = ShAmt0.getOperand(0);
18829 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18830 ShAmt1 = ShAmt1.getOperand(0);
18833 unsigned Opc = X86ISD::SHLD;
18834 SDValue Op0 = N0.getOperand(0);
18835 SDValue Op1 = N1.getOperand(0);
18836 if (ShAmt0.getOpcode() == ISD::SUB) {
18837 Opc = X86ISD::SHRD;
18838 std::swap(Op0, Op1);
18839 std::swap(ShAmt0, ShAmt1);
18842 unsigned Bits = VT.getSizeInBits();
18843 if (ShAmt1.getOpcode() == ISD::SUB) {
18844 SDValue Sum = ShAmt1.getOperand(0);
18845 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18846 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18847 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18848 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18849 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18850 return DAG.getNode(Opc, DL, VT,
18852 DAG.getNode(ISD::TRUNCATE, DL,
18855 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18856 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18858 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18859 return DAG.getNode(Opc, DL, VT,
18860 N0.getOperand(0), N1.getOperand(0),
18861 DAG.getNode(ISD::TRUNCATE, DL,
18868 // Generate NEG and CMOV for integer abs.
18869 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18870 EVT VT = N->getValueType(0);
18872 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18873 // 8-bit integer abs to NEG and CMOV.
18874 if (VT.isInteger() && VT.getSizeInBits() == 8)
18877 SDValue N0 = N->getOperand(0);
18878 SDValue N1 = N->getOperand(1);
18881 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18882 // and change it to SUB and CMOV.
18883 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18884 N0.getOpcode() == ISD::ADD &&
18885 N0.getOperand(1) == N1 &&
18886 N1.getOpcode() == ISD::SRA &&
18887 N1.getOperand(0) == N0.getOperand(0))
18888 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18889 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18890 // Generate SUB & CMOV.
18891 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18892 DAG.getConstant(0, VT), N0.getOperand(0));
18894 SDValue Ops[] = { N0.getOperand(0), Neg,
18895 DAG.getConstant(X86::COND_GE, MVT::i8),
18896 SDValue(Neg.getNode(), 1) };
18897 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18898 Ops, array_lengthof(Ops));
18903 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18904 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18905 TargetLowering::DAGCombinerInfo &DCI,
18906 const X86Subtarget *Subtarget) {
18907 if (DCI.isBeforeLegalizeOps())
18910 if (Subtarget->hasCMov()) {
18911 SDValue RV = performIntegerAbsCombine(N, DAG);
18919 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18920 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18921 TargetLowering::DAGCombinerInfo &DCI,
18922 const X86Subtarget *Subtarget) {
18923 LoadSDNode *Ld = cast<LoadSDNode>(N);
18924 EVT RegVT = Ld->getValueType(0);
18925 EVT MemVT = Ld->getMemoryVT();
18927 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18928 unsigned RegSz = RegVT.getSizeInBits();
18930 // On Sandybridge unaligned 256bit loads are inefficient.
18931 ISD::LoadExtType Ext = Ld->getExtensionType();
18932 unsigned Alignment = Ld->getAlignment();
18933 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18934 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18935 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18936 unsigned NumElems = RegVT.getVectorNumElements();
18940 SDValue Ptr = Ld->getBasePtr();
18941 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18943 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18945 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18946 Ld->getPointerInfo(), Ld->isVolatile(),
18947 Ld->isNonTemporal(), Ld->isInvariant(),
18949 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18950 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18951 Ld->getPointerInfo(), Ld->isVolatile(),
18952 Ld->isNonTemporal(), Ld->isInvariant(),
18953 std::min(16U, Alignment));
18954 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18956 Load2.getValue(1));
18958 SDValue NewVec = DAG.getUNDEF(RegVT);
18959 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18960 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18961 return DCI.CombineTo(N, NewVec, TF, true);
18964 // If this is a vector EXT Load then attempt to optimize it using a
18965 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18966 // expansion is still better than scalar code.
18967 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18968 // emit a shuffle and a arithmetic shift.
18969 // TODO: It is possible to support ZExt by zeroing the undef values
18970 // during the shuffle phase or after the shuffle.
18971 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18972 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18973 assert(MemVT != RegVT && "Cannot extend to the same type");
18974 assert(MemVT.isVector() && "Must load a vector from memory");
18976 unsigned NumElems = RegVT.getVectorNumElements();
18977 unsigned MemSz = MemVT.getSizeInBits();
18978 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18980 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18983 // All sizes must be a power of two.
18984 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18987 // Attempt to load the original value using scalar loads.
18988 // Find the largest scalar type that divides the total loaded size.
18989 MVT SclrLoadTy = MVT::i8;
18990 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18991 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18992 MVT Tp = (MVT::SimpleValueType)tp;
18993 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18998 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18999 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19001 SclrLoadTy = MVT::f64;
19003 // Calculate the number of scalar loads that we need to perform
19004 // in order to load our vector from memory.
19005 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19006 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19009 unsigned loadRegZize = RegSz;
19010 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19013 // Represent our vector as a sequence of elements which are the
19014 // largest scalar that we can load.
19015 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19016 loadRegZize/SclrLoadTy.getSizeInBits());
19018 // Represent the data using the same element type that is stored in
19019 // memory. In practice, we ''widen'' MemVT.
19021 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19022 loadRegZize/MemVT.getScalarType().getSizeInBits());
19024 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19025 "Invalid vector type");
19027 // We can't shuffle using an illegal type.
19028 if (!TLI.isTypeLegal(WideVecVT))
19031 SmallVector<SDValue, 8> Chains;
19032 SDValue Ptr = Ld->getBasePtr();
19033 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19034 TLI.getPointerTy());
19035 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19037 for (unsigned i = 0; i < NumLoads; ++i) {
19038 // Perform a single load.
19039 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19040 Ptr, Ld->getPointerInfo(),
19041 Ld->isVolatile(), Ld->isNonTemporal(),
19042 Ld->isInvariant(), Ld->getAlignment());
19043 Chains.push_back(ScalarLoad.getValue(1));
19044 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19045 // another round of DAGCombining.
19047 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19049 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19050 ScalarLoad, DAG.getIntPtrConstant(i));
19052 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19055 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19058 // Bitcast the loaded value to a vector of the original element type, in
19059 // the size of the target vector type.
19060 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19061 unsigned SizeRatio = RegSz/MemSz;
19063 if (Ext == ISD::SEXTLOAD) {
19064 // If we have SSE4.1 we can directly emit a VSEXT node.
19065 if (Subtarget->hasSSE41()) {
19066 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19067 return DCI.CombineTo(N, Sext, TF, true);
19070 // Otherwise we'll shuffle the small elements in the high bits of the
19071 // larger type and perform an arithmetic shift. If the shift is not legal
19072 // it's better to scalarize.
19073 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19076 // Redistribute the loaded elements into the different locations.
19077 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19078 for (unsigned i = 0; i != NumElems; ++i)
19079 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19081 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19082 DAG.getUNDEF(WideVecVT),
19085 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19087 // Build the arithmetic shift.
19088 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19089 MemVT.getVectorElementType().getSizeInBits();
19090 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19091 DAG.getConstant(Amt, RegVT));
19093 return DCI.CombineTo(N, Shuff, TF, true);
19096 // Redistribute the loaded elements into the different locations.
19097 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19098 for (unsigned i = 0; i != NumElems; ++i)
19099 ShuffleVec[i*SizeRatio] = i;
19101 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19102 DAG.getUNDEF(WideVecVT),
19105 // Bitcast to the requested type.
19106 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19107 // Replace the original load with the new sequence
19108 // and return the new chain.
19109 return DCI.CombineTo(N, Shuff, TF, true);
19115 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19116 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19117 const X86Subtarget *Subtarget) {
19118 StoreSDNode *St = cast<StoreSDNode>(N);
19119 EVT VT = St->getValue().getValueType();
19120 EVT StVT = St->getMemoryVT();
19122 SDValue StoredVal = St->getOperand(1);
19123 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19125 // If we are saving a concatenation of two XMM registers, perform two stores.
19126 // On Sandy Bridge, 256-bit memory operations are executed by two
19127 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19128 // memory operation.
19129 unsigned Alignment = St->getAlignment();
19130 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19131 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19132 StVT == VT && !IsAligned) {
19133 unsigned NumElems = VT.getVectorNumElements();
19137 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19138 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19140 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19141 SDValue Ptr0 = St->getBasePtr();
19142 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19144 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19145 St->getPointerInfo(), St->isVolatile(),
19146 St->isNonTemporal(), Alignment);
19147 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19148 St->getPointerInfo(), St->isVolatile(),
19149 St->isNonTemporal(),
19150 std::min(16U, Alignment));
19151 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19154 // Optimize trunc store (of multiple scalars) to shuffle and store.
19155 // First, pack all of the elements in one place. Next, store to memory
19156 // in fewer chunks.
19157 if (St->isTruncatingStore() && VT.isVector()) {
19158 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19159 unsigned NumElems = VT.getVectorNumElements();
19160 assert(StVT != VT && "Cannot truncate to the same type");
19161 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19162 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19164 // From, To sizes and ElemCount must be pow of two
19165 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19166 // We are going to use the original vector elt for storing.
19167 // Accumulated smaller vector elements must be a multiple of the store size.
19168 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19170 unsigned SizeRatio = FromSz / ToSz;
19172 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19174 // Create a type on which we perform the shuffle
19175 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19176 StVT.getScalarType(), NumElems*SizeRatio);
19178 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19180 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19181 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19182 for (unsigned i = 0; i != NumElems; ++i)
19183 ShuffleVec[i] = i * SizeRatio;
19185 // Can't shuffle using an illegal type.
19186 if (!TLI.isTypeLegal(WideVecVT))
19189 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19190 DAG.getUNDEF(WideVecVT),
19192 // At this point all of the data is stored at the bottom of the
19193 // register. We now need to save it to mem.
19195 // Find the largest store unit
19196 MVT StoreType = MVT::i8;
19197 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19198 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19199 MVT Tp = (MVT::SimpleValueType)tp;
19200 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19204 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19205 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19206 (64 <= NumElems * ToSz))
19207 StoreType = MVT::f64;
19209 // Bitcast the original vector into a vector of store-size units
19210 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19211 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19212 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19213 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19214 SmallVector<SDValue, 8> Chains;
19215 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19216 TLI.getPointerTy());
19217 SDValue Ptr = St->getBasePtr();
19219 // Perform one or more big stores into memory.
19220 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19221 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19222 StoreType, ShuffWide,
19223 DAG.getIntPtrConstant(i));
19224 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19225 St->getPointerInfo(), St->isVolatile(),
19226 St->isNonTemporal(), St->getAlignment());
19227 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19228 Chains.push_back(Ch);
19231 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19235 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19236 // the FP state in cases where an emms may be missing.
19237 // A preferable solution to the general problem is to figure out the right
19238 // places to insert EMMS. This qualifies as a quick hack.
19240 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19241 if (VT.getSizeInBits() != 64)
19244 const Function *F = DAG.getMachineFunction().getFunction();
19245 bool NoImplicitFloatOps = F->getAttributes().
19246 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19247 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19248 && Subtarget->hasSSE2();
19249 if ((VT.isVector() ||
19250 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19251 isa<LoadSDNode>(St->getValue()) &&
19252 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19253 St->getChain().hasOneUse() && !St->isVolatile()) {
19254 SDNode* LdVal = St->getValue().getNode();
19255 LoadSDNode *Ld = nullptr;
19256 int TokenFactorIndex = -1;
19257 SmallVector<SDValue, 8> Ops;
19258 SDNode* ChainVal = St->getChain().getNode();
19259 // Must be a store of a load. We currently handle two cases: the load
19260 // is a direct child, and it's under an intervening TokenFactor. It is
19261 // possible to dig deeper under nested TokenFactors.
19262 if (ChainVal == LdVal)
19263 Ld = cast<LoadSDNode>(St->getChain());
19264 else if (St->getValue().hasOneUse() &&
19265 ChainVal->getOpcode() == ISD::TokenFactor) {
19266 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19267 if (ChainVal->getOperand(i).getNode() == LdVal) {
19268 TokenFactorIndex = i;
19269 Ld = cast<LoadSDNode>(St->getValue());
19271 Ops.push_back(ChainVal->getOperand(i));
19275 if (!Ld || !ISD::isNormalLoad(Ld))
19278 // If this is not the MMX case, i.e. we are just turning i64 load/store
19279 // into f64 load/store, avoid the transformation if there are multiple
19280 // uses of the loaded value.
19281 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19286 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19287 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19289 if (Subtarget->is64Bit() || F64IsLegal) {
19290 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19291 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19292 Ld->getPointerInfo(), Ld->isVolatile(),
19293 Ld->isNonTemporal(), Ld->isInvariant(),
19294 Ld->getAlignment());
19295 SDValue NewChain = NewLd.getValue(1);
19296 if (TokenFactorIndex != -1) {
19297 Ops.push_back(NewChain);
19298 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19301 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19302 St->getPointerInfo(),
19303 St->isVolatile(), St->isNonTemporal(),
19304 St->getAlignment());
19307 // Otherwise, lower to two pairs of 32-bit loads / stores.
19308 SDValue LoAddr = Ld->getBasePtr();
19309 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19310 DAG.getConstant(4, MVT::i32));
19312 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19313 Ld->getPointerInfo(),
19314 Ld->isVolatile(), Ld->isNonTemporal(),
19315 Ld->isInvariant(), Ld->getAlignment());
19316 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19317 Ld->getPointerInfo().getWithOffset(4),
19318 Ld->isVolatile(), Ld->isNonTemporal(),
19320 MinAlign(Ld->getAlignment(), 4));
19322 SDValue NewChain = LoLd.getValue(1);
19323 if (TokenFactorIndex != -1) {
19324 Ops.push_back(LoLd);
19325 Ops.push_back(HiLd);
19326 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19330 LoAddr = St->getBasePtr();
19331 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19332 DAG.getConstant(4, MVT::i32));
19334 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19335 St->getPointerInfo(),
19336 St->isVolatile(), St->isNonTemporal(),
19337 St->getAlignment());
19338 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19339 St->getPointerInfo().getWithOffset(4),
19341 St->isNonTemporal(),
19342 MinAlign(St->getAlignment(), 4));
19343 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19348 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19349 /// and return the operands for the horizontal operation in LHS and RHS. A
19350 /// horizontal operation performs the binary operation on successive elements
19351 /// of its first operand, then on successive elements of its second operand,
19352 /// returning the resulting values in a vector. For example, if
19353 /// A = < float a0, float a1, float a2, float a3 >
19355 /// B = < float b0, float b1, float b2, float b3 >
19356 /// then the result of doing a horizontal operation on A and B is
19357 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19358 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19359 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19360 /// set to A, RHS to B, and the routine returns 'true'.
19361 /// Note that the binary operation should have the property that if one of the
19362 /// operands is UNDEF then the result is UNDEF.
19363 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19364 // Look for the following pattern: if
19365 // A = < float a0, float a1, float a2, float a3 >
19366 // B = < float b0, float b1, float b2, float b3 >
19368 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19369 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19370 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19371 // which is A horizontal-op B.
19373 // At least one of the operands should be a vector shuffle.
19374 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19375 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19378 MVT VT = LHS.getSimpleValueType();
19380 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19381 "Unsupported vector type for horizontal add/sub");
19383 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19384 // operate independently on 128-bit lanes.
19385 unsigned NumElts = VT.getVectorNumElements();
19386 unsigned NumLanes = VT.getSizeInBits()/128;
19387 unsigned NumLaneElts = NumElts / NumLanes;
19388 assert((NumLaneElts % 2 == 0) &&
19389 "Vector type should have an even number of elements in each lane");
19390 unsigned HalfLaneElts = NumLaneElts/2;
19392 // View LHS in the form
19393 // LHS = VECTOR_SHUFFLE A, B, LMask
19394 // If LHS is not a shuffle then pretend it is the shuffle
19395 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19396 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19399 SmallVector<int, 16> LMask(NumElts);
19400 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19401 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19402 A = LHS.getOperand(0);
19403 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19404 B = LHS.getOperand(1);
19405 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19406 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19408 if (LHS.getOpcode() != ISD::UNDEF)
19410 for (unsigned i = 0; i != NumElts; ++i)
19414 // Likewise, view RHS in the form
19415 // RHS = VECTOR_SHUFFLE C, D, RMask
19417 SmallVector<int, 16> RMask(NumElts);
19418 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19419 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19420 C = RHS.getOperand(0);
19421 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19422 D = RHS.getOperand(1);
19423 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19424 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19426 if (RHS.getOpcode() != ISD::UNDEF)
19428 for (unsigned i = 0; i != NumElts; ++i)
19432 // Check that the shuffles are both shuffling the same vectors.
19433 if (!(A == C && B == D) && !(A == D && B == C))
19436 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19437 if (!A.getNode() && !B.getNode())
19440 // If A and B occur in reverse order in RHS, then "swap" them (which means
19441 // rewriting the mask).
19443 CommuteVectorShuffleMask(RMask, NumElts);
19445 // At this point LHS and RHS are equivalent to
19446 // LHS = VECTOR_SHUFFLE A, B, LMask
19447 // RHS = VECTOR_SHUFFLE A, B, RMask
19448 // Check that the masks correspond to performing a horizontal operation.
19449 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19450 for (unsigned i = 0; i != NumLaneElts; ++i) {
19451 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19453 // Ignore any UNDEF components.
19454 if (LIdx < 0 || RIdx < 0 ||
19455 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19456 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19459 // Check that successive elements are being operated on. If not, this is
19460 // not a horizontal operation.
19461 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19462 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19463 if (!(LIdx == Index && RIdx == Index + 1) &&
19464 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19469 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19470 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19474 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19475 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19476 const X86Subtarget *Subtarget) {
19477 EVT VT = N->getValueType(0);
19478 SDValue LHS = N->getOperand(0);
19479 SDValue RHS = N->getOperand(1);
19481 // Try to synthesize horizontal adds from adds of shuffles.
19482 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19483 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19484 isHorizontalBinOp(LHS, RHS, true))
19485 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19489 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19490 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19491 const X86Subtarget *Subtarget) {
19492 EVT VT = N->getValueType(0);
19493 SDValue LHS = N->getOperand(0);
19494 SDValue RHS = N->getOperand(1);
19496 // Try to synthesize horizontal subs from subs of shuffles.
19497 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19498 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19499 isHorizontalBinOp(LHS, RHS, false))
19500 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19504 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19505 /// X86ISD::FXOR nodes.
19506 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19507 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19508 // F[X]OR(0.0, x) -> x
19509 // F[X]OR(x, 0.0) -> x
19510 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19511 if (C->getValueAPF().isPosZero())
19512 return N->getOperand(1);
19513 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19514 if (C->getValueAPF().isPosZero())
19515 return N->getOperand(0);
19519 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19520 /// X86ISD::FMAX nodes.
19521 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19522 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19524 // Only perform optimizations if UnsafeMath is used.
19525 if (!DAG.getTarget().Options.UnsafeFPMath)
19528 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19529 // into FMINC and FMAXC, which are Commutative operations.
19530 unsigned NewOp = 0;
19531 switch (N->getOpcode()) {
19532 default: llvm_unreachable("unknown opcode");
19533 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19534 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19537 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19538 N->getOperand(0), N->getOperand(1));
19541 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19542 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19543 // FAND(0.0, x) -> 0.0
19544 // FAND(x, 0.0) -> 0.0
19545 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19546 if (C->getValueAPF().isPosZero())
19547 return N->getOperand(0);
19548 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19549 if (C->getValueAPF().isPosZero())
19550 return N->getOperand(1);
19554 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19555 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19556 // FANDN(x, 0.0) -> 0.0
19557 // FANDN(0.0, x) -> x
19558 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19559 if (C->getValueAPF().isPosZero())
19560 return N->getOperand(1);
19561 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19562 if (C->getValueAPF().isPosZero())
19563 return N->getOperand(1);
19567 static SDValue PerformBTCombine(SDNode *N,
19569 TargetLowering::DAGCombinerInfo &DCI) {
19570 // BT ignores high bits in the bit index operand.
19571 SDValue Op1 = N->getOperand(1);
19572 if (Op1.hasOneUse()) {
19573 unsigned BitWidth = Op1.getValueSizeInBits();
19574 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19575 APInt KnownZero, KnownOne;
19576 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19577 !DCI.isBeforeLegalizeOps());
19578 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19579 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19580 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19581 DCI.CommitTargetLoweringOpt(TLO);
19586 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19587 SDValue Op = N->getOperand(0);
19588 if (Op.getOpcode() == ISD::BITCAST)
19589 Op = Op.getOperand(0);
19590 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19591 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19592 VT.getVectorElementType().getSizeInBits() ==
19593 OpVT.getVectorElementType().getSizeInBits()) {
19594 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19599 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19600 const X86Subtarget *Subtarget) {
19601 EVT VT = N->getValueType(0);
19602 if (!VT.isVector())
19605 SDValue N0 = N->getOperand(0);
19606 SDValue N1 = N->getOperand(1);
19607 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19610 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19611 // both SSE and AVX2 since there is no sign-extended shift right
19612 // operation on a vector with 64-bit elements.
19613 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19614 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19615 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19616 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19617 SDValue N00 = N0.getOperand(0);
19619 // EXTLOAD has a better solution on AVX2,
19620 // it may be replaced with X86ISD::VSEXT node.
19621 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19622 if (!ISD::isNormalLoad(N00.getNode()))
19625 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19626 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19628 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19634 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19635 TargetLowering::DAGCombinerInfo &DCI,
19636 const X86Subtarget *Subtarget) {
19637 if (!DCI.isBeforeLegalizeOps())
19640 if (!Subtarget->hasFp256())
19643 EVT VT = N->getValueType(0);
19644 if (VT.isVector() && VT.getSizeInBits() == 256) {
19645 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19653 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19654 const X86Subtarget* Subtarget) {
19656 EVT VT = N->getValueType(0);
19658 // Let legalize expand this if it isn't a legal type yet.
19659 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19662 EVT ScalarVT = VT.getScalarType();
19663 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19664 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19667 SDValue A = N->getOperand(0);
19668 SDValue B = N->getOperand(1);
19669 SDValue C = N->getOperand(2);
19671 bool NegA = (A.getOpcode() == ISD::FNEG);
19672 bool NegB = (B.getOpcode() == ISD::FNEG);
19673 bool NegC = (C.getOpcode() == ISD::FNEG);
19675 // Negative multiplication when NegA xor NegB
19676 bool NegMul = (NegA != NegB);
19678 A = A.getOperand(0);
19680 B = B.getOperand(0);
19682 C = C.getOperand(0);
19686 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19688 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19690 return DAG.getNode(Opcode, dl, VT, A, B, C);
19693 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19694 TargetLowering::DAGCombinerInfo &DCI,
19695 const X86Subtarget *Subtarget) {
19696 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19697 // (and (i32 x86isd::setcc_carry), 1)
19698 // This eliminates the zext. This transformation is necessary because
19699 // ISD::SETCC is always legalized to i8.
19701 SDValue N0 = N->getOperand(0);
19702 EVT VT = N->getValueType(0);
19704 if (N0.getOpcode() == ISD::AND &&
19706 N0.getOperand(0).hasOneUse()) {
19707 SDValue N00 = N0.getOperand(0);
19708 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19709 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19710 if (!C || C->getZExtValue() != 1)
19712 return DAG.getNode(ISD::AND, dl, VT,
19713 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19714 N00.getOperand(0), N00.getOperand(1)),
19715 DAG.getConstant(1, VT));
19719 if (N0.getOpcode() == ISD::TRUNCATE &&
19721 N0.getOperand(0).hasOneUse()) {
19722 SDValue N00 = N0.getOperand(0);
19723 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19724 return DAG.getNode(ISD::AND, dl, VT,
19725 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19726 N00.getOperand(0), N00.getOperand(1)),
19727 DAG.getConstant(1, VT));
19730 if (VT.is256BitVector()) {
19731 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19739 // Optimize x == -y --> x+y == 0
19740 // x != -y --> x+y != 0
19741 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19742 const X86Subtarget* Subtarget) {
19743 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19744 SDValue LHS = N->getOperand(0);
19745 SDValue RHS = N->getOperand(1);
19746 EVT VT = N->getValueType(0);
19749 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19750 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19751 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19752 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19753 LHS.getValueType(), RHS, LHS.getOperand(1));
19754 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19755 addV, DAG.getConstant(0, addV.getValueType()), CC);
19757 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19758 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19759 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19760 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19761 RHS.getValueType(), LHS, RHS.getOperand(1));
19762 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19763 addV, DAG.getConstant(0, addV.getValueType()), CC);
19766 if (VT.getScalarType() == MVT::i1) {
19767 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19768 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19769 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19770 if (!IsSEXT0 && !IsVZero0)
19772 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19773 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19774 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19776 if (!IsSEXT1 && !IsVZero1)
19779 if (IsSEXT0 && IsVZero1) {
19780 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19781 if (CC == ISD::SETEQ)
19782 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19783 return LHS.getOperand(0);
19785 if (IsSEXT1 && IsVZero0) {
19786 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19787 if (CC == ISD::SETEQ)
19788 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19789 return RHS.getOperand(0);
19796 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19797 // as "sbb reg,reg", since it can be extended without zext and produces
19798 // an all-ones bit which is more useful than 0/1 in some cases.
19799 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19802 return DAG.getNode(ISD::AND, DL, VT,
19803 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19804 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19805 DAG.getConstant(1, VT));
19806 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19807 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19808 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19809 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19812 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19813 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19814 TargetLowering::DAGCombinerInfo &DCI,
19815 const X86Subtarget *Subtarget) {
19817 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19818 SDValue EFLAGS = N->getOperand(1);
19820 if (CC == X86::COND_A) {
19821 // Try to convert COND_A into COND_B in an attempt to facilitate
19822 // materializing "setb reg".
19824 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19825 // cannot take an immediate as its first operand.
19827 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19828 EFLAGS.getValueType().isInteger() &&
19829 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19830 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19831 EFLAGS.getNode()->getVTList(),
19832 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19833 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19834 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19838 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19839 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19841 if (CC == X86::COND_B)
19842 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19846 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19847 if (Flags.getNode()) {
19848 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19849 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19855 // Optimize branch condition evaluation.
19857 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19858 TargetLowering::DAGCombinerInfo &DCI,
19859 const X86Subtarget *Subtarget) {
19861 SDValue Chain = N->getOperand(0);
19862 SDValue Dest = N->getOperand(1);
19863 SDValue EFLAGS = N->getOperand(3);
19864 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19868 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19869 if (Flags.getNode()) {
19870 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19871 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19878 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19879 const X86TargetLowering *XTLI) {
19880 SDValue Op0 = N->getOperand(0);
19881 EVT InVT = Op0->getValueType(0);
19883 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19884 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19886 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19887 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19888 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19891 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19892 // a 32-bit target where SSE doesn't support i64->FP operations.
19893 if (Op0.getOpcode() == ISD::LOAD) {
19894 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19895 EVT VT = Ld->getValueType(0);
19896 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19897 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19898 !XTLI->getSubtarget()->is64Bit() &&
19900 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19901 Ld->getChain(), Op0, DAG);
19902 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19909 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19910 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19911 X86TargetLowering::DAGCombinerInfo &DCI) {
19912 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19913 // the result is either zero or one (depending on the input carry bit).
19914 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19915 if (X86::isZeroNode(N->getOperand(0)) &&
19916 X86::isZeroNode(N->getOperand(1)) &&
19917 // We don't have a good way to replace an EFLAGS use, so only do this when
19919 SDValue(N, 1).use_empty()) {
19921 EVT VT = N->getValueType(0);
19922 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19923 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19924 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19925 DAG.getConstant(X86::COND_B,MVT::i8),
19927 DAG.getConstant(1, VT));
19928 return DCI.CombineTo(N, Res1, CarryOut);
19934 // fold (add Y, (sete X, 0)) -> adc 0, Y
19935 // (add Y, (setne X, 0)) -> sbb -1, Y
19936 // (sub (sete X, 0), Y) -> sbb 0, Y
19937 // (sub (setne X, 0), Y) -> adc -1, Y
19938 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19941 // Look through ZExts.
19942 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19943 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19946 SDValue SetCC = Ext.getOperand(0);
19947 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19950 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19951 if (CC != X86::COND_E && CC != X86::COND_NE)
19954 SDValue Cmp = SetCC.getOperand(1);
19955 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19956 !X86::isZeroNode(Cmp.getOperand(1)) ||
19957 !Cmp.getOperand(0).getValueType().isInteger())
19960 SDValue CmpOp0 = Cmp.getOperand(0);
19961 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19962 DAG.getConstant(1, CmpOp0.getValueType()));
19964 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19965 if (CC == X86::COND_NE)
19966 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19967 DL, OtherVal.getValueType(), OtherVal,
19968 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19969 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19970 DL, OtherVal.getValueType(), OtherVal,
19971 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19974 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19975 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19976 const X86Subtarget *Subtarget) {
19977 EVT VT = N->getValueType(0);
19978 SDValue Op0 = N->getOperand(0);
19979 SDValue Op1 = N->getOperand(1);
19981 // Try to synthesize horizontal adds from adds of shuffles.
19982 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19983 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19984 isHorizontalBinOp(Op0, Op1, true))
19985 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19987 return OptimizeConditionalInDecrement(N, DAG);
19990 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19991 const X86Subtarget *Subtarget) {
19992 SDValue Op0 = N->getOperand(0);
19993 SDValue Op1 = N->getOperand(1);
19995 // X86 can't encode an immediate LHS of a sub. See if we can push the
19996 // negation into a preceding instruction.
19997 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19998 // If the RHS of the sub is a XOR with one use and a constant, invert the
19999 // immediate. Then add one to the LHS of the sub so we can turn
20000 // X-Y -> X+~Y+1, saving one register.
20001 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20002 isa<ConstantSDNode>(Op1.getOperand(1))) {
20003 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20004 EVT VT = Op0.getValueType();
20005 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20007 DAG.getConstant(~XorC, VT));
20008 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20009 DAG.getConstant(C->getAPIntValue()+1, VT));
20013 // Try to synthesize horizontal adds from adds of shuffles.
20014 EVT VT = N->getValueType(0);
20015 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20016 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20017 isHorizontalBinOp(Op0, Op1, true))
20018 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20020 return OptimizeConditionalInDecrement(N, DAG);
20023 /// performVZEXTCombine - Performs build vector combines
20024 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20025 TargetLowering::DAGCombinerInfo &DCI,
20026 const X86Subtarget *Subtarget) {
20027 // (vzext (bitcast (vzext (x)) -> (vzext x)
20028 SDValue In = N->getOperand(0);
20029 while (In.getOpcode() == ISD::BITCAST)
20030 In = In.getOperand(0);
20032 if (In.getOpcode() != X86ISD::VZEXT)
20035 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20039 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20040 DAGCombinerInfo &DCI) const {
20041 SelectionDAG &DAG = DCI.DAG;
20042 switch (N->getOpcode()) {
20044 case ISD::EXTRACT_VECTOR_ELT:
20045 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20047 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20048 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20049 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20050 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20051 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20052 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20055 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20056 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20057 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20058 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20059 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20060 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20061 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20062 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20063 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20065 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20067 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20068 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20069 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20070 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20071 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20072 case ISD::ANY_EXTEND:
20073 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20074 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20075 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20076 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20077 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20078 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20079 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20080 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20081 case X86ISD::SHUFP: // Handle all target specific shuffles
20082 case X86ISD::PALIGNR:
20083 case X86ISD::UNPCKH:
20084 case X86ISD::UNPCKL:
20085 case X86ISD::MOVHLPS:
20086 case X86ISD::MOVLHPS:
20087 case X86ISD::PSHUFD:
20088 case X86ISD::PSHUFHW:
20089 case X86ISD::PSHUFLW:
20090 case X86ISD::MOVSS:
20091 case X86ISD::MOVSD:
20092 case X86ISD::VPERMILP:
20093 case X86ISD::VPERM2X128:
20094 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20095 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20101 /// isTypeDesirableForOp - Return true if the target has native support for
20102 /// the specified value type and it is 'desirable' to use the type for the
20103 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20104 /// instruction encodings are longer and some i16 instructions are slow.
20105 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20106 if (!isTypeLegal(VT))
20108 if (VT != MVT::i16)
20115 case ISD::SIGN_EXTEND:
20116 case ISD::ZERO_EXTEND:
20117 case ISD::ANY_EXTEND:
20130 /// IsDesirableToPromoteOp - This method query the target whether it is
20131 /// beneficial for dag combiner to promote the specified node. If true, it
20132 /// should return the desired promotion type by reference.
20133 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20134 EVT VT = Op.getValueType();
20135 if (VT != MVT::i16)
20138 bool Promote = false;
20139 bool Commute = false;
20140 switch (Op.getOpcode()) {
20143 LoadSDNode *LD = cast<LoadSDNode>(Op);
20144 // If the non-extending load has a single use and it's not live out, then it
20145 // might be folded.
20146 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20147 Op.hasOneUse()*/) {
20148 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20149 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20150 // The only case where we'd want to promote LOAD (rather then it being
20151 // promoted as an operand is when it's only use is liveout.
20152 if (UI->getOpcode() != ISD::CopyToReg)
20159 case ISD::SIGN_EXTEND:
20160 case ISD::ZERO_EXTEND:
20161 case ISD::ANY_EXTEND:
20166 SDValue N0 = Op.getOperand(0);
20167 // Look out for (store (shl (load), x)).
20168 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20181 SDValue N0 = Op.getOperand(0);
20182 SDValue N1 = Op.getOperand(1);
20183 if (!Commute && MayFoldLoad(N1))
20185 // Avoid disabling potential load folding opportunities.
20186 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20188 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20198 //===----------------------------------------------------------------------===//
20199 // X86 Inline Assembly Support
20200 //===----------------------------------------------------------------------===//
20203 // Helper to match a string separated by whitespace.
20204 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20205 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20207 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20208 StringRef piece(*args[i]);
20209 if (!s.startswith(piece)) // Check if the piece matches.
20212 s = s.substr(piece.size());
20213 StringRef::size_type pos = s.find_first_not_of(" \t");
20214 if (pos == 0) // We matched a prefix.
20222 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20225 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20227 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20228 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20229 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20230 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20232 if (AsmPieces.size() == 3)
20234 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20241 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20242 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20244 std::string AsmStr = IA->getAsmString();
20246 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20247 if (!Ty || Ty->getBitWidth() % 16 != 0)
20250 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20251 SmallVector<StringRef, 4> AsmPieces;
20252 SplitString(AsmStr, AsmPieces, ";\n");
20254 switch (AsmPieces.size()) {
20255 default: return false;
20257 // FIXME: this should verify that we are targeting a 486 or better. If not,
20258 // we will turn this bswap into something that will be lowered to logical
20259 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20260 // lower so don't worry about this.
20262 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20263 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20264 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20265 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20266 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20267 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20268 // No need to check constraints, nothing other than the equivalent of
20269 // "=r,0" would be valid here.
20270 return IntrinsicLowering::LowerToByteSwap(CI);
20273 // rorw $$8, ${0:w} --> llvm.bswap.i16
20274 if (CI->getType()->isIntegerTy(16) &&
20275 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20276 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20277 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20279 const std::string &ConstraintsStr = IA->getConstraintString();
20280 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20281 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20282 if (clobbersFlagRegisters(AsmPieces))
20283 return IntrinsicLowering::LowerToByteSwap(CI);
20287 if (CI->getType()->isIntegerTy(32) &&
20288 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20289 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20290 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20291 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20293 const std::string &ConstraintsStr = IA->getConstraintString();
20294 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20295 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20296 if (clobbersFlagRegisters(AsmPieces))
20297 return IntrinsicLowering::LowerToByteSwap(CI);
20300 if (CI->getType()->isIntegerTy(64)) {
20301 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20302 if (Constraints.size() >= 2 &&
20303 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20304 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20305 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20306 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20307 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20308 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20309 return IntrinsicLowering::LowerToByteSwap(CI);
20317 /// getConstraintType - Given a constraint letter, return the type of
20318 /// constraint it is for this target.
20319 X86TargetLowering::ConstraintType
20320 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20321 if (Constraint.size() == 1) {
20322 switch (Constraint[0]) {
20333 return C_RegisterClass;
20357 return TargetLowering::getConstraintType(Constraint);
20360 /// Examine constraint type and operand type and determine a weight value.
20361 /// This object must already have been set up with the operand type
20362 /// and the current alternative constraint selected.
20363 TargetLowering::ConstraintWeight
20364 X86TargetLowering::getSingleConstraintMatchWeight(
20365 AsmOperandInfo &info, const char *constraint) const {
20366 ConstraintWeight weight = CW_Invalid;
20367 Value *CallOperandVal = info.CallOperandVal;
20368 // If we don't have a value, we can't do a match,
20369 // but allow it at the lowest weight.
20370 if (!CallOperandVal)
20372 Type *type = CallOperandVal->getType();
20373 // Look at the constraint type.
20374 switch (*constraint) {
20376 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20387 if (CallOperandVal->getType()->isIntegerTy())
20388 weight = CW_SpecificReg;
20393 if (type->isFloatingPointTy())
20394 weight = CW_SpecificReg;
20397 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20398 weight = CW_SpecificReg;
20402 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20403 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20404 weight = CW_Register;
20407 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20408 if (C->getZExtValue() <= 31)
20409 weight = CW_Constant;
20413 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20414 if (C->getZExtValue() <= 63)
20415 weight = CW_Constant;
20419 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20420 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20421 weight = CW_Constant;
20425 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20426 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20427 weight = CW_Constant;
20431 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20432 if (C->getZExtValue() <= 3)
20433 weight = CW_Constant;
20437 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20438 if (C->getZExtValue() <= 0xff)
20439 weight = CW_Constant;
20444 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20445 weight = CW_Constant;
20449 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20450 if ((C->getSExtValue() >= -0x80000000LL) &&
20451 (C->getSExtValue() <= 0x7fffffffLL))
20452 weight = CW_Constant;
20456 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20457 if (C->getZExtValue() <= 0xffffffff)
20458 weight = CW_Constant;
20465 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20466 /// with another that has more specific requirements based on the type of the
20467 /// corresponding operand.
20468 const char *X86TargetLowering::
20469 LowerXConstraint(EVT ConstraintVT) const {
20470 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20471 // 'f' like normal targets.
20472 if (ConstraintVT.isFloatingPoint()) {
20473 if (Subtarget->hasSSE2())
20475 if (Subtarget->hasSSE1())
20479 return TargetLowering::LowerXConstraint(ConstraintVT);
20482 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20483 /// vector. If it is invalid, don't add anything to Ops.
20484 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20485 std::string &Constraint,
20486 std::vector<SDValue>&Ops,
20487 SelectionDAG &DAG) const {
20490 // Only support length 1 constraints for now.
20491 if (Constraint.length() > 1) return;
20493 char ConstraintLetter = Constraint[0];
20494 switch (ConstraintLetter) {
20497 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20498 if (C->getZExtValue() <= 31) {
20499 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20505 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20506 if (C->getZExtValue() <= 63) {
20507 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20513 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20514 if (isInt<8>(C->getSExtValue())) {
20515 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20521 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20522 if (C->getZExtValue() <= 255) {
20523 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20529 // 32-bit signed value
20530 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20531 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20532 C->getSExtValue())) {
20533 // Widen to 64 bits here to get it sign extended.
20534 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20537 // FIXME gcc accepts some relocatable values here too, but only in certain
20538 // memory models; it's complicated.
20543 // 32-bit unsigned value
20544 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20545 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20546 C->getZExtValue())) {
20547 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20551 // FIXME gcc accepts some relocatable values here too, but only in certain
20552 // memory models; it's complicated.
20556 // Literal immediates are always ok.
20557 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20558 // Widen to 64 bits here to get it sign extended.
20559 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20563 // In any sort of PIC mode addresses need to be computed at runtime by
20564 // adding in a register or some sort of table lookup. These can't
20565 // be used as immediates.
20566 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20569 // If we are in non-pic codegen mode, we allow the address of a global (with
20570 // an optional displacement) to be used with 'i'.
20571 GlobalAddressSDNode *GA = nullptr;
20572 int64_t Offset = 0;
20574 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20576 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20577 Offset += GA->getOffset();
20579 } else if (Op.getOpcode() == ISD::ADD) {
20580 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20581 Offset += C->getZExtValue();
20582 Op = Op.getOperand(0);
20585 } else if (Op.getOpcode() == ISD::SUB) {
20586 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20587 Offset += -C->getZExtValue();
20588 Op = Op.getOperand(0);
20593 // Otherwise, this isn't something we can handle, reject it.
20597 const GlobalValue *GV = GA->getGlobal();
20598 // If we require an extra load to get this address, as in PIC mode, we
20599 // can't accept it.
20600 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20601 getTargetMachine())))
20604 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20605 GA->getValueType(0), Offset);
20610 if (Result.getNode()) {
20611 Ops.push_back(Result);
20614 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20617 std::pair<unsigned, const TargetRegisterClass*>
20618 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20620 // First, see if this is a constraint that directly corresponds to an LLVM
20622 if (Constraint.size() == 1) {
20623 // GCC Constraint Letters
20624 switch (Constraint[0]) {
20626 // TODO: Slight differences here in allocation order and leaving
20627 // RIP in the class. Do they matter any more here than they do
20628 // in the normal allocation?
20629 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20630 if (Subtarget->is64Bit()) {
20631 if (VT == MVT::i32 || VT == MVT::f32)
20632 return std::make_pair(0U, &X86::GR32RegClass);
20633 if (VT == MVT::i16)
20634 return std::make_pair(0U, &X86::GR16RegClass);
20635 if (VT == MVT::i8 || VT == MVT::i1)
20636 return std::make_pair(0U, &X86::GR8RegClass);
20637 if (VT == MVT::i64 || VT == MVT::f64)
20638 return std::make_pair(0U, &X86::GR64RegClass);
20641 // 32-bit fallthrough
20642 case 'Q': // Q_REGS
20643 if (VT == MVT::i32 || VT == MVT::f32)
20644 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20645 if (VT == MVT::i16)
20646 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20647 if (VT == MVT::i8 || VT == MVT::i1)
20648 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20649 if (VT == MVT::i64)
20650 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20652 case 'r': // GENERAL_REGS
20653 case 'l': // INDEX_REGS
20654 if (VT == MVT::i8 || VT == MVT::i1)
20655 return std::make_pair(0U, &X86::GR8RegClass);
20656 if (VT == MVT::i16)
20657 return std::make_pair(0U, &X86::GR16RegClass);
20658 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20659 return std::make_pair(0U, &X86::GR32RegClass);
20660 return std::make_pair(0U, &X86::GR64RegClass);
20661 case 'R': // LEGACY_REGS
20662 if (VT == MVT::i8 || VT == MVT::i1)
20663 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20664 if (VT == MVT::i16)
20665 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20666 if (VT == MVT::i32 || !Subtarget->is64Bit())
20667 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20668 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20669 case 'f': // FP Stack registers.
20670 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20671 // value to the correct fpstack register class.
20672 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20673 return std::make_pair(0U, &X86::RFP32RegClass);
20674 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20675 return std::make_pair(0U, &X86::RFP64RegClass);
20676 return std::make_pair(0U, &X86::RFP80RegClass);
20677 case 'y': // MMX_REGS if MMX allowed.
20678 if (!Subtarget->hasMMX()) break;
20679 return std::make_pair(0U, &X86::VR64RegClass);
20680 case 'Y': // SSE_REGS if SSE2 allowed
20681 if (!Subtarget->hasSSE2()) break;
20683 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20684 if (!Subtarget->hasSSE1()) break;
20686 switch (VT.SimpleTy) {
20688 // Scalar SSE types.
20691 return std::make_pair(0U, &X86::FR32RegClass);
20694 return std::make_pair(0U, &X86::FR64RegClass);
20702 return std::make_pair(0U, &X86::VR128RegClass);
20710 return std::make_pair(0U, &X86::VR256RegClass);
20715 return std::make_pair(0U, &X86::VR512RegClass);
20721 // Use the default implementation in TargetLowering to convert the register
20722 // constraint into a member of a register class.
20723 std::pair<unsigned, const TargetRegisterClass*> Res;
20724 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20726 // Not found as a standard register?
20728 // Map st(0) -> st(7) -> ST0
20729 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20730 tolower(Constraint[1]) == 's' &&
20731 tolower(Constraint[2]) == 't' &&
20732 Constraint[3] == '(' &&
20733 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20734 Constraint[5] == ')' &&
20735 Constraint[6] == '}') {
20737 Res.first = X86::ST0+Constraint[4]-'0';
20738 Res.second = &X86::RFP80RegClass;
20742 // GCC allows "st(0)" to be called just plain "st".
20743 if (StringRef("{st}").equals_lower(Constraint)) {
20744 Res.first = X86::ST0;
20745 Res.second = &X86::RFP80RegClass;
20750 if (StringRef("{flags}").equals_lower(Constraint)) {
20751 Res.first = X86::EFLAGS;
20752 Res.second = &X86::CCRRegClass;
20756 // 'A' means EAX + EDX.
20757 if (Constraint == "A") {
20758 Res.first = X86::EAX;
20759 Res.second = &X86::GR32_ADRegClass;
20765 // Otherwise, check to see if this is a register class of the wrong value
20766 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20767 // turn into {ax},{dx}.
20768 if (Res.second->hasType(VT))
20769 return Res; // Correct type already, nothing to do.
20771 // All of the single-register GCC register classes map their values onto
20772 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20773 // really want an 8-bit or 32-bit register, map to the appropriate register
20774 // class and return the appropriate register.
20775 if (Res.second == &X86::GR16RegClass) {
20776 if (VT == MVT::i8 || VT == MVT::i1) {
20777 unsigned DestReg = 0;
20778 switch (Res.first) {
20780 case X86::AX: DestReg = X86::AL; break;
20781 case X86::DX: DestReg = X86::DL; break;
20782 case X86::CX: DestReg = X86::CL; break;
20783 case X86::BX: DestReg = X86::BL; break;
20786 Res.first = DestReg;
20787 Res.second = &X86::GR8RegClass;
20789 } else if (VT == MVT::i32 || VT == MVT::f32) {
20790 unsigned DestReg = 0;
20791 switch (Res.first) {
20793 case X86::AX: DestReg = X86::EAX; break;
20794 case X86::DX: DestReg = X86::EDX; break;
20795 case X86::CX: DestReg = X86::ECX; break;
20796 case X86::BX: DestReg = X86::EBX; break;
20797 case X86::SI: DestReg = X86::ESI; break;
20798 case X86::DI: DestReg = X86::EDI; break;
20799 case X86::BP: DestReg = X86::EBP; break;
20800 case X86::SP: DestReg = X86::ESP; break;
20803 Res.first = DestReg;
20804 Res.second = &X86::GR32RegClass;
20806 } else if (VT == MVT::i64 || VT == MVT::f64) {
20807 unsigned DestReg = 0;
20808 switch (Res.first) {
20810 case X86::AX: DestReg = X86::RAX; break;
20811 case X86::DX: DestReg = X86::RDX; break;
20812 case X86::CX: DestReg = X86::RCX; break;
20813 case X86::BX: DestReg = X86::RBX; break;
20814 case X86::SI: DestReg = X86::RSI; break;
20815 case X86::DI: DestReg = X86::RDI; break;
20816 case X86::BP: DestReg = X86::RBP; break;
20817 case X86::SP: DestReg = X86::RSP; break;
20820 Res.first = DestReg;
20821 Res.second = &X86::GR64RegClass;
20824 } else if (Res.second == &X86::FR32RegClass ||
20825 Res.second == &X86::FR64RegClass ||
20826 Res.second == &X86::VR128RegClass ||
20827 Res.second == &X86::VR256RegClass ||
20828 Res.second == &X86::FR32XRegClass ||
20829 Res.second == &X86::FR64XRegClass ||
20830 Res.second == &X86::VR128XRegClass ||
20831 Res.second == &X86::VR256XRegClass ||
20832 Res.second == &X86::VR512RegClass) {
20833 // Handle references to XMM physical registers that got mapped into the
20834 // wrong class. This can happen with constraints like {xmm0} where the
20835 // target independent register mapper will just pick the first match it can
20836 // find, ignoring the required type.
20838 if (VT == MVT::f32 || VT == MVT::i32)
20839 Res.second = &X86::FR32RegClass;
20840 else if (VT == MVT::f64 || VT == MVT::i64)
20841 Res.second = &X86::FR64RegClass;
20842 else if (X86::VR128RegClass.hasType(VT))
20843 Res.second = &X86::VR128RegClass;
20844 else if (X86::VR256RegClass.hasType(VT))
20845 Res.second = &X86::VR256RegClass;
20846 else if (X86::VR512RegClass.hasType(VT))
20847 Res.second = &X86::VR512RegClass;
20853 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20855 // Scaling factors are not free at all.
20856 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20857 // will take 2 allocations instead of 1 for plain addressing mode,
20858 // i.e. inst (reg1).
20859 if (isLegalAddressingMode(AM, Ty))
20860 // Scale represents reg2 * scale, thus account for 1
20861 // as soon as we use a second register.
20862 return AM.Scale != 0;