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, 0);
270 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
271 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
272 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
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::UMUL_LOHI, VT, Expand);
830 setOperationAction(ISD::SDIVREM, VT, Expand);
831 setOperationAction(ISD::UDIVREM, VT, Expand);
832 setOperationAction(ISD::FPOW, VT, Expand);
833 setOperationAction(ISD::CTPOP, VT, Expand);
834 setOperationAction(ISD::CTTZ, VT, Expand);
835 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
836 setOperationAction(ISD::CTLZ, VT, Expand);
837 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
838 setOperationAction(ISD::SHL, VT, Expand);
839 setOperationAction(ISD::SRA, VT, Expand);
840 setOperationAction(ISD::SRL, VT, Expand);
841 setOperationAction(ISD::ROTL, VT, Expand);
842 setOperationAction(ISD::ROTR, VT, Expand);
843 setOperationAction(ISD::BSWAP, VT, Expand);
844 setOperationAction(ISD::SETCC, VT, Expand);
845 setOperationAction(ISD::FLOG, VT, Expand);
846 setOperationAction(ISD::FLOG2, VT, Expand);
847 setOperationAction(ISD::FLOG10, VT, Expand);
848 setOperationAction(ISD::FEXP, VT, Expand);
849 setOperationAction(ISD::FEXP2, VT, Expand);
850 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
851 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
852 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
853 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
854 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
855 setOperationAction(ISD::TRUNCATE, VT, Expand);
856 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
857 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
858 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
859 setOperationAction(ISD::VSELECT, VT, Expand);
860 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
861 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
862 setTruncStoreAction(VT,
863 (MVT::SimpleValueType)InnerVT, Expand);
864 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
865 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
866 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
869 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
870 // with -msoft-float, disable use of MMX as well.
871 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
872 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
873 // No operations on x86mmx supported, everything uses intrinsics.
876 // MMX-sized vectors (other than x86mmx) are expected to be expanded
877 // into smaller operations.
878 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
879 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
880 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
881 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
882 setOperationAction(ISD::AND, MVT::v8i8, Expand);
883 setOperationAction(ISD::AND, MVT::v4i16, Expand);
884 setOperationAction(ISD::AND, MVT::v2i32, Expand);
885 setOperationAction(ISD::AND, MVT::v1i64, Expand);
886 setOperationAction(ISD::OR, MVT::v8i8, Expand);
887 setOperationAction(ISD::OR, MVT::v4i16, Expand);
888 setOperationAction(ISD::OR, MVT::v2i32, Expand);
889 setOperationAction(ISD::OR, MVT::v1i64, Expand);
890 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
891 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
892 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
893 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
894 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
895 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
898 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
899 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
900 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
901 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
902 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
903 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
904 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
908 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
909 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
911 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
912 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
913 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
914 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
915 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
916 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
917 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
918 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
919 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
920 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
921 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
922 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
925 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
926 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
928 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
929 // registers cannot be used even for integer operations.
930 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
931 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
932 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
933 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
935 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
936 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
937 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
938 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
939 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
940 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
941 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
942 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
943 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
944 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
945 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
946 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
947 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
948 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
949 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
950 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
951 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
952 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
954 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
955 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
956 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
957 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
959 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
960 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
961 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
962 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
965 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
966 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
967 MVT VT = (MVT::SimpleValueType)i;
968 // Do not attempt to custom lower non-power-of-2 vectors
969 if (!isPowerOf2_32(VT.getVectorNumElements()))
971 // Do not attempt to custom lower non-128-bit vectors
972 if (!VT.is128BitVector())
974 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
975 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
976 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
979 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
980 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
981 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
982 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
983 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
984 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
986 if (Subtarget->is64Bit()) {
987 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
991 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
992 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
993 MVT VT = (MVT::SimpleValueType)i;
995 // Do not attempt to promote non-128-bit vectors
996 if (!VT.is128BitVector())
999 setOperationAction(ISD::AND, VT, Promote);
1000 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1001 setOperationAction(ISD::OR, VT, Promote);
1002 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1003 setOperationAction(ISD::XOR, VT, Promote);
1004 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1005 setOperationAction(ISD::LOAD, VT, Promote);
1006 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1007 setOperationAction(ISD::SELECT, VT, Promote);
1008 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1011 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1013 // Custom lower v2i64 and v2f64 selects.
1014 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1015 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1016 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1017 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1019 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1020 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1022 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1023 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1024 // As there is no 64-bit GPR available, we need build a special custom
1025 // sequence to convert from v2i32 to v2f32.
1026 if (!Subtarget->is64Bit())
1027 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1029 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1030 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1032 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1035 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1036 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1037 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1038 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1039 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1040 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1041 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1042 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1043 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1044 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1045 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1047 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1048 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1049 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1050 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1051 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1052 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1055 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1058 // FIXME: Do we need to handle scalar-to-vector here?
1059 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1061 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1062 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1063 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1064 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1065 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1067 // i8 and i16 vectors are custom , because the source register and source
1068 // source memory operand types are not the same width. f32 vectors are
1069 // custom since the immediate controlling the insert encodes additional
1071 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1072 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1073 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1074 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1076 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1077 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1078 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1079 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1081 // FIXME: these should be Legal but thats only for the case where
1082 // the index is constant. For now custom expand to deal with that.
1083 if (Subtarget->is64Bit()) {
1084 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1085 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1089 if (Subtarget->hasSSE2()) {
1090 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1091 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1093 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1094 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1096 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1097 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1099 // In the customized shift lowering, the legal cases in AVX2 will be
1101 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1102 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1104 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1105 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1107 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1109 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1110 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1113 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1114 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1115 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1116 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1117 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1118 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1121 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1122 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1123 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1125 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1126 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1127 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1128 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1129 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1136 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1138 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1139 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1140 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1141 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1149 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1151 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1152 // even though v8i16 is a legal type.
1153 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1154 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1155 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1157 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1158 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1159 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1161 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1162 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1164 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1166 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1167 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1169 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1172 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1177 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1182 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1183 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1184 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1186 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1187 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1188 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1189 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1191 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1192 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1193 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1194 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1195 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1196 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1197 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1198 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1199 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1200 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1201 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1202 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1204 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1205 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1206 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1207 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1208 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1209 setOperationAction(ISD::FMA, MVT::f32, Legal);
1210 setOperationAction(ISD::FMA, MVT::f64, Legal);
1213 if (Subtarget->hasInt256()) {
1214 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1215 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1216 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1217 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1219 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1220 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1221 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1222 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1224 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1225 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1226 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1227 // Don't lower v32i8 because there is no 128-bit byte mul
1229 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1231 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1233 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1234 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1235 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1236 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1238 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1239 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1240 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1241 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1243 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1244 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1245 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1246 // Don't lower v32i8 because there is no 128-bit byte mul
1249 // In the customized shift lowering, the legal cases in AVX2 will be
1251 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1252 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1254 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1255 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1257 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1259 // Custom lower several nodes for 256-bit types.
1260 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1261 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1262 MVT VT = (MVT::SimpleValueType)i;
1264 // Extract subvector is special because the value type
1265 // (result) is 128-bit but the source is 256-bit wide.
1266 if (VT.is128BitVector())
1267 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1269 // Do not attempt to custom lower other non-256-bit vectors
1270 if (!VT.is256BitVector())
1273 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1274 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1275 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1276 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1277 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1278 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1279 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1282 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284 MVT VT = (MVT::SimpleValueType)i;
1286 // Do not attempt to promote non-256-bit vectors
1287 if (!VT.is256BitVector())
1290 setOperationAction(ISD::AND, VT, Promote);
1291 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1292 setOperationAction(ISD::OR, VT, Promote);
1293 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1294 setOperationAction(ISD::XOR, VT, Promote);
1295 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1296 setOperationAction(ISD::LOAD, VT, Promote);
1297 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1298 setOperationAction(ISD::SELECT, VT, Promote);
1299 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1303 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1304 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1307 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1309 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1310 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1311 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1313 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1314 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1315 setOperationAction(ISD::XOR, MVT::i1, Legal);
1316 setOperationAction(ISD::OR, MVT::i1, Legal);
1317 setOperationAction(ISD::AND, MVT::i1, Legal);
1318 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1319 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1320 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1321 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1322 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1323 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1325 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1326 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1327 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1328 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1329 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1330 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1332 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1333 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1334 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1335 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1336 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1337 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1338 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1340 setOperationAction(ISD::SDIV, MVT::v16i32, Custom);
1342 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1343 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1344 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1345 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1346 if (Subtarget->is64Bit()) {
1347 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1348 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1349 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1350 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1352 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1353 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1354 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1355 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1356 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1357 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1358 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1359 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1360 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1361 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1363 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1364 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1365 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1366 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1367 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1368 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1369 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1370 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1371 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1372 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1373 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1374 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1375 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1377 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1378 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1379 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1380 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1381 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1384 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1385 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1387 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1389 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1393 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1394 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1395 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1396 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1397 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1399 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1400 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1402 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1403 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1405 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1407 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1408 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1410 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1411 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1413 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1414 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1416 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1417 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1418 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1419 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1420 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1421 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1423 // Custom lower several nodes.
1424 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1425 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1426 MVT VT = (MVT::SimpleValueType)i;
1428 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1429 // Extract subvector is special because the value type
1430 // (result) is 256/128-bit but the source is 512-bit wide.
1431 if (VT.is128BitVector() || VT.is256BitVector())
1432 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1434 if (VT.getVectorElementType() == MVT::i1)
1435 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1437 // Do not attempt to custom lower other non-512-bit vectors
1438 if (!VT.is512BitVector())
1441 if ( EltSize >= 32) {
1442 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1443 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1444 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1445 setOperationAction(ISD::VSELECT, VT, Legal);
1446 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1447 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1448 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1451 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1452 MVT VT = (MVT::SimpleValueType)i;
1454 // Do not attempt to promote non-256-bit vectors
1455 if (!VT.is512BitVector())
1458 setOperationAction(ISD::SELECT, VT, Promote);
1459 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1463 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1464 // of this type with custom code.
1465 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1466 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1467 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1471 // We want to custom lower some of our intrinsics.
1472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1474 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1475 if (!Subtarget->is64Bit())
1476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1478 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1479 // handle type legalization for these operations here.
1481 // FIXME: We really should do custom legalization for addition and
1482 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1483 // than generic legalization for 64-bit multiplication-with-overflow, though.
1484 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1485 // Add/Sub/Mul with overflow operations are custom lowered.
1487 setOperationAction(ISD::SADDO, VT, Custom);
1488 setOperationAction(ISD::UADDO, VT, Custom);
1489 setOperationAction(ISD::SSUBO, VT, Custom);
1490 setOperationAction(ISD::USUBO, VT, Custom);
1491 setOperationAction(ISD::SMULO, VT, Custom);
1492 setOperationAction(ISD::UMULO, VT, Custom);
1495 // There are no 8-bit 3-address imul/mul instructions
1496 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1497 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1499 if (!Subtarget->is64Bit()) {
1500 // These libcalls are not available in 32-bit.
1501 setLibcallName(RTLIB::SHL_I128, 0);
1502 setLibcallName(RTLIB::SRL_I128, 0);
1503 setLibcallName(RTLIB::SRA_I128, 0);
1506 // Combine sin / cos into one node or libcall if possible.
1507 if (Subtarget->hasSinCos()) {
1508 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1509 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1510 if (Subtarget->isTargetDarwin()) {
1511 // For MacOSX, we don't want to the normal expansion of a libcall to
1512 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1514 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1515 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1519 // We have target-specific dag combine patterns for the following nodes:
1520 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1521 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1522 setTargetDAGCombine(ISD::VSELECT);
1523 setTargetDAGCombine(ISD::SELECT);
1524 setTargetDAGCombine(ISD::SHL);
1525 setTargetDAGCombine(ISD::SRA);
1526 setTargetDAGCombine(ISD::SRL);
1527 setTargetDAGCombine(ISD::OR);
1528 setTargetDAGCombine(ISD::AND);
1529 setTargetDAGCombine(ISD::ADD);
1530 setTargetDAGCombine(ISD::FADD);
1531 setTargetDAGCombine(ISD::FSUB);
1532 setTargetDAGCombine(ISD::FMA);
1533 setTargetDAGCombine(ISD::SUB);
1534 setTargetDAGCombine(ISD::LOAD);
1535 setTargetDAGCombine(ISD::STORE);
1536 setTargetDAGCombine(ISD::ZERO_EXTEND);
1537 setTargetDAGCombine(ISD::ANY_EXTEND);
1538 setTargetDAGCombine(ISD::SIGN_EXTEND);
1539 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1540 setTargetDAGCombine(ISD::TRUNCATE);
1541 setTargetDAGCombine(ISD::SINT_TO_FP);
1542 setTargetDAGCombine(ISD::SETCC);
1543 if (Subtarget->is64Bit())
1544 setTargetDAGCombine(ISD::MUL);
1545 setTargetDAGCombine(ISD::XOR);
1547 computeRegisterProperties();
1549 // On Darwin, -Os means optimize for size without hurting performance,
1550 // do not reduce the limit.
1551 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1552 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1553 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1554 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1555 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1556 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1557 setPrefLoopAlignment(4); // 2^4 bytes.
1559 // Predictable cmov don't hurt on atom because it's in-order.
1560 PredictableSelectIsExpensive = !Subtarget->isAtom();
1562 setPrefFunctionAlignment(4); // 2^4 bytes.
1565 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1567 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1569 if (Subtarget->hasAVX512())
1570 switch(VT.getVectorNumElements()) {
1571 case 8: return MVT::v8i1;
1572 case 16: return MVT::v16i1;
1575 return VT.changeVectorElementTypeToInteger();
1578 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1579 /// the desired ByVal argument alignment.
1580 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1583 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1584 if (VTy->getBitWidth() == 128)
1586 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1587 unsigned EltAlign = 0;
1588 getMaxByValAlign(ATy->getElementType(), EltAlign);
1589 if (EltAlign > MaxAlign)
1590 MaxAlign = EltAlign;
1591 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1592 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1593 unsigned EltAlign = 0;
1594 getMaxByValAlign(STy->getElementType(i), EltAlign);
1595 if (EltAlign > MaxAlign)
1596 MaxAlign = EltAlign;
1603 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1604 /// function arguments in the caller parameter area. For X86, aggregates
1605 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1606 /// are at 4-byte boundaries.
1607 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1608 if (Subtarget->is64Bit()) {
1609 // Max of 8 and alignment of type.
1610 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1617 if (Subtarget->hasSSE1())
1618 getMaxByValAlign(Ty, Align);
1622 /// getOptimalMemOpType - Returns the target specific optimal type for load
1623 /// and store operations as a result of memset, memcpy, and memmove
1624 /// lowering. If DstAlign is zero that means it's safe to destination
1625 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1626 /// means there isn't a need to check it against alignment requirement,
1627 /// probably because the source does not need to be loaded. If 'IsMemset' is
1628 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1629 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1630 /// source is constant so it does not need to be loaded.
1631 /// It returns EVT::Other if the type should be determined using generic
1632 /// target-independent logic.
1634 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1635 unsigned DstAlign, unsigned SrcAlign,
1636 bool IsMemset, bool ZeroMemset,
1638 MachineFunction &MF) const {
1639 const Function *F = MF.getFunction();
1640 if ((!IsMemset || ZeroMemset) &&
1641 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1642 Attribute::NoImplicitFloat)) {
1644 (Subtarget->isUnalignedMemAccessFast() ||
1645 ((DstAlign == 0 || DstAlign >= 16) &&
1646 (SrcAlign == 0 || SrcAlign >= 16)))) {
1648 if (Subtarget->hasInt256())
1650 if (Subtarget->hasFp256())
1653 if (Subtarget->hasSSE2())
1655 if (Subtarget->hasSSE1())
1657 } else if (!MemcpyStrSrc && Size >= 8 &&
1658 !Subtarget->is64Bit() &&
1659 Subtarget->hasSSE2()) {
1660 // Do not use f64 to lower memcpy if source is string constant. It's
1661 // better to use i32 to avoid the loads.
1665 if (Subtarget->is64Bit() && Size >= 8)
1670 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1672 return X86ScalarSSEf32;
1673 else if (VT == MVT::f64)
1674 return X86ScalarSSEf64;
1679 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1683 *Fast = Subtarget->isUnalignedMemAccessFast();
1687 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1688 /// current function. The returned value is a member of the
1689 /// MachineJumpTableInfo::JTEntryKind enum.
1690 unsigned X86TargetLowering::getJumpTableEncoding() const {
1691 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1693 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1694 Subtarget->isPICStyleGOT())
1695 return MachineJumpTableInfo::EK_Custom32;
1697 // Otherwise, use the normal jump table encoding heuristics.
1698 return TargetLowering::getJumpTableEncoding();
1702 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1703 const MachineBasicBlock *MBB,
1704 unsigned uid,MCContext &Ctx) const{
1705 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1706 Subtarget->isPICStyleGOT());
1707 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1709 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1710 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1713 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1715 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1716 SelectionDAG &DAG) const {
1717 if (!Subtarget->is64Bit())
1718 // This doesn't have SDLoc associated with it, but is not really the
1719 // same as a Register.
1720 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1724 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1725 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1727 const MCExpr *X86TargetLowering::
1728 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1729 MCContext &Ctx) const {
1730 // X86-64 uses RIP relative addressing based on the jump table label.
1731 if (Subtarget->isPICStyleRIPRel())
1732 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1734 // Otherwise, the reference is relative to the PIC base.
1735 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1738 // FIXME: Why this routine is here? Move to RegInfo!
1739 std::pair<const TargetRegisterClass*, uint8_t>
1740 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1741 const TargetRegisterClass *RRC = 0;
1743 switch (VT.SimpleTy) {
1745 return TargetLowering::findRepresentativeClass(VT);
1746 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1747 RRC = Subtarget->is64Bit() ?
1748 (const TargetRegisterClass*)&X86::GR64RegClass :
1749 (const TargetRegisterClass*)&X86::GR32RegClass;
1752 RRC = &X86::VR64RegClass;
1754 case MVT::f32: case MVT::f64:
1755 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1756 case MVT::v4f32: case MVT::v2f64:
1757 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1759 RRC = &X86::VR128RegClass;
1762 return std::make_pair(RRC, Cost);
1765 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1766 unsigned &Offset) const {
1767 if (!Subtarget->isTargetLinux())
1770 if (Subtarget->is64Bit()) {
1771 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1773 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1785 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1786 unsigned DestAS) const {
1787 assert(SrcAS != DestAS && "Expected different address spaces!");
1789 return SrcAS < 256 && DestAS < 256;
1792 //===----------------------------------------------------------------------===//
1793 // Return Value Calling Convention Implementation
1794 //===----------------------------------------------------------------------===//
1796 #include "X86GenCallingConv.inc"
1799 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1800 MachineFunction &MF, bool isVarArg,
1801 const SmallVectorImpl<ISD::OutputArg> &Outs,
1802 LLVMContext &Context) const {
1803 SmallVector<CCValAssign, 16> RVLocs;
1804 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1806 return CCInfo.CheckReturn(Outs, RetCC_X86);
1809 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1810 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1815 X86TargetLowering::LowerReturn(SDValue Chain,
1816 CallingConv::ID CallConv, bool isVarArg,
1817 const SmallVectorImpl<ISD::OutputArg> &Outs,
1818 const SmallVectorImpl<SDValue> &OutVals,
1819 SDLoc dl, SelectionDAG &DAG) const {
1820 MachineFunction &MF = DAG.getMachineFunction();
1821 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1823 SmallVector<CCValAssign, 16> RVLocs;
1824 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1825 RVLocs, *DAG.getContext());
1826 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1829 SmallVector<SDValue, 6> RetOps;
1830 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1831 // Operand #1 = Bytes To Pop
1832 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1835 // Copy the result values into the output registers.
1836 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1837 CCValAssign &VA = RVLocs[i];
1838 assert(VA.isRegLoc() && "Can only return in registers!");
1839 SDValue ValToCopy = OutVals[i];
1840 EVT ValVT = ValToCopy.getValueType();
1842 // Promote values to the appropriate types
1843 if (VA.getLocInfo() == CCValAssign::SExt)
1844 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1845 else if (VA.getLocInfo() == CCValAssign::ZExt)
1846 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1847 else if (VA.getLocInfo() == CCValAssign::AExt)
1848 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1849 else if (VA.getLocInfo() == CCValAssign::BCvt)
1850 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1852 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1853 "Unexpected FP-extend for return value.");
1855 // If this is x86-64, and we disabled SSE, we can't return FP values,
1856 // or SSE or MMX vectors.
1857 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1858 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1859 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1860 report_fatal_error("SSE register return with SSE disabled");
1862 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1863 // llvm-gcc has never done it right and no one has noticed, so this
1864 // should be OK for now.
1865 if (ValVT == MVT::f64 &&
1866 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1867 report_fatal_error("SSE2 register return with SSE2 disabled");
1869 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1870 // the RET instruction and handled by the FP Stackifier.
1871 if (VA.getLocReg() == X86::ST0 ||
1872 VA.getLocReg() == X86::ST1) {
1873 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1874 // change the value to the FP stack register class.
1875 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1876 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1877 RetOps.push_back(ValToCopy);
1878 // Don't emit a copytoreg.
1882 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1883 // which is returned in RAX / RDX.
1884 if (Subtarget->is64Bit()) {
1885 if (ValVT == MVT::x86mmx) {
1886 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1887 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1888 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1890 // If we don't have SSE2 available, convert to v4f32 so the generated
1891 // register is legal.
1892 if (!Subtarget->hasSSE2())
1893 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1898 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1899 Flag = Chain.getValue(1);
1900 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1903 // The x86-64 ABIs require that for returning structs by value we copy
1904 // the sret argument into %rax/%eax (depending on ABI) for the return.
1905 // Win32 requires us to put the sret argument to %eax as well.
1906 // We saved the argument into a virtual register in the entry block,
1907 // so now we copy the value out and into %rax/%eax.
1908 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1909 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1910 MachineFunction &MF = DAG.getMachineFunction();
1911 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1912 unsigned Reg = FuncInfo->getSRetReturnReg();
1914 "SRetReturnReg should have been set in LowerFormalArguments().");
1915 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1918 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1919 X86::RAX : X86::EAX;
1920 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1921 Flag = Chain.getValue(1);
1923 // RAX/EAX now acts like a return value.
1924 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1927 RetOps[0] = Chain; // Update chain.
1929 // Add the flag if we have it.
1931 RetOps.push_back(Flag);
1933 return DAG.getNode(X86ISD::RET_FLAG, dl,
1934 MVT::Other, &RetOps[0], RetOps.size());
1937 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1938 if (N->getNumValues() != 1)
1940 if (!N->hasNUsesOfValue(1, 0))
1943 SDValue TCChain = Chain;
1944 SDNode *Copy = *N->use_begin();
1945 if (Copy->getOpcode() == ISD::CopyToReg) {
1946 // If the copy has a glue operand, we conservatively assume it isn't safe to
1947 // perform a tail call.
1948 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1950 TCChain = Copy->getOperand(0);
1951 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1954 bool HasRet = false;
1955 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1957 if (UI->getOpcode() != X86ISD::RET_FLAG)
1970 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1971 ISD::NodeType ExtendKind) const {
1973 // TODO: Is this also valid on 32-bit?
1974 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1975 ReturnMVT = MVT::i8;
1977 ReturnMVT = MVT::i32;
1979 MVT MinVT = getRegisterType(ReturnMVT);
1980 return VT.bitsLT(MinVT) ? MinVT : VT;
1983 /// LowerCallResult - Lower the result values of a call into the
1984 /// appropriate copies out of appropriate physical registers.
1987 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1988 CallingConv::ID CallConv, bool isVarArg,
1989 const SmallVectorImpl<ISD::InputArg> &Ins,
1990 SDLoc dl, SelectionDAG &DAG,
1991 SmallVectorImpl<SDValue> &InVals) const {
1993 // Assign locations to each value returned by this call.
1994 SmallVector<CCValAssign, 16> RVLocs;
1995 bool Is64Bit = Subtarget->is64Bit();
1996 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1997 getTargetMachine(), RVLocs, *DAG.getContext());
1998 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2000 // Copy all of the result registers out of their specified physreg.
2001 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2002 CCValAssign &VA = RVLocs[i];
2003 EVT CopyVT = VA.getValVT();
2005 // If this is x86-64, and we disabled SSE, we can't return FP values
2006 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2007 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2008 report_fatal_error("SSE register return with SSE disabled");
2013 // If this is a call to a function that returns an fp value on the floating
2014 // point stack, we must guarantee the value is popped from the stack, so
2015 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2016 // if the return value is not used. We use the FpPOP_RETVAL instruction
2018 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2019 // If we prefer to use the value in xmm registers, copy it out as f80 and
2020 // use a truncate to move it from fp stack reg to xmm reg.
2021 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2022 SDValue Ops[] = { Chain, InFlag };
2023 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2024 MVT::Other, MVT::Glue, Ops), 1);
2025 Val = Chain.getValue(0);
2027 // Round the f80 to the right size, which also moves it to the appropriate
2029 if (CopyVT != VA.getValVT())
2030 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2031 // This truncation won't change the value.
2032 DAG.getIntPtrConstant(1));
2034 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2035 CopyVT, InFlag).getValue(1);
2036 Val = Chain.getValue(0);
2038 InFlag = Chain.getValue(2);
2039 InVals.push_back(Val);
2045 //===----------------------------------------------------------------------===//
2046 // C & StdCall & Fast Calling Convention implementation
2047 //===----------------------------------------------------------------------===//
2048 // StdCall calling convention seems to be standard for many Windows' API
2049 // routines and around. It differs from C calling convention just a little:
2050 // callee should clean up the stack, not caller. Symbols should be also
2051 // decorated in some fancy way :) It doesn't support any vector arguments.
2052 // For info on fast calling convention see Fast Calling Convention (tail call)
2053 // implementation LowerX86_32FastCCCallTo.
2055 /// CallIsStructReturn - Determines whether a call uses struct return
2057 enum StructReturnType {
2062 static StructReturnType
2063 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2065 return NotStructReturn;
2067 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2068 if (!Flags.isSRet())
2069 return NotStructReturn;
2070 if (Flags.isInReg())
2071 return RegStructReturn;
2072 return StackStructReturn;
2075 /// ArgsAreStructReturn - Determines whether a function uses struct
2076 /// return semantics.
2077 static StructReturnType
2078 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2080 return NotStructReturn;
2082 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2083 if (!Flags.isSRet())
2084 return NotStructReturn;
2085 if (Flags.isInReg())
2086 return RegStructReturn;
2087 return StackStructReturn;
2090 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2091 /// by "Src" to address "Dst" with size and alignment information specified by
2092 /// the specific parameter attribute. The copy will be passed as a byval
2093 /// function parameter.
2095 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2096 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2098 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2100 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2101 /*isVolatile*/false, /*AlwaysInline=*/true,
2102 MachinePointerInfo(), MachinePointerInfo());
2105 /// IsTailCallConvention - Return true if the calling convention is one that
2106 /// supports tail call optimization.
2107 static bool IsTailCallConvention(CallingConv::ID CC) {
2108 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2109 CC == CallingConv::HiPE);
2112 /// \brief Return true if the calling convention is a C calling convention.
2113 static bool IsCCallConvention(CallingConv::ID CC) {
2114 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2115 CC == CallingConv::X86_64_SysV);
2118 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2119 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2123 CallingConv::ID CalleeCC = CS.getCallingConv();
2124 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2130 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2131 /// a tailcall target by changing its ABI.
2132 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2133 bool GuaranteedTailCallOpt) {
2134 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2138 X86TargetLowering::LowerMemArgument(SDValue Chain,
2139 CallingConv::ID CallConv,
2140 const SmallVectorImpl<ISD::InputArg> &Ins,
2141 SDLoc dl, SelectionDAG &DAG,
2142 const CCValAssign &VA,
2143 MachineFrameInfo *MFI,
2145 // Create the nodes corresponding to a load from this parameter slot.
2146 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2147 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2148 getTargetMachine().Options.GuaranteedTailCallOpt);
2149 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2152 // If value is passed by pointer we have address passed instead of the value
2154 if (VA.getLocInfo() == CCValAssign::Indirect)
2155 ValVT = VA.getLocVT();
2157 ValVT = VA.getValVT();
2159 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2160 // changed with more analysis.
2161 // In case of tail call optimization mark all arguments mutable. Since they
2162 // could be overwritten by lowering of arguments in case of a tail call.
2163 if (Flags.isByVal()) {
2164 unsigned Bytes = Flags.getByValSize();
2165 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2166 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2167 return DAG.getFrameIndex(FI, getPointerTy());
2169 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2170 VA.getLocMemOffset(), isImmutable);
2171 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2172 return DAG.getLoad(ValVT, dl, Chain, FIN,
2173 MachinePointerInfo::getFixedStack(FI),
2174 false, false, false, 0);
2179 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2180 CallingConv::ID CallConv,
2182 const SmallVectorImpl<ISD::InputArg> &Ins,
2185 SmallVectorImpl<SDValue> &InVals)
2187 MachineFunction &MF = DAG.getMachineFunction();
2188 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2190 const Function* Fn = MF.getFunction();
2191 if (Fn->hasExternalLinkage() &&
2192 Subtarget->isTargetCygMing() &&
2193 Fn->getName() == "main")
2194 FuncInfo->setForceFramePointer(true);
2196 MachineFrameInfo *MFI = MF.getFrameInfo();
2197 bool Is64Bit = Subtarget->is64Bit();
2198 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2200 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2201 "Var args not supported with calling convention fastcc, ghc or hipe");
2203 // Assign locations to all of the incoming arguments.
2204 SmallVector<CCValAssign, 16> ArgLocs;
2205 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2206 ArgLocs, *DAG.getContext());
2208 // Allocate shadow area for Win64
2210 CCInfo.AllocateStack(32, 8);
2212 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2214 unsigned LastVal = ~0U;
2216 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2217 CCValAssign &VA = ArgLocs[i];
2218 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2220 assert(VA.getValNo() != LastVal &&
2221 "Don't support value assigned to multiple locs yet");
2223 LastVal = VA.getValNo();
2225 if (VA.isRegLoc()) {
2226 EVT RegVT = VA.getLocVT();
2227 const TargetRegisterClass *RC;
2228 if (RegVT == MVT::i32)
2229 RC = &X86::GR32RegClass;
2230 else if (Is64Bit && RegVT == MVT::i64)
2231 RC = &X86::GR64RegClass;
2232 else if (RegVT == MVT::f32)
2233 RC = &X86::FR32RegClass;
2234 else if (RegVT == MVT::f64)
2235 RC = &X86::FR64RegClass;
2236 else if (RegVT.is512BitVector())
2237 RC = &X86::VR512RegClass;
2238 else if (RegVT.is256BitVector())
2239 RC = &X86::VR256RegClass;
2240 else if (RegVT.is128BitVector())
2241 RC = &X86::VR128RegClass;
2242 else if (RegVT == MVT::x86mmx)
2243 RC = &X86::VR64RegClass;
2244 else if (RegVT == MVT::i1)
2245 RC = &X86::VK1RegClass;
2246 else if (RegVT == MVT::v8i1)
2247 RC = &X86::VK8RegClass;
2248 else if (RegVT == MVT::v16i1)
2249 RC = &X86::VK16RegClass;
2251 llvm_unreachable("Unknown argument type!");
2253 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2254 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2256 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2257 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2259 if (VA.getLocInfo() == CCValAssign::SExt)
2260 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2261 DAG.getValueType(VA.getValVT()));
2262 else if (VA.getLocInfo() == CCValAssign::ZExt)
2263 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2264 DAG.getValueType(VA.getValVT()));
2265 else if (VA.getLocInfo() == CCValAssign::BCvt)
2266 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2268 if (VA.isExtInLoc()) {
2269 // Handle MMX values passed in XMM regs.
2270 if (RegVT.isVector())
2271 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2273 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2276 assert(VA.isMemLoc());
2277 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2280 // If value is passed via pointer - do a load.
2281 if (VA.getLocInfo() == CCValAssign::Indirect)
2282 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2283 MachinePointerInfo(), false, false, false, 0);
2285 InVals.push_back(ArgValue);
2288 // The x86-64 ABIs require that for returning structs by value we copy
2289 // the sret argument into %rax/%eax (depending on ABI) for the return.
2290 // Win32 requires us to put the sret argument to %eax as well.
2291 // Save the argument into a virtual register so that we can access it
2292 // from the return points.
2293 if (MF.getFunction()->hasStructRetAttr() &&
2294 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2295 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2296 unsigned Reg = FuncInfo->getSRetReturnReg();
2298 MVT PtrTy = getPointerTy();
2299 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2300 FuncInfo->setSRetReturnReg(Reg);
2302 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2303 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2306 unsigned StackSize = CCInfo.getNextStackOffset();
2307 // Align stack specially for tail calls.
2308 if (FuncIsMadeTailCallSafe(CallConv,
2309 MF.getTarget().Options.GuaranteedTailCallOpt))
2310 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2312 // If the function takes variable number of arguments, make a frame index for
2313 // the start of the first vararg value... for expansion of llvm.va_start.
2315 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2316 CallConv != CallingConv::X86_ThisCall)) {
2317 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2320 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2322 // FIXME: We should really autogenerate these arrays
2323 static const MCPhysReg GPR64ArgRegsWin64[] = {
2324 X86::RCX, X86::RDX, X86::R8, X86::R9
2326 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2327 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2329 static const MCPhysReg XMMArgRegs64Bit[] = {
2330 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2331 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2333 const MCPhysReg *GPR64ArgRegs;
2334 unsigned NumXMMRegs = 0;
2337 // The XMM registers which might contain var arg parameters are shadowed
2338 // in their paired GPR. So we only need to save the GPR to their home
2340 TotalNumIntRegs = 4;
2341 GPR64ArgRegs = GPR64ArgRegsWin64;
2343 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2344 GPR64ArgRegs = GPR64ArgRegs64Bit;
2346 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2349 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2352 bool NoImplicitFloatOps = Fn->getAttributes().
2353 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2354 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2355 "SSE register cannot be used when SSE is disabled!");
2356 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2357 NoImplicitFloatOps) &&
2358 "SSE register cannot be used when SSE is disabled!");
2359 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2360 !Subtarget->hasSSE1())
2361 // Kernel mode asks for SSE to be disabled, so don't push them
2363 TotalNumXMMRegs = 0;
2366 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2367 // Get to the caller-allocated home save location. Add 8 to account
2368 // for the return address.
2369 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2370 FuncInfo->setRegSaveFrameIndex(
2371 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2372 // Fixup to set vararg frame on shadow area (4 x i64).
2374 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2376 // For X86-64, if there are vararg parameters that are passed via
2377 // registers, then we must store them to their spots on the stack so
2378 // they may be loaded by deferencing the result of va_next.
2379 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2380 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2381 FuncInfo->setRegSaveFrameIndex(
2382 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2386 // Store the integer parameter registers.
2387 SmallVector<SDValue, 8> MemOps;
2388 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2390 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2391 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2392 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2393 DAG.getIntPtrConstant(Offset));
2394 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2395 &X86::GR64RegClass);
2396 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2398 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2399 MachinePointerInfo::getFixedStack(
2400 FuncInfo->getRegSaveFrameIndex(), Offset),
2402 MemOps.push_back(Store);
2406 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2407 // Now store the XMM (fp + vector) parameter registers.
2408 SmallVector<SDValue, 11> SaveXMMOps;
2409 SaveXMMOps.push_back(Chain);
2411 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2412 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2413 SaveXMMOps.push_back(ALVal);
2415 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2416 FuncInfo->getRegSaveFrameIndex()));
2417 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2418 FuncInfo->getVarArgsFPOffset()));
2420 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2421 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2422 &X86::VR128RegClass);
2423 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2424 SaveXMMOps.push_back(Val);
2426 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2428 &SaveXMMOps[0], SaveXMMOps.size()));
2431 if (!MemOps.empty())
2432 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2433 &MemOps[0], MemOps.size());
2437 // Some CCs need callee pop.
2438 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2439 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2440 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2442 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2443 // If this is an sret function, the return should pop the hidden pointer.
2444 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2445 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2446 argsAreStructReturn(Ins) == StackStructReturn)
2447 FuncInfo->setBytesToPopOnReturn(4);
2451 // RegSaveFrameIndex is X86-64 only.
2452 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2453 if (CallConv == CallingConv::X86_FastCall ||
2454 CallConv == CallingConv::X86_ThisCall)
2455 // fastcc functions can't have varargs.
2456 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2459 FuncInfo->setArgumentStackSize(StackSize);
2465 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2466 SDValue StackPtr, SDValue Arg,
2467 SDLoc dl, SelectionDAG &DAG,
2468 const CCValAssign &VA,
2469 ISD::ArgFlagsTy Flags) const {
2470 unsigned LocMemOffset = VA.getLocMemOffset();
2471 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2472 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2473 if (Flags.isByVal())
2474 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2476 return DAG.getStore(Chain, dl, Arg, PtrOff,
2477 MachinePointerInfo::getStack(LocMemOffset),
2481 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2482 /// optimization is performed and it is required.
2484 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2485 SDValue &OutRetAddr, SDValue Chain,
2486 bool IsTailCall, bool Is64Bit,
2487 int FPDiff, SDLoc dl) const {
2488 // Adjust the Return address stack slot.
2489 EVT VT = getPointerTy();
2490 OutRetAddr = getReturnAddressFrameIndex(DAG);
2492 // Load the "old" Return address.
2493 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2494 false, false, false, 0);
2495 return SDValue(OutRetAddr.getNode(), 1);
2498 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2499 /// optimization is performed and it is required (FPDiff!=0).
2501 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2502 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2503 unsigned SlotSize, int FPDiff, SDLoc dl) {
2504 // Store the return address to the appropriate stack slot.
2505 if (!FPDiff) return Chain;
2506 // Calculate the new stack slot for the return address.
2507 int NewReturnAddrFI =
2508 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2510 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2511 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2512 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2518 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2519 SmallVectorImpl<SDValue> &InVals) const {
2520 SelectionDAG &DAG = CLI.DAG;
2522 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2523 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2524 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2525 SDValue Chain = CLI.Chain;
2526 SDValue Callee = CLI.Callee;
2527 CallingConv::ID CallConv = CLI.CallConv;
2528 bool &isTailCall = CLI.IsTailCall;
2529 bool isVarArg = CLI.IsVarArg;
2531 MachineFunction &MF = DAG.getMachineFunction();
2532 bool Is64Bit = Subtarget->is64Bit();
2533 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2534 StructReturnType SR = callIsStructReturn(Outs);
2535 bool IsSibcall = false;
2537 if (MF.getTarget().Options.DisableTailCalls)
2541 // Check if it's really possible to do a tail call.
2542 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2543 isVarArg, SR != NotStructReturn,
2544 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2545 Outs, OutVals, Ins, DAG);
2547 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2548 report_fatal_error("failed to perform tail call elimination on a call "
2549 "site marked musttail");
2551 // Sibcalls are automatically detected tailcalls which do not require
2553 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2560 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2561 "Var args not supported with calling convention fastcc, ghc or hipe");
2563 // Analyze operands of the call, assigning locations to each operand.
2564 SmallVector<CCValAssign, 16> ArgLocs;
2565 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2566 ArgLocs, *DAG.getContext());
2568 // Allocate shadow area for Win64
2570 CCInfo.AllocateStack(32, 8);
2572 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2574 // Get a count of how many bytes are to be pushed on the stack.
2575 unsigned NumBytes = CCInfo.getNextStackOffset();
2577 // This is a sibcall. The memory operands are available in caller's
2578 // own caller's stack.
2580 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2581 IsTailCallConvention(CallConv))
2582 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2585 if (isTailCall && !IsSibcall) {
2586 // Lower arguments at fp - stackoffset + fpdiff.
2587 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2588 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2590 FPDiff = NumBytesCallerPushed - NumBytes;
2592 // Set the delta of movement of the returnaddr stackslot.
2593 // But only set if delta is greater than previous delta.
2594 if (FPDiff < X86Info->getTCReturnAddrDelta())
2595 X86Info->setTCReturnAddrDelta(FPDiff);
2598 unsigned NumBytesToPush = NumBytes;
2599 unsigned NumBytesToPop = NumBytes;
2601 // If we have an inalloca argument, all stack space has already been allocated
2602 // for us and be right at the top of the stack. We don't support multiple
2603 // arguments passed in memory when using inalloca.
2604 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2606 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2607 "an inalloca argument must be the only memory argument");
2611 Chain = DAG.getCALLSEQ_START(
2612 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2614 SDValue RetAddrFrIdx;
2615 // Load return address for tail calls.
2616 if (isTailCall && FPDiff)
2617 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2618 Is64Bit, FPDiff, dl);
2620 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2621 SmallVector<SDValue, 8> MemOpChains;
2624 // Walk the register/memloc assignments, inserting copies/loads. In the case
2625 // of tail call optimization arguments are handle later.
2626 const X86RegisterInfo *RegInfo =
2627 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2628 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2629 // Skip inalloca arguments, they have already been written.
2630 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2631 if (Flags.isInAlloca())
2634 CCValAssign &VA = ArgLocs[i];
2635 EVT RegVT = VA.getLocVT();
2636 SDValue Arg = OutVals[i];
2637 bool isByVal = Flags.isByVal();
2639 // Promote the value if needed.
2640 switch (VA.getLocInfo()) {
2641 default: llvm_unreachable("Unknown loc info!");
2642 case CCValAssign::Full: break;
2643 case CCValAssign::SExt:
2644 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2646 case CCValAssign::ZExt:
2647 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2649 case CCValAssign::AExt:
2650 if (RegVT.is128BitVector()) {
2651 // Special case: passing MMX values in XMM registers.
2652 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2653 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2654 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2656 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2658 case CCValAssign::BCvt:
2659 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2661 case CCValAssign::Indirect: {
2662 // Store the argument.
2663 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2664 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2665 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2666 MachinePointerInfo::getFixedStack(FI),
2673 if (VA.isRegLoc()) {
2674 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2675 if (isVarArg && IsWin64) {
2676 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2677 // shadow reg if callee is a varargs function.
2678 unsigned ShadowReg = 0;
2679 switch (VA.getLocReg()) {
2680 case X86::XMM0: ShadowReg = X86::RCX; break;
2681 case X86::XMM1: ShadowReg = X86::RDX; break;
2682 case X86::XMM2: ShadowReg = X86::R8; break;
2683 case X86::XMM3: ShadowReg = X86::R9; break;
2686 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2688 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2689 assert(VA.isMemLoc());
2690 if (StackPtr.getNode() == 0)
2691 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2693 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2694 dl, DAG, VA, Flags));
2698 if (!MemOpChains.empty())
2699 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2700 &MemOpChains[0], MemOpChains.size());
2702 if (Subtarget->isPICStyleGOT()) {
2703 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2706 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2707 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2709 // If we are tail calling and generating PIC/GOT style code load the
2710 // address of the callee into ECX. The value in ecx is used as target of
2711 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2712 // for tail calls on PIC/GOT architectures. Normally we would just put the
2713 // address of GOT into ebx and then call target@PLT. But for tail calls
2714 // ebx would be restored (since ebx is callee saved) before jumping to the
2717 // Note: The actual moving to ECX is done further down.
2718 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2719 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2720 !G->getGlobal()->hasProtectedVisibility())
2721 Callee = LowerGlobalAddress(Callee, DAG);
2722 else if (isa<ExternalSymbolSDNode>(Callee))
2723 Callee = LowerExternalSymbol(Callee, DAG);
2727 if (Is64Bit && isVarArg && !IsWin64) {
2728 // From AMD64 ABI document:
2729 // For calls that may call functions that use varargs or stdargs
2730 // (prototype-less calls or calls to functions containing ellipsis (...) in
2731 // the declaration) %al is used as hidden argument to specify the number
2732 // of SSE registers used. The contents of %al do not need to match exactly
2733 // the number of registers, but must be an ubound on the number of SSE
2734 // registers used and is in the range 0 - 8 inclusive.
2736 // Count the number of XMM registers allocated.
2737 static const MCPhysReg XMMArgRegs[] = {
2738 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2739 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2741 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2742 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2743 && "SSE registers cannot be used when SSE is disabled");
2745 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2746 DAG.getConstant(NumXMMRegs, MVT::i8)));
2749 // For tail calls lower the arguments to the 'real' stack slot.
2751 // Force all the incoming stack arguments to be loaded from the stack
2752 // before any new outgoing arguments are stored to the stack, because the
2753 // outgoing stack slots may alias the incoming argument stack slots, and
2754 // the alias isn't otherwise explicit. This is slightly more conservative
2755 // than necessary, because it means that each store effectively depends
2756 // on every argument instead of just those arguments it would clobber.
2757 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2759 SmallVector<SDValue, 8> MemOpChains2;
2762 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2763 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2764 CCValAssign &VA = ArgLocs[i];
2767 assert(VA.isMemLoc());
2768 SDValue Arg = OutVals[i];
2769 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2770 // Create frame index.
2771 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2772 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2773 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2774 FIN = DAG.getFrameIndex(FI, getPointerTy());
2776 if (Flags.isByVal()) {
2777 // Copy relative to framepointer.
2778 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2779 if (StackPtr.getNode() == 0)
2780 StackPtr = DAG.getCopyFromReg(Chain, dl,
2781 RegInfo->getStackRegister(),
2783 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2785 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2789 // Store relative to framepointer.
2790 MemOpChains2.push_back(
2791 DAG.getStore(ArgChain, dl, Arg, FIN,
2792 MachinePointerInfo::getFixedStack(FI),
2798 if (!MemOpChains2.empty())
2799 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2800 &MemOpChains2[0], MemOpChains2.size());
2802 // Store the return address to the appropriate stack slot.
2803 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2804 getPointerTy(), RegInfo->getSlotSize(),
2808 // Build a sequence of copy-to-reg nodes chained together with token chain
2809 // and flag operands which copy the outgoing args into registers.
2811 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2812 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2813 RegsToPass[i].second, InFlag);
2814 InFlag = Chain.getValue(1);
2817 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2818 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2819 // In the 64-bit large code model, we have to make all calls
2820 // through a register, since the call instruction's 32-bit
2821 // pc-relative offset may not be large enough to hold the whole
2823 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2824 // If the callee is a GlobalAddress node (quite common, every direct call
2825 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2828 // We should use extra load for direct calls to dllimported functions in
2830 const GlobalValue *GV = G->getGlobal();
2831 if (!GV->hasDLLImportStorageClass()) {
2832 unsigned char OpFlags = 0;
2833 bool ExtraLoad = false;
2834 unsigned WrapperKind = ISD::DELETED_NODE;
2836 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2837 // external symbols most go through the PLT in PIC mode. If the symbol
2838 // has hidden or protected visibility, or if it is static or local, then
2839 // we don't need to use the PLT - we can directly call it.
2840 if (Subtarget->isTargetELF() &&
2841 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2842 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2843 OpFlags = X86II::MO_PLT;
2844 } else if (Subtarget->isPICStyleStubAny() &&
2845 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2846 (!Subtarget->getTargetTriple().isMacOSX() ||
2847 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2848 // PC-relative references to external symbols should go through $stub,
2849 // unless we're building with the leopard linker or later, which
2850 // automatically synthesizes these stubs.
2851 OpFlags = X86II::MO_DARWIN_STUB;
2852 } else if (Subtarget->isPICStyleRIPRel() &&
2853 isa<Function>(GV) &&
2854 cast<Function>(GV)->getAttributes().
2855 hasAttribute(AttributeSet::FunctionIndex,
2856 Attribute::NonLazyBind)) {
2857 // If the function is marked as non-lazy, generate an indirect call
2858 // which loads from the GOT directly. This avoids runtime overhead
2859 // at the cost of eager binding (and one extra byte of encoding).
2860 OpFlags = X86II::MO_GOTPCREL;
2861 WrapperKind = X86ISD::WrapperRIP;
2865 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2866 G->getOffset(), OpFlags);
2868 // Add a wrapper if needed.
2869 if (WrapperKind != ISD::DELETED_NODE)
2870 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2871 // Add extra indirection if needed.
2873 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2874 MachinePointerInfo::getGOT(),
2875 false, false, false, 0);
2877 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2878 unsigned char OpFlags = 0;
2880 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2881 // external symbols should go through the PLT.
2882 if (Subtarget->isTargetELF() &&
2883 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2884 OpFlags = X86II::MO_PLT;
2885 } else if (Subtarget->isPICStyleStubAny() &&
2886 (!Subtarget->getTargetTriple().isMacOSX() ||
2887 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2888 // PC-relative references to external symbols should go through $stub,
2889 // unless we're building with the leopard linker or later, which
2890 // automatically synthesizes these stubs.
2891 OpFlags = X86II::MO_DARWIN_STUB;
2894 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2898 // Returns a chain & a flag for retval copy to use.
2899 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2900 SmallVector<SDValue, 8> Ops;
2902 if (!IsSibcall && isTailCall) {
2903 Chain = DAG.getCALLSEQ_END(Chain,
2904 DAG.getIntPtrConstant(NumBytesToPop, true),
2905 DAG.getIntPtrConstant(0, true), InFlag, dl);
2906 InFlag = Chain.getValue(1);
2909 Ops.push_back(Chain);
2910 Ops.push_back(Callee);
2913 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2915 // Add argument registers to the end of the list so that they are known live
2917 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2918 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2919 RegsToPass[i].second.getValueType()));
2921 // Add a register mask operand representing the call-preserved registers.
2922 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2923 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2924 assert(Mask && "Missing call preserved mask for calling convention");
2925 Ops.push_back(DAG.getRegisterMask(Mask));
2927 if (InFlag.getNode())
2928 Ops.push_back(InFlag);
2932 //// If this is the first return lowered for this function, add the regs
2933 //// to the liveout set for the function.
2934 // This isn't right, although it's probably harmless on x86; liveouts
2935 // should be computed from returns not tail calls. Consider a void
2936 // function making a tail call to a function returning int.
2937 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2940 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2941 InFlag = Chain.getValue(1);
2943 // Create the CALLSEQ_END node.
2944 unsigned NumBytesForCalleeToPop;
2945 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2946 getTargetMachine().Options.GuaranteedTailCallOpt))
2947 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2948 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2949 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2950 SR == StackStructReturn)
2951 // If this is a call to a struct-return function, the callee
2952 // pops the hidden struct pointer, so we have to push it back.
2953 // This is common for Darwin/X86, Linux & Mingw32 targets.
2954 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2955 NumBytesForCalleeToPop = 4;
2957 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2959 // Returns a flag for retval copy to use.
2961 Chain = DAG.getCALLSEQ_END(Chain,
2962 DAG.getIntPtrConstant(NumBytesToPop, true),
2963 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2966 InFlag = Chain.getValue(1);
2969 // Handle result values, copying them out of physregs into vregs that we
2971 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2972 Ins, dl, DAG, InVals);
2975 //===----------------------------------------------------------------------===//
2976 // Fast Calling Convention (tail call) implementation
2977 //===----------------------------------------------------------------------===//
2979 // Like std call, callee cleans arguments, convention except that ECX is
2980 // reserved for storing the tail called function address. Only 2 registers are
2981 // free for argument passing (inreg). Tail call optimization is performed
2983 // * tailcallopt is enabled
2984 // * caller/callee are fastcc
2985 // On X86_64 architecture with GOT-style position independent code only local
2986 // (within module) calls are supported at the moment.
2987 // To keep the stack aligned according to platform abi the function
2988 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2989 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2990 // If a tail called function callee has more arguments than the caller the
2991 // caller needs to make sure that there is room to move the RETADDR to. This is
2992 // achieved by reserving an area the size of the argument delta right after the
2993 // original REtADDR, but before the saved framepointer or the spilled registers
2994 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3006 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3007 /// for a 16 byte align requirement.
3009 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3010 SelectionDAG& DAG) const {
3011 MachineFunction &MF = DAG.getMachineFunction();
3012 const TargetMachine &TM = MF.getTarget();
3013 const X86RegisterInfo *RegInfo =
3014 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3015 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3016 unsigned StackAlignment = TFI.getStackAlignment();
3017 uint64_t AlignMask = StackAlignment - 1;
3018 int64_t Offset = StackSize;
3019 unsigned SlotSize = RegInfo->getSlotSize();
3020 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3021 // Number smaller than 12 so just add the difference.
3022 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3024 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3025 Offset = ((~AlignMask) & Offset) + StackAlignment +
3026 (StackAlignment-SlotSize);
3031 /// MatchingStackOffset - Return true if the given stack call argument is
3032 /// already available in the same position (relatively) of the caller's
3033 /// incoming argument stack.
3035 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3036 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3037 const X86InstrInfo *TII) {
3038 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3040 if (Arg.getOpcode() == ISD::CopyFromReg) {
3041 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3042 if (!TargetRegisterInfo::isVirtualRegister(VR))
3044 MachineInstr *Def = MRI->getVRegDef(VR);
3047 if (!Flags.isByVal()) {
3048 if (!TII->isLoadFromStackSlot(Def, FI))
3051 unsigned Opcode = Def->getOpcode();
3052 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3053 Def->getOperand(1).isFI()) {
3054 FI = Def->getOperand(1).getIndex();
3055 Bytes = Flags.getByValSize();
3059 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3060 if (Flags.isByVal())
3061 // ByVal argument is passed in as a pointer but it's now being
3062 // dereferenced. e.g.
3063 // define @foo(%struct.X* %A) {
3064 // tail call @bar(%struct.X* byval %A)
3067 SDValue Ptr = Ld->getBasePtr();
3068 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3071 FI = FINode->getIndex();
3072 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3073 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3074 FI = FINode->getIndex();
3075 Bytes = Flags.getByValSize();
3079 assert(FI != INT_MAX);
3080 if (!MFI->isFixedObjectIndex(FI))
3082 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3085 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3086 /// for tail call optimization. Targets which want to do tail call
3087 /// optimization should implement this function.
3089 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3090 CallingConv::ID CalleeCC,
3092 bool isCalleeStructRet,
3093 bool isCallerStructRet,
3095 const SmallVectorImpl<ISD::OutputArg> &Outs,
3096 const SmallVectorImpl<SDValue> &OutVals,
3097 const SmallVectorImpl<ISD::InputArg> &Ins,
3098 SelectionDAG &DAG) const {
3099 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3102 // If -tailcallopt is specified, make fastcc functions tail-callable.
3103 const MachineFunction &MF = DAG.getMachineFunction();
3104 const Function *CallerF = MF.getFunction();
3106 // If the function return type is x86_fp80 and the callee return type is not,
3107 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3108 // perform a tailcall optimization here.
3109 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3112 CallingConv::ID CallerCC = CallerF->getCallingConv();
3113 bool CCMatch = CallerCC == CalleeCC;
3114 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3115 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3117 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3118 if (IsTailCallConvention(CalleeCC) && CCMatch)
3123 // Look for obvious safe cases to perform tail call optimization that do not
3124 // require ABI changes. This is what gcc calls sibcall.
3126 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3127 // emit a special epilogue.
3128 const X86RegisterInfo *RegInfo =
3129 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3130 if (RegInfo->needsStackRealignment(MF))
3133 // Also avoid sibcall optimization if either caller or callee uses struct
3134 // return semantics.
3135 if (isCalleeStructRet || isCallerStructRet)
3138 // An stdcall/thiscall caller is expected to clean up its arguments; the
3139 // callee isn't going to do that.
3140 // FIXME: this is more restrictive than needed. We could produce a tailcall
3141 // when the stack adjustment matches. For example, with a thiscall that takes
3142 // only one argument.
3143 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3144 CallerCC == CallingConv::X86_ThisCall))
3147 // Do not sibcall optimize vararg calls unless all arguments are passed via
3149 if (isVarArg && !Outs.empty()) {
3151 // Optimizing for varargs on Win64 is unlikely to be safe without
3152 // additional testing.
3153 if (IsCalleeWin64 || IsCallerWin64)
3156 SmallVector<CCValAssign, 16> ArgLocs;
3157 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3158 getTargetMachine(), ArgLocs, *DAG.getContext());
3160 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3161 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3162 if (!ArgLocs[i].isRegLoc())
3166 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3167 // stack. Therefore, if it's not used by the call it is not safe to optimize
3168 // this into a sibcall.
3169 bool Unused = false;
3170 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3177 SmallVector<CCValAssign, 16> RVLocs;
3178 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3179 getTargetMachine(), RVLocs, *DAG.getContext());
3180 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3181 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3182 CCValAssign &VA = RVLocs[i];
3183 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3188 // If the calling conventions do not match, then we'd better make sure the
3189 // results are returned in the same way as what the caller expects.
3191 SmallVector<CCValAssign, 16> RVLocs1;
3192 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3193 getTargetMachine(), RVLocs1, *DAG.getContext());
3194 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3196 SmallVector<CCValAssign, 16> RVLocs2;
3197 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3198 getTargetMachine(), RVLocs2, *DAG.getContext());
3199 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3201 if (RVLocs1.size() != RVLocs2.size())
3203 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3204 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3206 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3208 if (RVLocs1[i].isRegLoc()) {
3209 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3212 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3218 // If the callee takes no arguments then go on to check the results of the
3220 if (!Outs.empty()) {
3221 // Check if stack adjustment is needed. For now, do not do this if any
3222 // argument is passed on the stack.
3223 SmallVector<CCValAssign, 16> ArgLocs;
3224 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3225 getTargetMachine(), ArgLocs, *DAG.getContext());
3227 // Allocate shadow area for Win64
3229 CCInfo.AllocateStack(32, 8);
3231 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3232 if (CCInfo.getNextStackOffset()) {
3233 MachineFunction &MF = DAG.getMachineFunction();
3234 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3237 // Check if the arguments are already laid out in the right way as
3238 // the caller's fixed stack objects.
3239 MachineFrameInfo *MFI = MF.getFrameInfo();
3240 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3241 const X86InstrInfo *TII =
3242 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3243 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3244 CCValAssign &VA = ArgLocs[i];
3245 SDValue Arg = OutVals[i];
3246 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3247 if (VA.getLocInfo() == CCValAssign::Indirect)
3249 if (!VA.isRegLoc()) {
3250 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3257 // If the tailcall address may be in a register, then make sure it's
3258 // possible to register allocate for it. In 32-bit, the call address can
3259 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3260 // callee-saved registers are restored. These happen to be the same
3261 // registers used to pass 'inreg' arguments so watch out for those.
3262 if (!Subtarget->is64Bit() &&
3263 ((!isa<GlobalAddressSDNode>(Callee) &&
3264 !isa<ExternalSymbolSDNode>(Callee)) ||
3265 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3266 unsigned NumInRegs = 0;
3267 // In PIC we need an extra register to formulate the address computation
3269 unsigned MaxInRegs =
3270 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3272 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3273 CCValAssign &VA = ArgLocs[i];
3276 unsigned Reg = VA.getLocReg();
3279 case X86::EAX: case X86::EDX: case X86::ECX:
3280 if (++NumInRegs == MaxInRegs)
3292 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3293 const TargetLibraryInfo *libInfo) const {
3294 return X86::createFastISel(funcInfo, libInfo);
3297 //===----------------------------------------------------------------------===//
3298 // Other Lowering Hooks
3299 //===----------------------------------------------------------------------===//
3301 static bool MayFoldLoad(SDValue Op) {
3302 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3305 static bool MayFoldIntoStore(SDValue Op) {
3306 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3309 static bool isTargetShuffle(unsigned Opcode) {
3311 default: return false;
3312 case X86ISD::PSHUFD:
3313 case X86ISD::PSHUFHW:
3314 case X86ISD::PSHUFLW:
3316 case X86ISD::PALIGNR:
3317 case X86ISD::MOVLHPS:
3318 case X86ISD::MOVLHPD:
3319 case X86ISD::MOVHLPS:
3320 case X86ISD::MOVLPS:
3321 case X86ISD::MOVLPD:
3322 case X86ISD::MOVSHDUP:
3323 case X86ISD::MOVSLDUP:
3324 case X86ISD::MOVDDUP:
3327 case X86ISD::UNPCKL:
3328 case X86ISD::UNPCKH:
3329 case X86ISD::VPERMILP:
3330 case X86ISD::VPERM2X128:
3331 case X86ISD::VPERMI:
3336 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3337 SDValue V1, SelectionDAG &DAG) {
3339 default: llvm_unreachable("Unknown x86 shuffle node");
3340 case X86ISD::MOVSHDUP:
3341 case X86ISD::MOVSLDUP:
3342 case X86ISD::MOVDDUP:
3343 return DAG.getNode(Opc, dl, VT, V1);
3347 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3348 SDValue V1, unsigned TargetMask,
3349 SelectionDAG &DAG) {
3351 default: llvm_unreachable("Unknown x86 shuffle node");
3352 case X86ISD::PSHUFD:
3353 case X86ISD::PSHUFHW:
3354 case X86ISD::PSHUFLW:
3355 case X86ISD::VPERMILP:
3356 case X86ISD::VPERMI:
3357 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3361 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3362 SDValue V1, SDValue V2, unsigned TargetMask,
3363 SelectionDAG &DAG) {
3365 default: llvm_unreachable("Unknown x86 shuffle node");
3366 case X86ISD::PALIGNR:
3368 case X86ISD::VPERM2X128:
3369 return DAG.getNode(Opc, dl, VT, V1, V2,
3370 DAG.getConstant(TargetMask, MVT::i8));
3374 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3375 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3377 default: llvm_unreachable("Unknown x86 shuffle node");
3378 case X86ISD::MOVLHPS:
3379 case X86ISD::MOVLHPD:
3380 case X86ISD::MOVHLPS:
3381 case X86ISD::MOVLPS:
3382 case X86ISD::MOVLPD:
3385 case X86ISD::UNPCKL:
3386 case X86ISD::UNPCKH:
3387 return DAG.getNode(Opc, dl, VT, V1, V2);
3391 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3392 MachineFunction &MF = DAG.getMachineFunction();
3393 const X86RegisterInfo *RegInfo =
3394 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3395 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3396 int ReturnAddrIndex = FuncInfo->getRAIndex();
3398 if (ReturnAddrIndex == 0) {
3399 // Set up a frame object for the return address.
3400 unsigned SlotSize = RegInfo->getSlotSize();
3401 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3404 FuncInfo->setRAIndex(ReturnAddrIndex);
3407 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3410 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3411 bool hasSymbolicDisplacement) {
3412 // Offset should fit into 32 bit immediate field.
3413 if (!isInt<32>(Offset))
3416 // If we don't have a symbolic displacement - we don't have any extra
3418 if (!hasSymbolicDisplacement)
3421 // FIXME: Some tweaks might be needed for medium code model.
3422 if (M != CodeModel::Small && M != CodeModel::Kernel)
3425 // For small code model we assume that latest object is 16MB before end of 31
3426 // bits boundary. We may also accept pretty large negative constants knowing
3427 // that all objects are in the positive half of address space.
3428 if (M == CodeModel::Small && Offset < 16*1024*1024)
3431 // For kernel code model we know that all object resist in the negative half
3432 // of 32bits address space. We may not accept negative offsets, since they may
3433 // be just off and we may accept pretty large positive ones.
3434 if (M == CodeModel::Kernel && Offset > 0)
3440 /// isCalleePop - Determines whether the callee is required to pop its
3441 /// own arguments. Callee pop is necessary to support tail calls.
3442 bool X86::isCalleePop(CallingConv::ID CallingConv,
3443 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3447 switch (CallingConv) {
3450 case CallingConv::X86_StdCall:
3452 case CallingConv::X86_FastCall:
3454 case CallingConv::X86_ThisCall:
3456 case CallingConv::Fast:
3458 case CallingConv::GHC:
3460 case CallingConv::HiPE:
3465 /// \brief Return true if the condition is an unsigned comparison operation.
3466 static bool isX86CCUnsigned(unsigned X86CC) {
3468 default: llvm_unreachable("Invalid integer condition!");
3469 case X86::COND_E: return true;
3470 case X86::COND_G: return false;
3471 case X86::COND_GE: return false;
3472 case X86::COND_L: return false;
3473 case X86::COND_LE: return false;
3474 case X86::COND_NE: return true;
3475 case X86::COND_B: return true;
3476 case X86::COND_A: return true;
3477 case X86::COND_BE: return true;
3478 case X86::COND_AE: return true;
3480 llvm_unreachable("covered switch fell through?!");
3483 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3484 /// specific condition code, returning the condition code and the LHS/RHS of the
3485 /// comparison to make.
3486 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3487 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3489 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3490 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3491 // X > -1 -> X == 0, jump !sign.
3492 RHS = DAG.getConstant(0, RHS.getValueType());
3493 return X86::COND_NS;
3495 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3496 // X < 0 -> X == 0, jump on sign.
3499 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3501 RHS = DAG.getConstant(0, RHS.getValueType());
3502 return X86::COND_LE;
3506 switch (SetCCOpcode) {
3507 default: llvm_unreachable("Invalid integer condition!");
3508 case ISD::SETEQ: return X86::COND_E;
3509 case ISD::SETGT: return X86::COND_G;
3510 case ISD::SETGE: return X86::COND_GE;
3511 case ISD::SETLT: return X86::COND_L;
3512 case ISD::SETLE: return X86::COND_LE;
3513 case ISD::SETNE: return X86::COND_NE;
3514 case ISD::SETULT: return X86::COND_B;
3515 case ISD::SETUGT: return X86::COND_A;
3516 case ISD::SETULE: return X86::COND_BE;
3517 case ISD::SETUGE: return X86::COND_AE;
3521 // First determine if it is required or is profitable to flip the operands.
3523 // If LHS is a foldable load, but RHS is not, flip the condition.
3524 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3525 !ISD::isNON_EXTLoad(RHS.getNode())) {
3526 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3527 std::swap(LHS, RHS);
3530 switch (SetCCOpcode) {
3536 std::swap(LHS, RHS);
3540 // On a floating point condition, the flags are set as follows:
3542 // 0 | 0 | 0 | X > Y
3543 // 0 | 0 | 1 | X < Y
3544 // 1 | 0 | 0 | X == Y
3545 // 1 | 1 | 1 | unordered
3546 switch (SetCCOpcode) {
3547 default: llvm_unreachable("Condcode should be pre-legalized away");
3549 case ISD::SETEQ: return X86::COND_E;
3550 case ISD::SETOLT: // flipped
3552 case ISD::SETGT: return X86::COND_A;
3553 case ISD::SETOLE: // flipped
3555 case ISD::SETGE: return X86::COND_AE;
3556 case ISD::SETUGT: // flipped
3558 case ISD::SETLT: return X86::COND_B;
3559 case ISD::SETUGE: // flipped
3561 case ISD::SETLE: return X86::COND_BE;
3563 case ISD::SETNE: return X86::COND_NE;
3564 case ISD::SETUO: return X86::COND_P;
3565 case ISD::SETO: return X86::COND_NP;
3567 case ISD::SETUNE: return X86::COND_INVALID;
3571 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3572 /// code. Current x86 isa includes the following FP cmov instructions:
3573 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3574 static bool hasFPCMov(unsigned X86CC) {
3590 /// isFPImmLegal - Returns true if the target can instruction select the
3591 /// specified FP immediate natively. If false, the legalizer will
3592 /// materialize the FP immediate as a load from a constant pool.
3593 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3594 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3595 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3601 /// \brief Returns true if it is beneficial to convert a load of a constant
3602 /// to just the constant itself.
3603 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3605 assert(Ty->isIntegerTy());
3607 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3608 if (BitSize == 0 || BitSize > 64)
3613 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3614 /// the specified range (L, H].
3615 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3616 return (Val < 0) || (Val >= Low && Val < Hi);
3619 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3620 /// specified value.
3621 static bool isUndefOrEqual(int Val, int CmpVal) {
3622 return (Val < 0 || Val == CmpVal);
3625 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3626 /// from position Pos and ending in Pos+Size, falls within the specified
3627 /// sequential range (L, L+Pos]. or is undef.
3628 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3629 unsigned Pos, unsigned Size, int Low) {
3630 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3631 if (!isUndefOrEqual(Mask[i], Low))
3636 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3637 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3638 /// the second operand.
3639 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3640 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3641 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3642 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3643 return (Mask[0] < 2 && Mask[1] < 2);
3647 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3648 /// is suitable for input to PSHUFHW.
3649 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3650 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3653 // Lower quadword copied in order or undef.
3654 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3657 // Upper quadword shuffled.
3658 for (unsigned i = 4; i != 8; ++i)
3659 if (!isUndefOrInRange(Mask[i], 4, 8))
3662 if (VT == MVT::v16i16) {
3663 // Lower quadword copied in order or undef.
3664 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3667 // Upper quadword shuffled.
3668 for (unsigned i = 12; i != 16; ++i)
3669 if (!isUndefOrInRange(Mask[i], 12, 16))
3676 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3677 /// is suitable for input to PSHUFLW.
3678 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3679 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3682 // Upper quadword copied in order.
3683 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3686 // Lower quadword shuffled.
3687 for (unsigned i = 0; i != 4; ++i)
3688 if (!isUndefOrInRange(Mask[i], 0, 4))
3691 if (VT == MVT::v16i16) {
3692 // Upper quadword copied in order.
3693 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3696 // Lower quadword shuffled.
3697 for (unsigned i = 8; i != 12; ++i)
3698 if (!isUndefOrInRange(Mask[i], 8, 12))
3705 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3706 /// is suitable for input to PALIGNR.
3707 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3708 const X86Subtarget *Subtarget) {
3709 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3710 (VT.is256BitVector() && !Subtarget->hasInt256()))
3713 unsigned NumElts = VT.getVectorNumElements();
3714 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3715 unsigned NumLaneElts = NumElts/NumLanes;
3717 // Do not handle 64-bit element shuffles with palignr.
3718 if (NumLaneElts == 2)
3721 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3723 for (i = 0; i != NumLaneElts; ++i) {
3728 // Lane is all undef, go to next lane
3729 if (i == NumLaneElts)
3732 int Start = Mask[i+l];
3734 // Make sure its in this lane in one of the sources
3735 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3736 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3739 // If not lane 0, then we must match lane 0
3740 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3743 // Correct second source to be contiguous with first source
3744 if (Start >= (int)NumElts)
3745 Start -= NumElts - NumLaneElts;
3747 // Make sure we're shifting in the right direction.
3748 if (Start <= (int)(i+l))
3753 // Check the rest of the elements to see if they are consecutive.
3754 for (++i; i != NumLaneElts; ++i) {
3755 int Idx = Mask[i+l];
3757 // Make sure its in this lane
3758 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3759 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3762 // If not lane 0, then we must match lane 0
3763 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3766 if (Idx >= (int)NumElts)
3767 Idx -= NumElts - NumLaneElts;
3769 if (!isUndefOrEqual(Idx, Start+i))
3778 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3779 /// the two vector operands have swapped position.
3780 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3781 unsigned NumElems) {
3782 for (unsigned i = 0; i != NumElems; ++i) {
3786 else if (idx < (int)NumElems)
3787 Mask[i] = idx + NumElems;
3789 Mask[i] = idx - NumElems;
3793 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3794 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3795 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3796 /// reverse of what x86 shuffles want.
3797 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3799 unsigned NumElems = VT.getVectorNumElements();
3800 unsigned NumLanes = VT.getSizeInBits()/128;
3801 unsigned NumLaneElems = NumElems/NumLanes;
3803 if (NumLaneElems != 2 && NumLaneElems != 4)
3806 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3807 bool symetricMaskRequired =
3808 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3810 // VSHUFPSY divides the resulting vector into 4 chunks.
3811 // The sources are also splitted into 4 chunks, and each destination
3812 // chunk must come from a different source chunk.
3814 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3815 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3817 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3818 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3820 // VSHUFPDY divides the resulting vector into 4 chunks.
3821 // The sources are also splitted into 4 chunks, and each destination
3822 // chunk must come from a different source chunk.
3824 // SRC1 => X3 X2 X1 X0
3825 // SRC2 => Y3 Y2 Y1 Y0
3827 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3829 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3830 unsigned HalfLaneElems = NumLaneElems/2;
3831 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3832 for (unsigned i = 0; i != NumLaneElems; ++i) {
3833 int Idx = Mask[i+l];
3834 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3835 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3837 // For VSHUFPSY, the mask of the second half must be the same as the
3838 // first but with the appropriate offsets. This works in the same way as
3839 // VPERMILPS works with masks.
3840 if (!symetricMaskRequired || Idx < 0)
3842 if (MaskVal[i] < 0) {
3843 MaskVal[i] = Idx - l;
3846 if ((signed)(Idx - l) != MaskVal[i])
3854 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3855 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3856 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3857 if (!VT.is128BitVector())
3860 unsigned NumElems = VT.getVectorNumElements();
3865 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3866 return isUndefOrEqual(Mask[0], 6) &&
3867 isUndefOrEqual(Mask[1], 7) &&
3868 isUndefOrEqual(Mask[2], 2) &&
3869 isUndefOrEqual(Mask[3], 3);
3872 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3873 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3875 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3876 if (!VT.is128BitVector())
3879 unsigned NumElems = VT.getVectorNumElements();
3884 return isUndefOrEqual(Mask[0], 2) &&
3885 isUndefOrEqual(Mask[1], 3) &&
3886 isUndefOrEqual(Mask[2], 2) &&
3887 isUndefOrEqual(Mask[3], 3);
3890 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3891 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3892 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3893 if (!VT.is128BitVector())
3896 unsigned NumElems = VT.getVectorNumElements();
3898 if (NumElems != 2 && NumElems != 4)
3901 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3902 if (!isUndefOrEqual(Mask[i], i + NumElems))
3905 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3906 if (!isUndefOrEqual(Mask[i], i))
3912 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3913 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3914 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3915 if (!VT.is128BitVector())
3918 unsigned NumElems = VT.getVectorNumElements();
3920 if (NumElems != 2 && NumElems != 4)
3923 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3924 if (!isUndefOrEqual(Mask[i], i))
3927 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3928 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3935 // Some special combinations that can be optimized.
3938 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3939 SelectionDAG &DAG) {
3940 MVT VT = SVOp->getSimpleValueType(0);
3943 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3946 ArrayRef<int> Mask = SVOp->getMask();
3948 // These are the special masks that may be optimized.
3949 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3950 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3951 bool MatchEvenMask = true;
3952 bool MatchOddMask = true;
3953 for (int i=0; i<8; ++i) {
3954 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3955 MatchEvenMask = false;
3956 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3957 MatchOddMask = false;
3960 if (!MatchEvenMask && !MatchOddMask)
3963 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3965 SDValue Op0 = SVOp->getOperand(0);
3966 SDValue Op1 = SVOp->getOperand(1);
3968 if (MatchEvenMask) {
3969 // Shift the second operand right to 32 bits.
3970 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3971 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3973 // Shift the first operand left to 32 bits.
3974 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3975 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3977 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3978 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3981 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3982 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3983 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3984 bool HasInt256, bool V2IsSplat = false) {
3986 assert(VT.getSizeInBits() >= 128 &&
3987 "Unsupported vector type for unpckl");
3989 // AVX defines UNPCK* to operate independently on 128-bit lanes.
3991 unsigned NumOf256BitLanes;
3992 unsigned NumElts = VT.getVectorNumElements();
3993 if (VT.is256BitVector()) {
3994 if (NumElts != 4 && NumElts != 8 &&
3995 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3998 NumOf256BitLanes = 1;
3999 } else if (VT.is512BitVector()) {
4000 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4001 "Unsupported vector type for unpckh");
4003 NumOf256BitLanes = 2;
4006 NumOf256BitLanes = 1;
4009 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4010 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4012 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4013 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4014 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4015 int BitI = Mask[l256*NumEltsInStride+l+i];
4016 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4017 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4019 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4021 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4029 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4030 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4031 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4032 bool HasInt256, bool V2IsSplat = false) {
4033 assert(VT.getSizeInBits() >= 128 &&
4034 "Unsupported vector type for unpckh");
4036 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4038 unsigned NumOf256BitLanes;
4039 unsigned NumElts = VT.getVectorNumElements();
4040 if (VT.is256BitVector()) {
4041 if (NumElts != 4 && NumElts != 8 &&
4042 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4045 NumOf256BitLanes = 1;
4046 } else if (VT.is512BitVector()) {
4047 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4048 "Unsupported vector type for unpckh");
4050 NumOf256BitLanes = 2;
4053 NumOf256BitLanes = 1;
4056 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4057 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4059 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4060 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4061 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4062 int BitI = Mask[l256*NumEltsInStride+l+i];
4063 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4064 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4066 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4068 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4076 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4077 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4079 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4080 unsigned NumElts = VT.getVectorNumElements();
4081 bool Is256BitVec = VT.is256BitVector();
4083 if (VT.is512BitVector())
4085 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4086 "Unsupported vector type for unpckh");
4088 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4089 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4092 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4093 // FIXME: Need a better way to get rid of this, there's no latency difference
4094 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4095 // the former later. We should also remove the "_undef" special mask.
4096 if (NumElts == 4 && Is256BitVec)
4099 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4100 // independently on 128-bit lanes.
4101 unsigned NumLanes = VT.getSizeInBits()/128;
4102 unsigned NumLaneElts = NumElts/NumLanes;
4104 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4105 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4106 int BitI = Mask[l+i];
4107 int BitI1 = Mask[l+i+1];
4109 if (!isUndefOrEqual(BitI, j))
4111 if (!isUndefOrEqual(BitI1, j))
4119 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4120 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4122 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4123 unsigned NumElts = VT.getVectorNumElements();
4125 if (VT.is512BitVector())
4128 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4129 "Unsupported vector type for unpckh");
4131 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4132 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4135 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4136 // independently on 128-bit lanes.
4137 unsigned NumLanes = VT.getSizeInBits()/128;
4138 unsigned NumLaneElts = NumElts/NumLanes;
4140 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4141 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4142 int BitI = Mask[l+i];
4143 int BitI1 = Mask[l+i+1];
4144 if (!isUndefOrEqual(BitI, j))
4146 if (!isUndefOrEqual(BitI1, j))
4153 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4154 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4155 /// MOVSD, and MOVD, i.e. setting the lowest element.
4156 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4157 if (VT.getVectorElementType().getSizeInBits() < 32)
4159 if (!VT.is128BitVector())
4162 unsigned NumElts = VT.getVectorNumElements();
4164 if (!isUndefOrEqual(Mask[0], NumElts))
4167 for (unsigned i = 1; i != NumElts; ++i)
4168 if (!isUndefOrEqual(Mask[i], i))
4174 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4175 /// as permutations between 128-bit chunks or halves. As an example: this
4177 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4178 /// The first half comes from the second half of V1 and the second half from the
4179 /// the second half of V2.
4180 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4181 if (!HasFp256 || !VT.is256BitVector())
4184 // The shuffle result is divided into half A and half B. In total the two
4185 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4186 // B must come from C, D, E or F.
4187 unsigned HalfSize = VT.getVectorNumElements()/2;
4188 bool MatchA = false, MatchB = false;
4190 // Check if A comes from one of C, D, E, F.
4191 for (unsigned Half = 0; Half != 4; ++Half) {
4192 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4198 // Check if B comes from one of C, D, E, F.
4199 for (unsigned Half = 0; Half != 4; ++Half) {
4200 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4206 return MatchA && MatchB;
4209 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4210 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4211 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4212 MVT VT = SVOp->getSimpleValueType(0);
4214 unsigned HalfSize = VT.getVectorNumElements()/2;
4216 unsigned FstHalf = 0, SndHalf = 0;
4217 for (unsigned i = 0; i < HalfSize; ++i) {
4218 if (SVOp->getMaskElt(i) > 0) {
4219 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4223 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4224 if (SVOp->getMaskElt(i) > 0) {
4225 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4230 return (FstHalf | (SndHalf << 4));
4233 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4234 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4235 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4239 unsigned NumElts = VT.getVectorNumElements();
4241 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4242 for (unsigned i = 0; i != NumElts; ++i) {
4245 Imm8 |= Mask[i] << (i*2);
4250 unsigned LaneSize = 4;
4251 SmallVector<int, 4> MaskVal(LaneSize, -1);
4253 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4254 for (unsigned i = 0; i != LaneSize; ++i) {
4255 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4259 if (MaskVal[i] < 0) {
4260 MaskVal[i] = Mask[i+l] - l;
4261 Imm8 |= MaskVal[i] << (i*2);
4264 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4271 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4272 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4273 /// Note that VPERMIL mask matching is different depending whether theunderlying
4274 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4275 /// to the same elements of the low, but to the higher half of the source.
4276 /// In VPERMILPD the two lanes could be shuffled independently of each other
4277 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4278 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4279 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4280 if (VT.getSizeInBits() < 256 || EltSize < 32)
4282 bool symetricMaskRequired = (EltSize == 32);
4283 unsigned NumElts = VT.getVectorNumElements();
4285 unsigned NumLanes = VT.getSizeInBits()/128;
4286 unsigned LaneSize = NumElts/NumLanes;
4287 // 2 or 4 elements in one lane
4289 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4290 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4291 for (unsigned i = 0; i != LaneSize; ++i) {
4292 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4294 if (symetricMaskRequired) {
4295 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4296 ExpectedMaskVal[i] = Mask[i+l] - l;
4299 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4307 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4308 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4309 /// element of vector 2 and the other elements to come from vector 1 in order.
4310 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4311 bool V2IsSplat = false, bool V2IsUndef = false) {
4312 if (!VT.is128BitVector())
4315 unsigned NumOps = VT.getVectorNumElements();
4316 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4319 if (!isUndefOrEqual(Mask[0], 0))
4322 for (unsigned i = 1; i != NumOps; ++i)
4323 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4324 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4325 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4331 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4332 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4333 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4334 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4335 const X86Subtarget *Subtarget) {
4336 if (!Subtarget->hasSSE3())
4339 unsigned NumElems = VT.getVectorNumElements();
4341 if ((VT.is128BitVector() && NumElems != 4) ||
4342 (VT.is256BitVector() && NumElems != 8) ||
4343 (VT.is512BitVector() && NumElems != 16))
4346 // "i+1" is the value the indexed mask element must have
4347 for (unsigned i = 0; i != NumElems; i += 2)
4348 if (!isUndefOrEqual(Mask[i], i+1) ||
4349 !isUndefOrEqual(Mask[i+1], i+1))
4355 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4356 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4357 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4358 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4359 const X86Subtarget *Subtarget) {
4360 if (!Subtarget->hasSSE3())
4363 unsigned NumElems = VT.getVectorNumElements();
4365 if ((VT.is128BitVector() && NumElems != 4) ||
4366 (VT.is256BitVector() && NumElems != 8) ||
4367 (VT.is512BitVector() && NumElems != 16))
4370 // "i" is the value the indexed mask element must have
4371 for (unsigned i = 0; i != NumElems; i += 2)
4372 if (!isUndefOrEqual(Mask[i], i) ||
4373 !isUndefOrEqual(Mask[i+1], i))
4379 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4380 /// specifies a shuffle of elements that is suitable for input to 256-bit
4381 /// version of MOVDDUP.
4382 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4383 if (!HasFp256 || !VT.is256BitVector())
4386 unsigned NumElts = VT.getVectorNumElements();
4390 for (unsigned i = 0; i != NumElts/2; ++i)
4391 if (!isUndefOrEqual(Mask[i], 0))
4393 for (unsigned i = NumElts/2; i != NumElts; ++i)
4394 if (!isUndefOrEqual(Mask[i], NumElts/2))
4399 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4400 /// specifies a shuffle of elements that is suitable for input to 128-bit
4401 /// version of MOVDDUP.
4402 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4403 if (!VT.is128BitVector())
4406 unsigned e = VT.getVectorNumElements() / 2;
4407 for (unsigned i = 0; i != e; ++i)
4408 if (!isUndefOrEqual(Mask[i], i))
4410 for (unsigned i = 0; i != e; ++i)
4411 if (!isUndefOrEqual(Mask[e+i], i))
4416 /// isVEXTRACTIndex - Return true if the specified
4417 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4418 /// suitable for instruction that extract 128 or 256 bit vectors
4419 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4420 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4421 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4424 // The index should be aligned on a vecWidth-bit boundary.
4426 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4428 MVT VT = N->getSimpleValueType(0);
4429 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4430 bool Result = (Index * ElSize) % vecWidth == 0;
4435 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4436 /// operand specifies a subvector insert that is suitable for input to
4437 /// insertion of 128 or 256-bit subvectors
4438 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4439 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4440 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4442 // The index should be aligned on a vecWidth-bit boundary.
4444 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4446 MVT VT = N->getSimpleValueType(0);
4447 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4448 bool Result = (Index * ElSize) % vecWidth == 0;
4453 bool X86::isVINSERT128Index(SDNode *N) {
4454 return isVINSERTIndex(N, 128);
4457 bool X86::isVINSERT256Index(SDNode *N) {
4458 return isVINSERTIndex(N, 256);
4461 bool X86::isVEXTRACT128Index(SDNode *N) {
4462 return isVEXTRACTIndex(N, 128);
4465 bool X86::isVEXTRACT256Index(SDNode *N) {
4466 return isVEXTRACTIndex(N, 256);
4469 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4470 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4471 /// Handles 128-bit and 256-bit.
4472 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4473 MVT VT = N->getSimpleValueType(0);
4475 assert((VT.getSizeInBits() >= 128) &&
4476 "Unsupported vector type for PSHUF/SHUFP");
4478 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4479 // independently on 128-bit lanes.
4480 unsigned NumElts = VT.getVectorNumElements();
4481 unsigned NumLanes = VT.getSizeInBits()/128;
4482 unsigned NumLaneElts = NumElts/NumLanes;
4484 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4485 "Only supports 2, 4 or 8 elements per lane");
4487 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4489 for (unsigned i = 0; i != NumElts; ++i) {
4490 int Elt = N->getMaskElt(i);
4491 if (Elt < 0) continue;
4492 Elt &= NumLaneElts - 1;
4493 unsigned ShAmt = (i << Shift) % 8;
4494 Mask |= Elt << ShAmt;
4500 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4501 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4502 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4503 MVT VT = N->getSimpleValueType(0);
4505 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4506 "Unsupported vector type for PSHUFHW");
4508 unsigned NumElts = VT.getVectorNumElements();
4511 for (unsigned l = 0; l != NumElts; l += 8) {
4512 // 8 nodes per lane, but we only care about the last 4.
4513 for (unsigned i = 0; i < 4; ++i) {
4514 int Elt = N->getMaskElt(l+i+4);
4515 if (Elt < 0) continue;
4516 Elt &= 0x3; // only 2-bits.
4517 Mask |= Elt << (i * 2);
4524 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4525 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4526 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4527 MVT VT = N->getSimpleValueType(0);
4529 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4530 "Unsupported vector type for PSHUFHW");
4532 unsigned NumElts = VT.getVectorNumElements();
4535 for (unsigned l = 0; l != NumElts; l += 8) {
4536 // 8 nodes per lane, but we only care about the first 4.
4537 for (unsigned i = 0; i < 4; ++i) {
4538 int Elt = N->getMaskElt(l+i);
4539 if (Elt < 0) continue;
4540 Elt &= 0x3; // only 2-bits
4541 Mask |= Elt << (i * 2);
4548 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4549 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4550 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4551 MVT VT = SVOp->getSimpleValueType(0);
4552 unsigned EltSize = VT.is512BitVector() ? 1 :
4553 VT.getVectorElementType().getSizeInBits() >> 3;
4555 unsigned NumElts = VT.getVectorNumElements();
4556 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4557 unsigned NumLaneElts = NumElts/NumLanes;
4561 for (i = 0; i != NumElts; ++i) {
4562 Val = SVOp->getMaskElt(i);
4566 if (Val >= (int)NumElts)
4567 Val -= NumElts - NumLaneElts;
4569 assert(Val - i > 0 && "PALIGNR imm should be positive");
4570 return (Val - i) * EltSize;
4573 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4574 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4575 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4576 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4579 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4581 MVT VecVT = N->getOperand(0).getSimpleValueType();
4582 MVT ElVT = VecVT.getVectorElementType();
4584 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4585 return Index / NumElemsPerChunk;
4588 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4589 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4590 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4591 llvm_unreachable("Illegal insert subvector for VINSERT");
4594 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4596 MVT VecVT = N->getSimpleValueType(0);
4597 MVT ElVT = VecVT.getVectorElementType();
4599 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4600 return Index / NumElemsPerChunk;
4603 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4604 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4605 /// and VINSERTI128 instructions.
4606 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4607 return getExtractVEXTRACTImmediate(N, 128);
4610 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4611 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4612 /// and VINSERTI64x4 instructions.
4613 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4614 return getExtractVEXTRACTImmediate(N, 256);
4617 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4618 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4619 /// and VINSERTI128 instructions.
4620 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4621 return getInsertVINSERTImmediate(N, 128);
4624 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4625 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4626 /// and VINSERTI64x4 instructions.
4627 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4628 return getInsertVINSERTImmediate(N, 256);
4631 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4633 bool X86::isZeroNode(SDValue Elt) {
4634 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4635 return CN->isNullValue();
4636 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4637 return CFP->getValueAPF().isPosZero();
4641 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4642 /// their permute mask.
4643 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4644 SelectionDAG &DAG) {
4645 MVT VT = SVOp->getSimpleValueType(0);
4646 unsigned NumElems = VT.getVectorNumElements();
4647 SmallVector<int, 8> MaskVec;
4649 for (unsigned i = 0; i != NumElems; ++i) {
4650 int Idx = SVOp->getMaskElt(i);
4652 if (Idx < (int)NumElems)
4657 MaskVec.push_back(Idx);
4659 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4660 SVOp->getOperand(0), &MaskVec[0]);
4663 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4664 /// match movhlps. The lower half elements should come from upper half of
4665 /// V1 (and in order), and the upper half elements should come from the upper
4666 /// half of V2 (and in order).
4667 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4668 if (!VT.is128BitVector())
4670 if (VT.getVectorNumElements() != 4)
4672 for (unsigned i = 0, e = 2; i != e; ++i)
4673 if (!isUndefOrEqual(Mask[i], i+2))
4675 for (unsigned i = 2; i != 4; ++i)
4676 if (!isUndefOrEqual(Mask[i], i+4))
4681 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4682 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4684 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4685 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4687 N = N->getOperand(0).getNode();
4688 if (!ISD::isNON_EXTLoad(N))
4691 *LD = cast<LoadSDNode>(N);
4695 // Test whether the given value is a vector value which will be legalized
4697 static bool WillBeConstantPoolLoad(SDNode *N) {
4698 if (N->getOpcode() != ISD::BUILD_VECTOR)
4701 // Check for any non-constant elements.
4702 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4703 switch (N->getOperand(i).getNode()->getOpcode()) {
4705 case ISD::ConstantFP:
4712 // Vectors of all-zeros and all-ones are materialized with special
4713 // instructions rather than being loaded.
4714 return !ISD::isBuildVectorAllZeros(N) &&
4715 !ISD::isBuildVectorAllOnes(N);
4718 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4719 /// match movlp{s|d}. The lower half elements should come from lower half of
4720 /// V1 (and in order), and the upper half elements should come from the upper
4721 /// half of V2 (and in order). And since V1 will become the source of the
4722 /// MOVLP, it must be either a vector load or a scalar load to vector.
4723 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4724 ArrayRef<int> Mask, MVT VT) {
4725 if (!VT.is128BitVector())
4728 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4730 // Is V2 is a vector load, don't do this transformation. We will try to use
4731 // load folding shufps op.
4732 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4735 unsigned NumElems = VT.getVectorNumElements();
4737 if (NumElems != 2 && NumElems != 4)
4739 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4740 if (!isUndefOrEqual(Mask[i], i))
4742 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4743 if (!isUndefOrEqual(Mask[i], i+NumElems))
4748 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4750 static bool isSplatVector(SDNode *N) {
4751 if (N->getOpcode() != ISD::BUILD_VECTOR)
4754 SDValue SplatValue = N->getOperand(0);
4755 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4756 if (N->getOperand(i) != SplatValue)
4761 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4762 /// to an zero vector.
4763 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4764 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4765 SDValue V1 = N->getOperand(0);
4766 SDValue V2 = N->getOperand(1);
4767 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4768 for (unsigned i = 0; i != NumElems; ++i) {
4769 int Idx = N->getMaskElt(i);
4770 if (Idx >= (int)NumElems) {
4771 unsigned Opc = V2.getOpcode();
4772 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4774 if (Opc != ISD::BUILD_VECTOR ||
4775 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4777 } else if (Idx >= 0) {
4778 unsigned Opc = V1.getOpcode();
4779 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4781 if (Opc != ISD::BUILD_VECTOR ||
4782 !X86::isZeroNode(V1.getOperand(Idx)))
4789 /// getZeroVector - Returns a vector of specified type with all zero elements.
4791 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4792 SelectionDAG &DAG, SDLoc dl) {
4793 assert(VT.isVector() && "Expected a vector type");
4795 // Always build SSE zero vectors as <4 x i32> bitcasted
4796 // to their dest type. This ensures they get CSE'd.
4798 if (VT.is128BitVector()) { // SSE
4799 if (Subtarget->hasSSE2()) { // SSE2
4800 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4801 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4803 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4804 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4806 } else if (VT.is256BitVector()) { // AVX
4807 if (Subtarget->hasInt256()) { // AVX2
4808 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4809 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4810 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4811 array_lengthof(Ops));
4813 // 256-bit logic and arithmetic instructions in AVX are all
4814 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4815 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4816 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4817 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4818 array_lengthof(Ops));
4820 } else if (VT.is512BitVector()) { // AVX-512
4821 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4822 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4823 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4824 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4825 } else if (VT.getScalarType() == MVT::i1) {
4826 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4827 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4828 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4829 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4830 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4831 Ops, VT.getVectorNumElements());
4833 llvm_unreachable("Unexpected vector type");
4835 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4838 /// getOnesVector - Returns a vector of specified type with all bits set.
4839 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4840 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4841 /// Then bitcast to their original type, ensuring they get CSE'd.
4842 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4844 assert(VT.isVector() && "Expected a vector type");
4846 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4848 if (VT.is256BitVector()) {
4849 if (HasInt256) { // AVX2
4850 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4851 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4852 array_lengthof(Ops));
4854 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4855 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4857 } else if (VT.is128BitVector()) {
4858 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4860 llvm_unreachable("Unexpected vector type");
4862 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4865 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4866 /// that point to V2 points to its first element.
4867 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4868 for (unsigned i = 0; i != NumElems; ++i) {
4869 if (Mask[i] > (int)NumElems) {
4875 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4876 /// operation of specified width.
4877 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4879 unsigned NumElems = VT.getVectorNumElements();
4880 SmallVector<int, 8> Mask;
4881 Mask.push_back(NumElems);
4882 for (unsigned i = 1; i != NumElems; ++i)
4884 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4887 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4888 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4890 unsigned NumElems = VT.getVectorNumElements();
4891 SmallVector<int, 8> Mask;
4892 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4894 Mask.push_back(i + NumElems);
4896 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4899 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4900 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4902 unsigned NumElems = VT.getVectorNumElements();
4903 SmallVector<int, 8> Mask;
4904 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4905 Mask.push_back(i + Half);
4906 Mask.push_back(i + NumElems + Half);
4908 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4911 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4912 // a generic shuffle instruction because the target has no such instructions.
4913 // Generate shuffles which repeat i16 and i8 several times until they can be
4914 // represented by v4f32 and then be manipulated by target suported shuffles.
4915 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4916 MVT VT = V.getSimpleValueType();
4917 int NumElems = VT.getVectorNumElements();
4920 while (NumElems > 4) {
4921 if (EltNo < NumElems/2) {
4922 V = getUnpackl(DAG, dl, VT, V, V);
4924 V = getUnpackh(DAG, dl, VT, V, V);
4925 EltNo -= NumElems/2;
4932 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4933 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4934 MVT VT = V.getSimpleValueType();
4937 if (VT.is128BitVector()) {
4938 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4939 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4940 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4942 } else if (VT.is256BitVector()) {
4943 // To use VPERMILPS to splat scalars, the second half of indicies must
4944 // refer to the higher part, which is a duplication of the lower one,
4945 // because VPERMILPS can only handle in-lane permutations.
4946 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4947 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4949 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4950 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4953 llvm_unreachable("Vector size not supported");
4955 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4958 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4959 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4960 MVT SrcVT = SV->getSimpleValueType(0);
4961 SDValue V1 = SV->getOperand(0);
4964 int EltNo = SV->getSplatIndex();
4965 int NumElems = SrcVT.getVectorNumElements();
4966 bool Is256BitVec = SrcVT.is256BitVector();
4968 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4969 "Unknown how to promote splat for type");
4971 // Extract the 128-bit part containing the splat element and update
4972 // the splat element index when it refers to the higher register.
4974 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4975 if (EltNo >= NumElems/2)
4976 EltNo -= NumElems/2;
4979 // All i16 and i8 vector types can't be used directly by a generic shuffle
4980 // instruction because the target has no such instruction. Generate shuffles
4981 // which repeat i16 and i8 several times until they fit in i32, and then can
4982 // be manipulated by target suported shuffles.
4983 MVT EltVT = SrcVT.getVectorElementType();
4984 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4985 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4987 // Recreate the 256-bit vector and place the same 128-bit vector
4988 // into the low and high part. This is necessary because we want
4989 // to use VPERM* to shuffle the vectors
4991 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4994 return getLegalSplat(DAG, V1, EltNo);
4997 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4998 /// vector of zero or undef vector. This produces a shuffle where the low
4999 /// element of V2 is swizzled into the zero/undef vector, landing at element
5000 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5001 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5003 const X86Subtarget *Subtarget,
5004 SelectionDAG &DAG) {
5005 MVT VT = V2.getSimpleValueType();
5007 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5008 unsigned NumElems = VT.getVectorNumElements();
5009 SmallVector<int, 16> MaskVec;
5010 for (unsigned i = 0; i != NumElems; ++i)
5011 // If this is the insertion idx, put the low elt of V2 here.
5012 MaskVec.push_back(i == Idx ? NumElems : i);
5013 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5016 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5017 /// target specific opcode. Returns true if the Mask could be calculated.
5018 /// Sets IsUnary to true if only uses one source.
5019 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5020 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5021 unsigned NumElems = VT.getVectorNumElements();
5025 switch(N->getOpcode()) {
5027 ImmN = N->getOperand(N->getNumOperands()-1);
5028 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5030 case X86ISD::UNPCKH:
5031 DecodeUNPCKHMask(VT, Mask);
5033 case X86ISD::UNPCKL:
5034 DecodeUNPCKLMask(VT, Mask);
5036 case X86ISD::MOVHLPS:
5037 DecodeMOVHLPSMask(NumElems, Mask);
5039 case X86ISD::MOVLHPS:
5040 DecodeMOVLHPSMask(NumElems, Mask);
5042 case X86ISD::PALIGNR:
5043 ImmN = N->getOperand(N->getNumOperands()-1);
5044 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5046 case X86ISD::PSHUFD:
5047 case X86ISD::VPERMILP:
5048 ImmN = N->getOperand(N->getNumOperands()-1);
5049 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5052 case X86ISD::PSHUFHW:
5053 ImmN = N->getOperand(N->getNumOperands()-1);
5054 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5057 case X86ISD::PSHUFLW:
5058 ImmN = N->getOperand(N->getNumOperands()-1);
5059 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5062 case X86ISD::VPERMI:
5063 ImmN = N->getOperand(N->getNumOperands()-1);
5064 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5068 case X86ISD::MOVSD: {
5069 // The index 0 always comes from the first element of the second source,
5070 // this is why MOVSS and MOVSD are used in the first place. The other
5071 // elements come from the other positions of the first source vector
5072 Mask.push_back(NumElems);
5073 for (unsigned i = 1; i != NumElems; ++i) {
5078 case X86ISD::VPERM2X128:
5079 ImmN = N->getOperand(N->getNumOperands()-1);
5080 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5081 if (Mask.empty()) return false;
5083 case X86ISD::MOVDDUP:
5084 case X86ISD::MOVLHPD:
5085 case X86ISD::MOVLPD:
5086 case X86ISD::MOVLPS:
5087 case X86ISD::MOVSHDUP:
5088 case X86ISD::MOVSLDUP:
5089 // Not yet implemented
5091 default: llvm_unreachable("unknown target shuffle node");
5097 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5098 /// element of the result of the vector shuffle.
5099 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5102 return SDValue(); // Limit search depth.
5104 SDValue V = SDValue(N, 0);
5105 EVT VT = V.getValueType();
5106 unsigned Opcode = V.getOpcode();
5108 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5109 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5110 int Elt = SV->getMaskElt(Index);
5113 return DAG.getUNDEF(VT.getVectorElementType());
5115 unsigned NumElems = VT.getVectorNumElements();
5116 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5117 : SV->getOperand(1);
5118 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5121 // Recurse into target specific vector shuffles to find scalars.
5122 if (isTargetShuffle(Opcode)) {
5123 MVT ShufVT = V.getSimpleValueType();
5124 unsigned NumElems = ShufVT.getVectorNumElements();
5125 SmallVector<int, 16> ShuffleMask;
5128 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5131 int Elt = ShuffleMask[Index];
5133 return DAG.getUNDEF(ShufVT.getVectorElementType());
5135 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5137 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5141 // Actual nodes that may contain scalar elements
5142 if (Opcode == ISD::BITCAST) {
5143 V = V.getOperand(0);
5144 EVT SrcVT = V.getValueType();
5145 unsigned NumElems = VT.getVectorNumElements();
5147 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5151 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5152 return (Index == 0) ? V.getOperand(0)
5153 : DAG.getUNDEF(VT.getVectorElementType());
5155 if (V.getOpcode() == ISD::BUILD_VECTOR)
5156 return V.getOperand(Index);
5161 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5162 /// shuffle operation which come from a consecutively from a zero. The
5163 /// search can start in two different directions, from left or right.
5164 /// We count undefs as zeros until PreferredNum is reached.
5165 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5166 unsigned NumElems, bool ZerosFromLeft,
5168 unsigned PreferredNum = -1U) {
5169 unsigned NumZeros = 0;
5170 for (unsigned i = 0; i != NumElems; ++i) {
5171 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5172 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5176 if (X86::isZeroNode(Elt))
5178 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5179 NumZeros = std::min(NumZeros + 1, PreferredNum);
5187 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5188 /// correspond consecutively to elements from one of the vector operands,
5189 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5191 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5192 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5193 unsigned NumElems, unsigned &OpNum) {
5194 bool SeenV1 = false;
5195 bool SeenV2 = false;
5197 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5198 int Idx = SVOp->getMaskElt(i);
5199 // Ignore undef indicies
5203 if (Idx < (int)NumElems)
5208 // Only accept consecutive elements from the same vector
5209 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5213 OpNum = SeenV1 ? 0 : 1;
5217 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5218 /// logical left shift of a vector.
5219 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5220 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5222 SVOp->getSimpleValueType(0).getVectorNumElements();
5223 unsigned NumZeros = getNumOfConsecutiveZeros(
5224 SVOp, NumElems, false /* check zeros from right */, DAG,
5225 SVOp->getMaskElt(0));
5231 // Considering the elements in the mask that are not consecutive zeros,
5232 // check if they consecutively come from only one of the source vectors.
5234 // V1 = {X, A, B, C} 0
5236 // vector_shuffle V1, V2 <1, 2, 3, X>
5238 if (!isShuffleMaskConsecutive(SVOp,
5239 0, // Mask Start Index
5240 NumElems-NumZeros, // Mask End Index(exclusive)
5241 NumZeros, // Where to start looking in the src vector
5242 NumElems, // Number of elements in vector
5243 OpSrc)) // Which source operand ?
5248 ShVal = SVOp->getOperand(OpSrc);
5252 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5253 /// logical left shift of a vector.
5254 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5255 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5257 SVOp->getSimpleValueType(0).getVectorNumElements();
5258 unsigned NumZeros = getNumOfConsecutiveZeros(
5259 SVOp, NumElems, true /* check zeros from left */, DAG,
5260 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5266 // Considering the elements in the mask that are not consecutive zeros,
5267 // check if they consecutively come from only one of the source vectors.
5269 // 0 { A, B, X, X } = V2
5271 // vector_shuffle V1, V2 <X, X, 4, 5>
5273 if (!isShuffleMaskConsecutive(SVOp,
5274 NumZeros, // Mask Start Index
5275 NumElems, // Mask End Index(exclusive)
5276 0, // Where to start looking in the src vector
5277 NumElems, // Number of elements in vector
5278 OpSrc)) // Which source operand ?
5283 ShVal = SVOp->getOperand(OpSrc);
5287 /// isVectorShift - Returns true if the shuffle can be implemented as a
5288 /// logical left or right shift of a vector.
5289 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5290 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5291 // Although the logic below support any bitwidth size, there are no
5292 // shift instructions which handle more than 128-bit vectors.
5293 if (!SVOp->getSimpleValueType(0).is128BitVector())
5296 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5297 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5303 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5305 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5306 unsigned NumNonZero, unsigned NumZero,
5308 const X86Subtarget* Subtarget,
5309 const TargetLowering &TLI) {
5316 for (unsigned i = 0; i < 16; ++i) {
5317 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5318 if (ThisIsNonZero && First) {
5320 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5322 V = DAG.getUNDEF(MVT::v8i16);
5327 SDValue ThisElt(0, 0), LastElt(0, 0);
5328 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5329 if (LastIsNonZero) {
5330 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5331 MVT::i16, Op.getOperand(i-1));
5333 if (ThisIsNonZero) {
5334 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5335 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5336 ThisElt, DAG.getConstant(8, MVT::i8));
5338 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5342 if (ThisElt.getNode())
5343 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5344 DAG.getIntPtrConstant(i/2));
5348 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5351 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5353 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5354 unsigned NumNonZero, unsigned NumZero,
5356 const X86Subtarget* Subtarget,
5357 const TargetLowering &TLI) {
5364 for (unsigned i = 0; i < 8; ++i) {
5365 bool isNonZero = (NonZeros & (1 << i)) != 0;
5369 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5371 V = DAG.getUNDEF(MVT::v8i16);
5374 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5375 MVT::v8i16, V, Op.getOperand(i),
5376 DAG.getIntPtrConstant(i));
5383 /// getVShift - Return a vector logical shift node.
5385 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5386 unsigned NumBits, SelectionDAG &DAG,
5387 const TargetLowering &TLI, SDLoc dl) {
5388 assert(VT.is128BitVector() && "Unknown type for VShift");
5389 EVT ShVT = MVT::v2i64;
5390 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5391 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5392 return DAG.getNode(ISD::BITCAST, dl, VT,
5393 DAG.getNode(Opc, dl, ShVT, SrcOp,
5394 DAG.getConstant(NumBits,
5395 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5399 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5401 // Check if the scalar load can be widened into a vector load. And if
5402 // the address is "base + cst" see if the cst can be "absorbed" into
5403 // the shuffle mask.
5404 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5405 SDValue Ptr = LD->getBasePtr();
5406 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5408 EVT PVT = LD->getValueType(0);
5409 if (PVT != MVT::i32 && PVT != MVT::f32)
5414 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5415 FI = FINode->getIndex();
5417 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5418 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5419 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5420 Offset = Ptr.getConstantOperandVal(1);
5421 Ptr = Ptr.getOperand(0);
5426 // FIXME: 256-bit vector instructions don't require a strict alignment,
5427 // improve this code to support it better.
5428 unsigned RequiredAlign = VT.getSizeInBits()/8;
5429 SDValue Chain = LD->getChain();
5430 // Make sure the stack object alignment is at least 16 or 32.
5431 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5432 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5433 if (MFI->isFixedObjectIndex(FI)) {
5434 // Can't change the alignment. FIXME: It's possible to compute
5435 // the exact stack offset and reference FI + adjust offset instead.
5436 // If someone *really* cares about this. That's the way to implement it.
5439 MFI->setObjectAlignment(FI, RequiredAlign);
5443 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5444 // Ptr + (Offset & ~15).
5447 if ((Offset % RequiredAlign) & 3)
5449 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5451 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5452 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5454 int EltNo = (Offset - StartOffset) >> 2;
5455 unsigned NumElems = VT.getVectorNumElements();
5457 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5458 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5459 LD->getPointerInfo().getWithOffset(StartOffset),
5460 false, false, false, 0);
5462 SmallVector<int, 8> Mask;
5463 for (unsigned i = 0; i != NumElems; ++i)
5464 Mask.push_back(EltNo);
5466 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5472 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5473 /// vector of type 'VT', see if the elements can be replaced by a single large
5474 /// load which has the same value as a build_vector whose operands are 'elts'.
5476 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5478 /// FIXME: we'd also like to handle the case where the last elements are zero
5479 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5480 /// There's even a handy isZeroNode for that purpose.
5481 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5482 SDLoc &DL, SelectionDAG &DAG,
5483 bool isAfterLegalize) {
5484 EVT EltVT = VT.getVectorElementType();
5485 unsigned NumElems = Elts.size();
5487 LoadSDNode *LDBase = NULL;
5488 unsigned LastLoadedElt = -1U;
5490 // For each element in the initializer, see if we've found a load or an undef.
5491 // If we don't find an initial load element, or later load elements are
5492 // non-consecutive, bail out.
5493 for (unsigned i = 0; i < NumElems; ++i) {
5494 SDValue Elt = Elts[i];
5496 if (!Elt.getNode() ||
5497 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5500 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5502 LDBase = cast<LoadSDNode>(Elt.getNode());
5506 if (Elt.getOpcode() == ISD::UNDEF)
5509 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5510 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5515 // If we have found an entire vector of loads and undefs, then return a large
5516 // load of the entire vector width starting at the base pointer. If we found
5517 // consecutive loads for the low half, generate a vzext_load node.
5518 if (LastLoadedElt == NumElems - 1) {
5520 if (isAfterLegalize &&
5521 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5524 SDValue NewLd = SDValue();
5526 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5527 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5528 LDBase->getPointerInfo(),
5529 LDBase->isVolatile(), LDBase->isNonTemporal(),
5530 LDBase->isInvariant(), 0);
5531 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5532 LDBase->getPointerInfo(),
5533 LDBase->isVolatile(), LDBase->isNonTemporal(),
5534 LDBase->isInvariant(), LDBase->getAlignment());
5536 if (LDBase->hasAnyUseOfValue(1)) {
5537 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5539 SDValue(NewLd.getNode(), 1));
5540 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5541 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5542 SDValue(NewLd.getNode(), 1));
5547 if (NumElems == 4 && LastLoadedElt == 1 &&
5548 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5549 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5550 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5552 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5553 array_lengthof(Ops), MVT::i64,
5554 LDBase->getPointerInfo(),
5555 LDBase->getAlignment(),
5556 false/*isVolatile*/, true/*ReadMem*/,
5559 // Make sure the newly-created LOAD is in the same position as LDBase in
5560 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5561 // update uses of LDBase's output chain to use the TokenFactor.
5562 if (LDBase->hasAnyUseOfValue(1)) {
5563 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5564 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5565 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5566 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5567 SDValue(ResNode.getNode(), 1));
5570 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5575 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5576 /// to generate a splat value for the following cases:
5577 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5578 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5579 /// a scalar load, or a constant.
5580 /// The VBROADCAST node is returned when a pattern is found,
5581 /// or SDValue() otherwise.
5582 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5583 SelectionDAG &DAG) {
5584 if (!Subtarget->hasFp256())
5587 MVT VT = Op.getSimpleValueType();
5590 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5591 "Unsupported vector type for broadcast.");
5596 switch (Op.getOpcode()) {
5598 // Unknown pattern found.
5601 case ISD::BUILD_VECTOR: {
5602 // The BUILD_VECTOR node must be a splat.
5603 if (!isSplatVector(Op.getNode()))
5606 Ld = Op.getOperand(0);
5607 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5608 Ld.getOpcode() == ISD::ConstantFP);
5610 // The suspected load node has several users. Make sure that all
5611 // of its users are from the BUILD_VECTOR node.
5612 // Constants may have multiple users.
5613 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5618 case ISD::VECTOR_SHUFFLE: {
5619 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5621 // Shuffles must have a splat mask where the first element is
5623 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5626 SDValue Sc = Op.getOperand(0);
5627 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5628 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5630 if (!Subtarget->hasInt256())
5633 // Use the register form of the broadcast instruction available on AVX2.
5634 if (VT.getSizeInBits() >= 256)
5635 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5636 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5639 Ld = Sc.getOperand(0);
5640 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5641 Ld.getOpcode() == ISD::ConstantFP);
5643 // The scalar_to_vector node and the suspected
5644 // load node must have exactly one user.
5645 // Constants may have multiple users.
5647 // AVX-512 has register version of the broadcast
5648 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5649 Ld.getValueType().getSizeInBits() >= 32;
5650 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5657 bool IsGE256 = (VT.getSizeInBits() >= 256);
5659 // Handle the broadcasting a single constant scalar from the constant pool
5660 // into a vector. On Sandybridge it is still better to load a constant vector
5661 // from the constant pool and not to broadcast it from a scalar.
5662 if (ConstSplatVal && Subtarget->hasInt256()) {
5663 EVT CVT = Ld.getValueType();
5664 assert(!CVT.isVector() && "Must not broadcast a vector type");
5665 unsigned ScalarSize = CVT.getSizeInBits();
5667 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5668 const Constant *C = 0;
5669 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5670 C = CI->getConstantIntValue();
5671 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5672 C = CF->getConstantFPValue();
5674 assert(C && "Invalid constant type");
5676 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5677 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5678 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5679 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5680 MachinePointerInfo::getConstantPool(),
5681 false, false, false, Alignment);
5683 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5687 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5688 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5690 // Handle AVX2 in-register broadcasts.
5691 if (!IsLoad && Subtarget->hasInt256() &&
5692 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5693 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5695 // The scalar source must be a normal load.
5699 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5700 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5702 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5703 // double since there is no vbroadcastsd xmm
5704 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5705 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5706 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5709 // Unsupported broadcast.
5713 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5714 /// underlying vector and index.
5716 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5718 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5720 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5721 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5724 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5726 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5728 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5729 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5732 // In this case the vector is the extract_subvector expression and the index
5733 // is 2, as specified by the shuffle.
5734 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5735 SDValue ShuffleVec = SVOp->getOperand(0);
5736 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5737 assert(ShuffleVecVT.getVectorElementType() ==
5738 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5740 int ShuffleIdx = SVOp->getMaskElt(Idx);
5741 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5742 ExtractedFromVec = ShuffleVec;
5748 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5749 MVT VT = Op.getSimpleValueType();
5751 // Skip if insert_vec_elt is not supported.
5752 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5753 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5757 unsigned NumElems = Op.getNumOperands();
5761 SmallVector<unsigned, 4> InsertIndices;
5762 SmallVector<int, 8> Mask(NumElems, -1);
5764 for (unsigned i = 0; i != NumElems; ++i) {
5765 unsigned Opc = Op.getOperand(i).getOpcode();
5767 if (Opc == ISD::UNDEF)
5770 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5771 // Quit if more than 1 elements need inserting.
5772 if (InsertIndices.size() > 1)
5775 InsertIndices.push_back(i);
5779 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5780 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5781 // Quit if non-constant index.
5782 if (!isa<ConstantSDNode>(ExtIdx))
5784 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5786 // Quit if extracted from vector of different type.
5787 if (ExtractedFromVec.getValueType() != VT)
5790 if (VecIn1.getNode() == 0)
5791 VecIn1 = ExtractedFromVec;
5792 else if (VecIn1 != ExtractedFromVec) {
5793 if (VecIn2.getNode() == 0)
5794 VecIn2 = ExtractedFromVec;
5795 else if (VecIn2 != ExtractedFromVec)
5796 // Quit if more than 2 vectors to shuffle
5800 if (ExtractedFromVec == VecIn1)
5802 else if (ExtractedFromVec == VecIn2)
5803 Mask[i] = Idx + NumElems;
5806 if (VecIn1.getNode() == 0)
5809 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5810 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5811 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5812 unsigned Idx = InsertIndices[i];
5813 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5814 DAG.getIntPtrConstant(Idx));
5820 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5822 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5824 MVT VT = Op.getSimpleValueType();
5825 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5826 "Unexpected type in LowerBUILD_VECTORvXi1!");
5829 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5830 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5831 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5832 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5833 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5834 Ops, VT.getVectorNumElements());
5837 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5838 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5839 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5840 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5841 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5842 Ops, VT.getVectorNumElements());
5845 bool AllContants = true;
5846 uint64_t Immediate = 0;
5847 int NonConstIdx = -1;
5848 bool IsSplat = true;
5849 unsigned NumNonConsts = 0;
5850 unsigned NumConsts = 0;
5851 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5852 SDValue In = Op.getOperand(idx);
5853 if (In.getOpcode() == ISD::UNDEF)
5855 if (!isa<ConstantSDNode>(In)) {
5856 AllContants = false;
5862 if (cast<ConstantSDNode>(In)->getZExtValue())
5863 Immediate |= (1ULL << idx);
5865 if (In != Op.getOperand(0))
5870 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5871 DAG.getConstant(Immediate, MVT::i16));
5872 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5873 DAG.getIntPtrConstant(0));
5876 if (NumNonConsts == 1 && NonConstIdx != 0) {
5879 SDValue VecAsImm = DAG.getConstant(Immediate,
5880 MVT::getIntegerVT(VT.getSizeInBits()));
5881 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5884 DstVec = DAG.getUNDEF(VT);
5885 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5886 Op.getOperand(NonConstIdx),
5887 DAG.getIntPtrConstant(NonConstIdx));
5889 if (!IsSplat && (NonConstIdx != 0))
5890 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5891 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5894 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5895 DAG.getConstant(-1, SelectVT),
5896 DAG.getConstant(0, SelectVT));
5898 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5899 DAG.getConstant((Immediate | 1), SelectVT),
5900 DAG.getConstant(Immediate, SelectVT));
5901 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5905 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5908 MVT VT = Op.getSimpleValueType();
5909 MVT ExtVT = VT.getVectorElementType();
5910 unsigned NumElems = Op.getNumOperands();
5912 // Generate vectors for predicate vectors.
5913 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5914 return LowerBUILD_VECTORvXi1(Op, DAG);
5916 // Vectors containing all zeros can be matched by pxor and xorps later
5917 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5918 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5919 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5920 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5923 return getZeroVector(VT, Subtarget, DAG, dl);
5926 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5927 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5928 // vpcmpeqd on 256-bit vectors.
5929 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5930 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5933 if (!VT.is512BitVector())
5934 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5937 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5938 if (Broadcast.getNode())
5941 unsigned EVTBits = ExtVT.getSizeInBits();
5943 unsigned NumZero = 0;
5944 unsigned NumNonZero = 0;
5945 unsigned NonZeros = 0;
5946 bool IsAllConstants = true;
5947 SmallSet<SDValue, 8> Values;
5948 for (unsigned i = 0; i < NumElems; ++i) {
5949 SDValue Elt = Op.getOperand(i);
5950 if (Elt.getOpcode() == ISD::UNDEF)
5953 if (Elt.getOpcode() != ISD::Constant &&
5954 Elt.getOpcode() != ISD::ConstantFP)
5955 IsAllConstants = false;
5956 if (X86::isZeroNode(Elt))
5959 NonZeros |= (1 << i);
5964 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5965 if (NumNonZero == 0)
5966 return DAG.getUNDEF(VT);
5968 // Special case for single non-zero, non-undef, element.
5969 if (NumNonZero == 1) {
5970 unsigned Idx = countTrailingZeros(NonZeros);
5971 SDValue Item = Op.getOperand(Idx);
5973 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5974 // the value are obviously zero, truncate the value to i32 and do the
5975 // insertion that way. Only do this if the value is non-constant or if the
5976 // value is a constant being inserted into element 0. It is cheaper to do
5977 // a constant pool load than it is to do a movd + shuffle.
5978 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5979 (!IsAllConstants || Idx == 0)) {
5980 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5982 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5983 EVT VecVT = MVT::v4i32;
5984 unsigned VecElts = 4;
5986 // Truncate the value (which may itself be a constant) to i32, and
5987 // convert it to a vector with movd (S2V+shuffle to zero extend).
5988 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5989 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5990 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5992 // Now we have our 32-bit value zero extended in the low element of
5993 // a vector. If Idx != 0, swizzle it into place.
5995 SmallVector<int, 4> Mask;
5996 Mask.push_back(Idx);
5997 for (unsigned i = 1; i != VecElts; ++i)
5999 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6002 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6006 // If we have a constant or non-constant insertion into the low element of
6007 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6008 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6009 // depending on what the source datatype is.
6012 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6014 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6015 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6016 if (VT.is256BitVector() || VT.is512BitVector()) {
6017 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6018 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6019 Item, DAG.getIntPtrConstant(0));
6021 assert(VT.is128BitVector() && "Expected an SSE value type!");
6022 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6023 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6024 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6027 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6028 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6029 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6030 if (VT.is256BitVector()) {
6031 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6032 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6034 assert(VT.is128BitVector() && "Expected an SSE value type!");
6035 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6037 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6041 // Is it a vector logical left shift?
6042 if (NumElems == 2 && Idx == 1 &&
6043 X86::isZeroNode(Op.getOperand(0)) &&
6044 !X86::isZeroNode(Op.getOperand(1))) {
6045 unsigned NumBits = VT.getSizeInBits();
6046 return getVShift(true, VT,
6047 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6048 VT, Op.getOperand(1)),
6049 NumBits/2, DAG, *this, dl);
6052 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6055 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6056 // is a non-constant being inserted into an element other than the low one,
6057 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6058 // movd/movss) to move this into the low element, then shuffle it into
6060 if (EVTBits == 32) {
6061 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6063 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6064 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6065 SmallVector<int, 8> MaskVec;
6066 for (unsigned i = 0; i != NumElems; ++i)
6067 MaskVec.push_back(i == Idx ? 0 : 1);
6068 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6072 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6073 if (Values.size() == 1) {
6074 if (EVTBits == 32) {
6075 // Instead of a shuffle like this:
6076 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6077 // Check if it's possible to issue this instead.
6078 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6079 unsigned Idx = countTrailingZeros(NonZeros);
6080 SDValue Item = Op.getOperand(Idx);
6081 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6082 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6087 // A vector full of immediates; various special cases are already
6088 // handled, so this is best done with a single constant-pool load.
6092 // For AVX-length vectors, build the individual 128-bit pieces and use
6093 // shuffles to put them in place.
6094 if (VT.is256BitVector() || VT.is512BitVector()) {
6095 SmallVector<SDValue, 64> V;
6096 for (unsigned i = 0; i != NumElems; ++i)
6097 V.push_back(Op.getOperand(i));
6099 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6101 // Build both the lower and upper subvector.
6102 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6103 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6106 // Recreate the wider vector with the lower and upper part.
6107 if (VT.is256BitVector())
6108 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6109 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6112 // Let legalizer expand 2-wide build_vectors.
6113 if (EVTBits == 64) {
6114 if (NumNonZero == 1) {
6115 // One half is zero or undef.
6116 unsigned Idx = countTrailingZeros(NonZeros);
6117 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6118 Op.getOperand(Idx));
6119 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6124 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6125 if (EVTBits == 8 && NumElems == 16) {
6126 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6128 if (V.getNode()) return V;
6131 if (EVTBits == 16 && NumElems == 8) {
6132 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6134 if (V.getNode()) return V;
6137 // If element VT is == 32 bits, turn it into a number of shuffles.
6138 SmallVector<SDValue, 8> V(NumElems);
6139 if (NumElems == 4 && NumZero > 0) {
6140 for (unsigned i = 0; i < 4; ++i) {
6141 bool isZero = !(NonZeros & (1 << i));
6143 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6145 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6148 for (unsigned i = 0; i < 2; ++i) {
6149 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6152 V[i] = V[i*2]; // Must be a zero vector.
6155 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6158 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6161 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6166 bool Reverse1 = (NonZeros & 0x3) == 2;
6167 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6171 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6172 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6174 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6177 if (Values.size() > 1 && VT.is128BitVector()) {
6178 // Check for a build vector of consecutive loads.
6179 for (unsigned i = 0; i < NumElems; ++i)
6180 V[i] = Op.getOperand(i);
6182 // Check for elements which are consecutive loads.
6183 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6187 // Check for a build vector from mostly shuffle plus few inserting.
6188 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6192 // For SSE 4.1, use insertps to put the high elements into the low element.
6193 if (getSubtarget()->hasSSE41()) {
6195 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6196 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6198 Result = DAG.getUNDEF(VT);
6200 for (unsigned i = 1; i < NumElems; ++i) {
6201 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6202 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6203 Op.getOperand(i), DAG.getIntPtrConstant(i));
6208 // Otherwise, expand into a number of unpckl*, start by extending each of
6209 // our (non-undef) elements to the full vector width with the element in the
6210 // bottom slot of the vector (which generates no code for SSE).
6211 for (unsigned i = 0; i < NumElems; ++i) {
6212 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6213 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6215 V[i] = DAG.getUNDEF(VT);
6218 // Next, we iteratively mix elements, e.g. for v4f32:
6219 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6220 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6221 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6222 unsigned EltStride = NumElems >> 1;
6223 while (EltStride != 0) {
6224 for (unsigned i = 0; i < EltStride; ++i) {
6225 // If V[i+EltStride] is undef and this is the first round of mixing,
6226 // then it is safe to just drop this shuffle: V[i] is already in the
6227 // right place, the one element (since it's the first round) being
6228 // inserted as undef can be dropped. This isn't safe for successive
6229 // rounds because they will permute elements within both vectors.
6230 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6231 EltStride == NumElems/2)
6234 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6243 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6244 // to create 256-bit vectors from two other 128-bit ones.
6245 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6247 MVT ResVT = Op.getSimpleValueType();
6249 assert((ResVT.is256BitVector() ||
6250 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6252 SDValue V1 = Op.getOperand(0);
6253 SDValue V2 = Op.getOperand(1);
6254 unsigned NumElems = ResVT.getVectorNumElements();
6255 if(ResVT.is256BitVector())
6256 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6258 if (Op.getNumOperands() == 4) {
6259 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6260 ResVT.getVectorNumElements()/2);
6261 SDValue V3 = Op.getOperand(2);
6262 SDValue V4 = Op.getOperand(3);
6263 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6264 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6266 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6269 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6270 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6271 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6272 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6273 Op.getNumOperands() == 4)));
6275 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6276 // from two other 128-bit ones.
6278 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6279 return LowerAVXCONCAT_VECTORS(Op, DAG);
6282 // Try to lower a shuffle node into a simple blend instruction.
6284 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6285 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6286 SDValue V1 = SVOp->getOperand(0);
6287 SDValue V2 = SVOp->getOperand(1);
6289 MVT VT = SVOp->getSimpleValueType(0);
6290 MVT EltVT = VT.getVectorElementType();
6291 unsigned NumElems = VT.getVectorNumElements();
6293 // There is no blend with immediate in AVX-512.
6294 if (VT.is512BitVector())
6297 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6299 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6302 // Check the mask for BLEND and build the value.
6303 unsigned MaskValue = 0;
6304 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6305 unsigned NumLanes = (NumElems-1)/8 + 1;
6306 unsigned NumElemsInLane = NumElems / NumLanes;
6308 // Blend for v16i16 should be symetric for the both lanes.
6309 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6311 int SndLaneEltIdx = (NumLanes == 2) ?
6312 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6313 int EltIdx = SVOp->getMaskElt(i);
6315 if ((EltIdx < 0 || EltIdx == (int)i) &&
6316 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6319 if (((unsigned)EltIdx == (i + NumElems)) &&
6320 (SndLaneEltIdx < 0 ||
6321 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6322 MaskValue |= (1<<i);
6327 // Convert i32 vectors to floating point if it is not AVX2.
6328 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6330 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6331 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6333 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6334 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6337 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6338 DAG.getConstant(MaskValue, MVT::i32));
6339 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6342 /// In vector type \p VT, return true if the element at index \p InputIdx
6343 /// falls on a different 128-bit lane than \p OutputIdx.
6344 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6345 unsigned OutputIdx) {
6346 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6347 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6350 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6351 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6352 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6353 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6355 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6356 SelectionDAG &DAG) {
6357 MVT VT = V1.getSimpleValueType();
6358 assert(VT.is128BitVector() || VT.is256BitVector());
6360 MVT EltVT = VT.getVectorElementType();
6361 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6362 unsigned NumElts = VT.getVectorNumElements();
6364 SmallVector<SDValue, 32> PshufbMask;
6365 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6366 int InputIdx = MaskVals[OutputIdx];
6367 unsigned InputByteIdx;
6369 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6370 InputByteIdx = 0x80;
6372 // Cross lane is not allowed.
6373 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6375 InputByteIdx = InputIdx * EltSizeInBytes;
6376 // Index is an byte offset within the 128-bit lane.
6377 InputByteIdx &= 0xf;
6380 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6381 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6382 if (InputByteIdx != 0x80)
6387 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6389 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6390 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6391 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6392 PshufbMask.data(), PshufbMask.size()));
6395 // v8i16 shuffles - Prefer shuffles in the following order:
6396 // 1. [all] pshuflw, pshufhw, optional move
6397 // 2. [ssse3] 1 x pshufb
6398 // 3. [ssse3] 2 x pshufb + 1 x por
6399 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6401 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6402 SelectionDAG &DAG) {
6403 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6404 SDValue V1 = SVOp->getOperand(0);
6405 SDValue V2 = SVOp->getOperand(1);
6407 SmallVector<int, 8> MaskVals;
6409 // Determine if more than 1 of the words in each of the low and high quadwords
6410 // of the result come from the same quadword of one of the two inputs. Undef
6411 // mask values count as coming from any quadword, for better codegen.
6413 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6414 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6415 unsigned LoQuad[] = { 0, 0, 0, 0 };
6416 unsigned HiQuad[] = { 0, 0, 0, 0 };
6417 // Indices of quads used.
6418 std::bitset<4> InputQuads;
6419 for (unsigned i = 0; i < 8; ++i) {
6420 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6421 int EltIdx = SVOp->getMaskElt(i);
6422 MaskVals.push_back(EltIdx);
6431 InputQuads.set(EltIdx / 4);
6434 int BestLoQuad = -1;
6435 unsigned MaxQuad = 1;
6436 for (unsigned i = 0; i < 4; ++i) {
6437 if (LoQuad[i] > MaxQuad) {
6439 MaxQuad = LoQuad[i];
6443 int BestHiQuad = -1;
6445 for (unsigned i = 0; i < 4; ++i) {
6446 if (HiQuad[i] > MaxQuad) {
6448 MaxQuad = HiQuad[i];
6452 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6453 // of the two input vectors, shuffle them into one input vector so only a
6454 // single pshufb instruction is necessary. If there are more than 2 input
6455 // quads, disable the next transformation since it does not help SSSE3.
6456 bool V1Used = InputQuads[0] || InputQuads[1];
6457 bool V2Used = InputQuads[2] || InputQuads[3];
6458 if (Subtarget->hasSSSE3()) {
6459 if (InputQuads.count() == 2 && V1Used && V2Used) {
6460 BestLoQuad = InputQuads[0] ? 0 : 1;
6461 BestHiQuad = InputQuads[2] ? 2 : 3;
6463 if (InputQuads.count() > 2) {
6469 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6470 // the shuffle mask. If a quad is scored as -1, that means that it contains
6471 // words from all 4 input quadwords.
6473 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6475 BestLoQuad < 0 ? 0 : BestLoQuad,
6476 BestHiQuad < 0 ? 1 : BestHiQuad
6478 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6479 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6480 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6481 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6483 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6484 // source words for the shuffle, to aid later transformations.
6485 bool AllWordsInNewV = true;
6486 bool InOrder[2] = { true, true };
6487 for (unsigned i = 0; i != 8; ++i) {
6488 int idx = MaskVals[i];
6490 InOrder[i/4] = false;
6491 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6493 AllWordsInNewV = false;
6497 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6498 if (AllWordsInNewV) {
6499 for (int i = 0; i != 8; ++i) {
6500 int idx = MaskVals[i];
6503 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6504 if ((idx != i) && idx < 4)
6506 if ((idx != i) && idx > 3)
6515 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6516 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6517 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6518 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6519 unsigned TargetMask = 0;
6520 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6521 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6522 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6523 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6524 getShufflePSHUFLWImmediate(SVOp);
6525 V1 = NewV.getOperand(0);
6526 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6530 // Promote splats to a larger type which usually leads to more efficient code.
6531 // FIXME: Is this true if pshufb is available?
6532 if (SVOp->isSplat())
6533 return PromoteSplat(SVOp, DAG);
6535 // If we have SSSE3, and all words of the result are from 1 input vector,
6536 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6537 // is present, fall back to case 4.
6538 if (Subtarget->hasSSSE3()) {
6539 SmallVector<SDValue,16> pshufbMask;
6541 // If we have elements from both input vectors, set the high bit of the
6542 // shuffle mask element to zero out elements that come from V2 in the V1
6543 // mask, and elements that come from V1 in the V2 mask, so that the two
6544 // results can be OR'd together.
6545 bool TwoInputs = V1Used && V2Used;
6546 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6548 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6550 // Calculate the shuffle mask for the second input, shuffle it, and
6551 // OR it with the first shuffled input.
6552 CommuteVectorShuffleMask(MaskVals, 8);
6553 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6554 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6555 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6558 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6559 // and update MaskVals with new element order.
6560 std::bitset<8> InOrder;
6561 if (BestLoQuad >= 0) {
6562 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6563 for (int i = 0; i != 4; ++i) {
6564 int idx = MaskVals[i];
6567 } else if ((idx / 4) == BestLoQuad) {
6572 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6575 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6576 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6577 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6579 getShufflePSHUFLWImmediate(SVOp), DAG);
6583 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6584 // and update MaskVals with the new element order.
6585 if (BestHiQuad >= 0) {
6586 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6587 for (unsigned i = 4; i != 8; ++i) {
6588 int idx = MaskVals[i];
6591 } else if ((idx / 4) == BestHiQuad) {
6592 MaskV[i] = (idx & 3) + 4;
6596 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6599 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6600 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6601 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6603 getShufflePSHUFHWImmediate(SVOp), DAG);
6607 // In case BestHi & BestLo were both -1, which means each quadword has a word
6608 // from each of the four input quadwords, calculate the InOrder bitvector now
6609 // before falling through to the insert/extract cleanup.
6610 if (BestLoQuad == -1 && BestHiQuad == -1) {
6612 for (int i = 0; i != 8; ++i)
6613 if (MaskVals[i] < 0 || MaskVals[i] == i)
6617 // The other elements are put in the right place using pextrw and pinsrw.
6618 for (unsigned i = 0; i != 8; ++i) {
6621 int EltIdx = MaskVals[i];
6624 SDValue ExtOp = (EltIdx < 8) ?
6625 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6626 DAG.getIntPtrConstant(EltIdx)) :
6627 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6628 DAG.getIntPtrConstant(EltIdx - 8));
6629 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6630 DAG.getIntPtrConstant(i));
6635 /// \brief v16i16 shuffles
6637 /// FIXME: We only support generation of a single pshufb currently. We can
6638 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6639 /// well (e.g 2 x pshufb + 1 x por).
6641 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6642 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6643 SDValue V1 = SVOp->getOperand(0);
6644 SDValue V2 = SVOp->getOperand(1);
6647 if (V2.getOpcode() != ISD::UNDEF)
6650 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6651 return getPSHUFB(MaskVals, V1, dl, DAG);
6654 // v16i8 shuffles - Prefer shuffles in the following order:
6655 // 1. [ssse3] 1 x pshufb
6656 // 2. [ssse3] 2 x pshufb + 1 x por
6657 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6658 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6659 const X86Subtarget* Subtarget,
6660 SelectionDAG &DAG) {
6661 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6662 SDValue V1 = SVOp->getOperand(0);
6663 SDValue V2 = SVOp->getOperand(1);
6665 ArrayRef<int> MaskVals = SVOp->getMask();
6667 // Promote splats to a larger type which usually leads to more efficient code.
6668 // FIXME: Is this true if pshufb is available?
6669 if (SVOp->isSplat())
6670 return PromoteSplat(SVOp, DAG);
6672 // If we have SSSE3, case 1 is generated when all result bytes come from
6673 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6674 // present, fall back to case 3.
6676 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6677 if (Subtarget->hasSSSE3()) {
6678 SmallVector<SDValue,16> pshufbMask;
6680 // If all result elements are from one input vector, then only translate
6681 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6683 // Otherwise, we have elements from both input vectors, and must zero out
6684 // elements that come from V2 in the first mask, and V1 in the second mask
6685 // so that we can OR them together.
6686 for (unsigned i = 0; i != 16; ++i) {
6687 int EltIdx = MaskVals[i];
6688 if (EltIdx < 0 || EltIdx >= 16)
6690 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6692 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6693 DAG.getNode(ISD::BUILD_VECTOR, dl,
6694 MVT::v16i8, &pshufbMask[0], 16));
6696 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6697 // the 2nd operand if it's undefined or zero.
6698 if (V2.getOpcode() == ISD::UNDEF ||
6699 ISD::isBuildVectorAllZeros(V2.getNode()))
6702 // Calculate the shuffle mask for the second input, shuffle it, and
6703 // OR it with the first shuffled input.
6705 for (unsigned i = 0; i != 16; ++i) {
6706 int EltIdx = MaskVals[i];
6707 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6708 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6710 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6711 DAG.getNode(ISD::BUILD_VECTOR, dl,
6712 MVT::v16i8, &pshufbMask[0], 16));
6713 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6716 // No SSSE3 - Calculate in place words and then fix all out of place words
6717 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6718 // the 16 different words that comprise the two doublequadword input vectors.
6719 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6720 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6722 for (int i = 0; i != 8; ++i) {
6723 int Elt0 = MaskVals[i*2];
6724 int Elt1 = MaskVals[i*2+1];
6726 // This word of the result is all undef, skip it.
6727 if (Elt0 < 0 && Elt1 < 0)
6730 // This word of the result is already in the correct place, skip it.
6731 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6734 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6735 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6738 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6739 // using a single extract together, load it and store it.
6740 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6741 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6742 DAG.getIntPtrConstant(Elt1 / 2));
6743 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6744 DAG.getIntPtrConstant(i));
6748 // If Elt1 is defined, extract it from the appropriate source. If the
6749 // source byte is not also odd, shift the extracted word left 8 bits
6750 // otherwise clear the bottom 8 bits if we need to do an or.
6752 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6753 DAG.getIntPtrConstant(Elt1 / 2));
6754 if ((Elt1 & 1) == 0)
6755 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6757 TLI.getShiftAmountTy(InsElt.getValueType())));
6759 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6760 DAG.getConstant(0xFF00, MVT::i16));
6762 // If Elt0 is defined, extract it from the appropriate source. If the
6763 // source byte is not also even, shift the extracted word right 8 bits. If
6764 // Elt1 was also defined, OR the extracted values together before
6765 // inserting them in the result.
6767 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6768 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6769 if ((Elt0 & 1) != 0)
6770 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6772 TLI.getShiftAmountTy(InsElt0.getValueType())));
6774 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6775 DAG.getConstant(0x00FF, MVT::i16));
6776 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6779 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6780 DAG.getIntPtrConstant(i));
6782 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6785 // v32i8 shuffles - Translate to VPSHUFB if possible.
6787 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6788 const X86Subtarget *Subtarget,
6789 SelectionDAG &DAG) {
6790 MVT VT = SVOp->getSimpleValueType(0);
6791 SDValue V1 = SVOp->getOperand(0);
6792 SDValue V2 = SVOp->getOperand(1);
6794 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6796 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6797 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6798 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6800 // VPSHUFB may be generated if
6801 // (1) one of input vector is undefined or zeroinitializer.
6802 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6803 // And (2) the mask indexes don't cross the 128-bit lane.
6804 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6805 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6808 if (V1IsAllZero && !V2IsAllZero) {
6809 CommuteVectorShuffleMask(MaskVals, 32);
6812 return getPSHUFB(MaskVals, V1, dl, DAG);
6815 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6816 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6817 /// done when every pair / quad of shuffle mask elements point to elements in
6818 /// the right sequence. e.g.
6819 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6821 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6822 SelectionDAG &DAG) {
6823 MVT VT = SVOp->getSimpleValueType(0);
6825 unsigned NumElems = VT.getVectorNumElements();
6828 switch (VT.SimpleTy) {
6829 default: llvm_unreachable("Unexpected!");
6830 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6831 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6832 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6833 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6834 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6835 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6838 SmallVector<int, 8> MaskVec;
6839 for (unsigned i = 0; i != NumElems; i += Scale) {
6841 for (unsigned j = 0; j != Scale; ++j) {
6842 int EltIdx = SVOp->getMaskElt(i+j);
6846 StartIdx = (EltIdx / Scale);
6847 if (EltIdx != (int)(StartIdx*Scale + j))
6850 MaskVec.push_back(StartIdx);
6853 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6854 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6855 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6858 /// getVZextMovL - Return a zero-extending vector move low node.
6860 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6861 SDValue SrcOp, SelectionDAG &DAG,
6862 const X86Subtarget *Subtarget, SDLoc dl) {
6863 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6864 LoadSDNode *LD = NULL;
6865 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6866 LD = dyn_cast<LoadSDNode>(SrcOp);
6868 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6870 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6871 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6872 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6873 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6874 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6876 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6877 return DAG.getNode(ISD::BITCAST, dl, VT,
6878 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6879 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6887 return DAG.getNode(ISD::BITCAST, dl, VT,
6888 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6889 DAG.getNode(ISD::BITCAST, dl,
6893 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6894 /// which could not be matched by any known target speficic shuffle
6896 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6898 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6899 if (NewOp.getNode())
6902 MVT VT = SVOp->getSimpleValueType(0);
6904 unsigned NumElems = VT.getVectorNumElements();
6905 unsigned NumLaneElems = NumElems / 2;
6908 MVT EltVT = VT.getVectorElementType();
6909 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6912 SmallVector<int, 16> Mask;
6913 for (unsigned l = 0; l < 2; ++l) {
6914 // Build a shuffle mask for the output, discovering on the fly which
6915 // input vectors to use as shuffle operands (recorded in InputUsed).
6916 // If building a suitable shuffle vector proves too hard, then bail
6917 // out with UseBuildVector set.
6918 bool UseBuildVector = false;
6919 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6920 unsigned LaneStart = l * NumLaneElems;
6921 for (unsigned i = 0; i != NumLaneElems; ++i) {
6922 // The mask element. This indexes into the input.
6923 int Idx = SVOp->getMaskElt(i+LaneStart);
6925 // the mask element does not index into any input vector.
6930 // The input vector this mask element indexes into.
6931 int Input = Idx / NumLaneElems;
6933 // Turn the index into an offset from the start of the input vector.
6934 Idx -= Input * NumLaneElems;
6936 // Find or create a shuffle vector operand to hold this input.
6938 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6939 if (InputUsed[OpNo] == Input)
6940 // This input vector is already an operand.
6942 if (InputUsed[OpNo] < 0) {
6943 // Create a new operand for this input vector.
6944 InputUsed[OpNo] = Input;
6949 if (OpNo >= array_lengthof(InputUsed)) {
6950 // More than two input vectors used! Give up on trying to create a
6951 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6952 UseBuildVector = true;
6956 // Add the mask index for the new shuffle vector.
6957 Mask.push_back(Idx + OpNo * NumLaneElems);
6960 if (UseBuildVector) {
6961 SmallVector<SDValue, 16> SVOps;
6962 for (unsigned i = 0; i != NumLaneElems; ++i) {
6963 // The mask element. This indexes into the input.
6964 int Idx = SVOp->getMaskElt(i+LaneStart);
6966 SVOps.push_back(DAG.getUNDEF(EltVT));
6970 // The input vector this mask element indexes into.
6971 int Input = Idx / NumElems;
6973 // Turn the index into an offset from the start of the input vector.
6974 Idx -= Input * NumElems;
6976 // Extract the vector element by hand.
6977 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6978 SVOp->getOperand(Input),
6979 DAG.getIntPtrConstant(Idx)));
6982 // Construct the output using a BUILD_VECTOR.
6983 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6985 } else if (InputUsed[0] < 0) {
6986 // No input vectors were used! The result is undefined.
6987 Output[l] = DAG.getUNDEF(NVT);
6989 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6990 (InputUsed[0] % 2) * NumLaneElems,
6992 // If only one input was used, use an undefined vector for the other.
6993 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6994 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6995 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6996 // At least one input vector was used. Create a new shuffle vector.
6997 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7003 // Concatenate the result back
7004 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7007 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7008 /// 4 elements, and match them with several different shuffle types.
7010 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7011 SDValue V1 = SVOp->getOperand(0);
7012 SDValue V2 = SVOp->getOperand(1);
7014 MVT VT = SVOp->getSimpleValueType(0);
7016 assert(VT.is128BitVector() && "Unsupported vector size");
7018 std::pair<int, int> Locs[4];
7019 int Mask1[] = { -1, -1, -1, -1 };
7020 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7024 for (unsigned i = 0; i != 4; ++i) {
7025 int Idx = PermMask[i];
7027 Locs[i] = std::make_pair(-1, -1);
7029 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7031 Locs[i] = std::make_pair(0, NumLo);
7035 Locs[i] = std::make_pair(1, NumHi);
7037 Mask1[2+NumHi] = Idx;
7043 if (NumLo <= 2 && NumHi <= 2) {
7044 // If no more than two elements come from either vector. This can be
7045 // implemented with two shuffles. First shuffle gather the elements.
7046 // The second shuffle, which takes the first shuffle as both of its
7047 // vector operands, put the elements into the right order.
7048 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7050 int Mask2[] = { -1, -1, -1, -1 };
7052 for (unsigned i = 0; i != 4; ++i)
7053 if (Locs[i].first != -1) {
7054 unsigned Idx = (i < 2) ? 0 : 4;
7055 Idx += Locs[i].first * 2 + Locs[i].second;
7059 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7062 if (NumLo == 3 || NumHi == 3) {
7063 // Otherwise, we must have three elements from one vector, call it X, and
7064 // one element from the other, call it Y. First, use a shufps to build an
7065 // intermediate vector with the one element from Y and the element from X
7066 // that will be in the same half in the final destination (the indexes don't
7067 // matter). Then, use a shufps to build the final vector, taking the half
7068 // containing the element from Y from the intermediate, and the other half
7071 // Normalize it so the 3 elements come from V1.
7072 CommuteVectorShuffleMask(PermMask, 4);
7076 // Find the element from V2.
7078 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7079 int Val = PermMask[HiIndex];
7086 Mask1[0] = PermMask[HiIndex];
7088 Mask1[2] = PermMask[HiIndex^1];
7090 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7093 Mask1[0] = PermMask[0];
7094 Mask1[1] = PermMask[1];
7095 Mask1[2] = HiIndex & 1 ? 6 : 4;
7096 Mask1[3] = HiIndex & 1 ? 4 : 6;
7097 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7100 Mask1[0] = HiIndex & 1 ? 2 : 0;
7101 Mask1[1] = HiIndex & 1 ? 0 : 2;
7102 Mask1[2] = PermMask[2];
7103 Mask1[3] = PermMask[3];
7108 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7111 // Break it into (shuffle shuffle_hi, shuffle_lo).
7112 int LoMask[] = { -1, -1, -1, -1 };
7113 int HiMask[] = { -1, -1, -1, -1 };
7115 int *MaskPtr = LoMask;
7116 unsigned MaskIdx = 0;
7119 for (unsigned i = 0; i != 4; ++i) {
7126 int Idx = PermMask[i];
7128 Locs[i] = std::make_pair(-1, -1);
7129 } else if (Idx < 4) {
7130 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7131 MaskPtr[LoIdx] = Idx;
7134 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7135 MaskPtr[HiIdx] = Idx;
7140 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7141 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7142 int MaskOps[] = { -1, -1, -1, -1 };
7143 for (unsigned i = 0; i != 4; ++i)
7144 if (Locs[i].first != -1)
7145 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7146 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7149 static bool MayFoldVectorLoad(SDValue V) {
7150 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7151 V = V.getOperand(0);
7153 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7154 V = V.getOperand(0);
7155 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7156 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7157 // BUILD_VECTOR (load), undef
7158 V = V.getOperand(0);
7160 return MayFoldLoad(V);
7164 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7165 MVT VT = Op.getSimpleValueType();
7167 // Canonizalize to v2f64.
7168 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7169 return DAG.getNode(ISD::BITCAST, dl, VT,
7170 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7175 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7177 SDValue V1 = Op.getOperand(0);
7178 SDValue V2 = Op.getOperand(1);
7179 MVT VT = Op.getSimpleValueType();
7181 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7183 if (HasSSE2 && VT == MVT::v2f64)
7184 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7186 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7187 return DAG.getNode(ISD::BITCAST, dl, VT,
7188 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7189 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7190 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7194 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7195 SDValue V1 = Op.getOperand(0);
7196 SDValue V2 = Op.getOperand(1);
7197 MVT VT = Op.getSimpleValueType();
7199 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7200 "unsupported shuffle type");
7202 if (V2.getOpcode() == ISD::UNDEF)
7206 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7210 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7211 SDValue V1 = Op.getOperand(0);
7212 SDValue V2 = Op.getOperand(1);
7213 MVT VT = Op.getSimpleValueType();
7214 unsigned NumElems = VT.getVectorNumElements();
7216 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7217 // operand of these instructions is only memory, so check if there's a
7218 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7220 bool CanFoldLoad = false;
7222 // Trivial case, when V2 comes from a load.
7223 if (MayFoldVectorLoad(V2))
7226 // When V1 is a load, it can be folded later into a store in isel, example:
7227 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7229 // (MOVLPSmr addr:$src1, VR128:$src2)
7230 // So, recognize this potential and also use MOVLPS or MOVLPD
7231 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7234 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7236 if (HasSSE2 && NumElems == 2)
7237 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7240 // If we don't care about the second element, proceed to use movss.
7241 if (SVOp->getMaskElt(1) != -1)
7242 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7245 // movl and movlp will both match v2i64, but v2i64 is never matched by
7246 // movl earlier because we make it strict to avoid messing with the movlp load
7247 // folding logic (see the code above getMOVLP call). Match it here then,
7248 // this is horrible, but will stay like this until we move all shuffle
7249 // matching to x86 specific nodes. Note that for the 1st condition all
7250 // types are matched with movsd.
7252 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7253 // as to remove this logic from here, as much as possible
7254 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7255 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7256 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7259 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7261 // Invert the operand order and use SHUFPS to match it.
7262 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7263 getShuffleSHUFImmediate(SVOp), DAG);
7266 // Reduce a vector shuffle to zext.
7267 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7268 SelectionDAG &DAG) {
7269 // PMOVZX is only available from SSE41.
7270 if (!Subtarget->hasSSE41())
7273 MVT VT = Op.getSimpleValueType();
7275 // Only AVX2 support 256-bit vector integer extending.
7276 if (!Subtarget->hasInt256() && VT.is256BitVector())
7279 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7281 SDValue V1 = Op.getOperand(0);
7282 SDValue V2 = Op.getOperand(1);
7283 unsigned NumElems = VT.getVectorNumElements();
7285 // Extending is an unary operation and the element type of the source vector
7286 // won't be equal to or larger than i64.
7287 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7288 VT.getVectorElementType() == MVT::i64)
7291 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7292 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7293 while ((1U << Shift) < NumElems) {
7294 if (SVOp->getMaskElt(1U << Shift) == 1)
7297 // The maximal ratio is 8, i.e. from i8 to i64.
7302 // Check the shuffle mask.
7303 unsigned Mask = (1U << Shift) - 1;
7304 for (unsigned i = 0; i != NumElems; ++i) {
7305 int EltIdx = SVOp->getMaskElt(i);
7306 if ((i & Mask) != 0 && EltIdx != -1)
7308 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7312 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7313 MVT NeVT = MVT::getIntegerVT(NBits);
7314 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7316 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7319 // Simplify the operand as it's prepared to be fed into shuffle.
7320 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7321 if (V1.getOpcode() == ISD::BITCAST &&
7322 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7323 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7324 V1.getOperand(0).getOperand(0)
7325 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7326 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7327 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7328 ConstantSDNode *CIdx =
7329 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7330 // If it's foldable, i.e. normal load with single use, we will let code
7331 // selection to fold it. Otherwise, we will short the conversion sequence.
7332 if (CIdx && CIdx->getZExtValue() == 0 &&
7333 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7334 MVT FullVT = V.getSimpleValueType();
7335 MVT V1VT = V1.getSimpleValueType();
7336 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7337 // The "ext_vec_elt" node is wider than the result node.
7338 // In this case we should extract subvector from V.
7339 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7340 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7341 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7342 FullVT.getVectorNumElements()/Ratio);
7343 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7344 DAG.getIntPtrConstant(0));
7346 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7350 return DAG.getNode(ISD::BITCAST, DL, VT,
7351 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7355 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7356 SelectionDAG &DAG) {
7357 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7358 MVT VT = Op.getSimpleValueType();
7360 SDValue V1 = Op.getOperand(0);
7361 SDValue V2 = Op.getOperand(1);
7363 if (isZeroShuffle(SVOp))
7364 return getZeroVector(VT, Subtarget, DAG, dl);
7366 // Handle splat operations
7367 if (SVOp->isSplat()) {
7368 // Use vbroadcast whenever the splat comes from a foldable load
7369 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7370 if (Broadcast.getNode())
7374 // Check integer expanding shuffles.
7375 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7376 if (NewOp.getNode())
7379 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7381 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7382 VT == MVT::v16i16 || VT == MVT::v32i8) {
7383 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7384 if (NewOp.getNode())
7385 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7386 } else if ((VT == MVT::v4i32 ||
7387 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7388 // FIXME: Figure out a cleaner way to do this.
7389 // Try to make use of movq to zero out the top part.
7390 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7391 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7392 if (NewOp.getNode()) {
7393 MVT NewVT = NewOp.getSimpleValueType();
7394 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7395 NewVT, true, false))
7396 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7397 DAG, Subtarget, dl);
7399 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7400 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7401 if (NewOp.getNode()) {
7402 MVT NewVT = NewOp.getSimpleValueType();
7403 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7404 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7405 DAG, Subtarget, dl);
7413 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7414 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7415 SDValue V1 = Op.getOperand(0);
7416 SDValue V2 = Op.getOperand(1);
7417 MVT VT = Op.getSimpleValueType();
7419 unsigned NumElems = VT.getVectorNumElements();
7420 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7421 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7422 bool V1IsSplat = false;
7423 bool V2IsSplat = false;
7424 bool HasSSE2 = Subtarget->hasSSE2();
7425 bool HasFp256 = Subtarget->hasFp256();
7426 bool HasInt256 = Subtarget->hasInt256();
7427 MachineFunction &MF = DAG.getMachineFunction();
7428 bool OptForSize = MF.getFunction()->getAttributes().
7429 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7431 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7433 if (V1IsUndef && V2IsUndef)
7434 return DAG.getUNDEF(VT);
7436 // When we create a shuffle node we put the UNDEF node to second operand,
7437 // but in some cases the first operand may be transformed to UNDEF.
7438 // In this case we should just commute the node.
7440 return CommuteVectorShuffle(SVOp, DAG);
7442 // Vector shuffle lowering takes 3 steps:
7444 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7445 // narrowing and commutation of operands should be handled.
7446 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7448 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7449 // so the shuffle can be broken into other shuffles and the legalizer can
7450 // try the lowering again.
7452 // The general idea is that no vector_shuffle operation should be left to
7453 // be matched during isel, all of them must be converted to a target specific
7456 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7457 // narrowing and commutation of operands should be handled. The actual code
7458 // doesn't include all of those, work in progress...
7459 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7460 if (NewOp.getNode())
7463 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7465 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7466 // unpckh_undef). Only use pshufd if speed is more important than size.
7467 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7468 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7469 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7470 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7472 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7473 V2IsUndef && MayFoldVectorLoad(V1))
7474 return getMOVDDup(Op, dl, V1, DAG);
7476 if (isMOVHLPS_v_undef_Mask(M, VT))
7477 return getMOVHighToLow(Op, dl, DAG);
7479 // Use to match splats
7480 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7481 (VT == MVT::v2f64 || VT == MVT::v2i64))
7482 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7484 if (isPSHUFDMask(M, VT)) {
7485 // The actual implementation will match the mask in the if above and then
7486 // during isel it can match several different instructions, not only pshufd
7487 // as its name says, sad but true, emulate the behavior for now...
7488 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7489 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7491 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7493 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7494 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7496 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7497 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7500 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7504 if (isPALIGNRMask(M, VT, Subtarget))
7505 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7506 getShufflePALIGNRImmediate(SVOp),
7509 // Check if this can be converted into a logical shift.
7510 bool isLeft = false;
7513 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7514 if (isShift && ShVal.hasOneUse()) {
7515 // If the shifted value has multiple uses, it may be cheaper to use
7516 // v_set0 + movlhps or movhlps, etc.
7517 MVT EltVT = VT.getVectorElementType();
7518 ShAmt *= EltVT.getSizeInBits();
7519 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7522 if (isMOVLMask(M, VT)) {
7523 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7524 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7525 if (!isMOVLPMask(M, VT)) {
7526 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7527 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7529 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7530 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7534 // FIXME: fold these into legal mask.
7535 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7536 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7538 if (isMOVHLPSMask(M, VT))
7539 return getMOVHighToLow(Op, dl, DAG);
7541 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7542 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7544 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7545 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7547 if (isMOVLPMask(M, VT))
7548 return getMOVLP(Op, dl, DAG, HasSSE2);
7550 if (ShouldXformToMOVHLPS(M, VT) ||
7551 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7552 return CommuteVectorShuffle(SVOp, DAG);
7555 // No better options. Use a vshldq / vsrldq.
7556 MVT EltVT = VT.getVectorElementType();
7557 ShAmt *= EltVT.getSizeInBits();
7558 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7561 bool Commuted = false;
7562 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7563 // 1,1,1,1 -> v8i16 though.
7564 V1IsSplat = isSplatVector(V1.getNode());
7565 V2IsSplat = isSplatVector(V2.getNode());
7567 // Canonicalize the splat or undef, if present, to be on the RHS.
7568 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7569 CommuteVectorShuffleMask(M, NumElems);
7571 std::swap(V1IsSplat, V2IsSplat);
7575 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7576 // Shuffling low element of v1 into undef, just return v1.
7579 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7580 // the instruction selector will not match, so get a canonical MOVL with
7581 // swapped operands to undo the commute.
7582 return getMOVL(DAG, dl, VT, V2, V1);
7585 if (isUNPCKLMask(M, VT, HasInt256))
7586 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7588 if (isUNPCKHMask(M, VT, HasInt256))
7589 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7592 // Normalize mask so all entries that point to V2 points to its first
7593 // element then try to match unpck{h|l} again. If match, return a
7594 // new vector_shuffle with the corrected mask.p
7595 SmallVector<int, 8> NewMask(M.begin(), M.end());
7596 NormalizeMask(NewMask, NumElems);
7597 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7598 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7599 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7600 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7604 // Commute is back and try unpck* again.
7605 // FIXME: this seems wrong.
7606 CommuteVectorShuffleMask(M, NumElems);
7608 std::swap(V1IsSplat, V2IsSplat);
7610 if (isUNPCKLMask(M, VT, HasInt256))
7611 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7613 if (isUNPCKHMask(M, VT, HasInt256))
7614 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7617 // Normalize the node to match x86 shuffle ops if needed
7618 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7619 return CommuteVectorShuffle(SVOp, DAG);
7621 // The checks below are all present in isShuffleMaskLegal, but they are
7622 // inlined here right now to enable us to directly emit target specific
7623 // nodes, and remove one by one until they don't return Op anymore.
7625 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7626 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7627 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7628 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7631 if (isPSHUFHWMask(M, VT, HasInt256))
7632 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7633 getShufflePSHUFHWImmediate(SVOp),
7636 if (isPSHUFLWMask(M, VT, HasInt256))
7637 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7638 getShufflePSHUFLWImmediate(SVOp),
7641 if (isSHUFPMask(M, VT))
7642 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7643 getShuffleSHUFImmediate(SVOp), DAG);
7645 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7646 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7647 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7648 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7650 //===--------------------------------------------------------------------===//
7651 // Generate target specific nodes for 128 or 256-bit shuffles only
7652 // supported in the AVX instruction set.
7655 // Handle VMOVDDUPY permutations
7656 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7657 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7659 // Handle VPERMILPS/D* permutations
7660 if (isVPERMILPMask(M, VT)) {
7661 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7662 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7663 getShuffleSHUFImmediate(SVOp), DAG);
7664 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7665 getShuffleSHUFImmediate(SVOp), DAG);
7668 // Handle VPERM2F128/VPERM2I128 permutations
7669 if (isVPERM2X128Mask(M, VT, HasFp256))
7670 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7671 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7673 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7674 if (BlendOp.getNode())
7678 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7679 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7681 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7682 VT.is512BitVector()) {
7683 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7684 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7685 SmallVector<SDValue, 16> permclMask;
7686 for (unsigned i = 0; i != NumElems; ++i) {
7687 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7690 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7691 &permclMask[0], NumElems);
7693 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7694 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7695 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7696 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7697 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7700 //===--------------------------------------------------------------------===//
7701 // Since no target specific shuffle was selected for this generic one,
7702 // lower it into other known shuffles. FIXME: this isn't true yet, but
7703 // this is the plan.
7706 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7707 if (VT == MVT::v8i16) {
7708 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7709 if (NewOp.getNode())
7713 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7714 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7715 if (NewOp.getNode())
7719 if (VT == MVT::v16i8) {
7720 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7721 if (NewOp.getNode())
7725 if (VT == MVT::v32i8) {
7726 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7727 if (NewOp.getNode())
7731 // Handle all 128-bit wide vectors with 4 elements, and match them with
7732 // several different shuffle types.
7733 if (NumElems == 4 && VT.is128BitVector())
7734 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7736 // Handle general 256-bit shuffles
7737 if (VT.is256BitVector())
7738 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7743 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7744 MVT VT = Op.getSimpleValueType();
7747 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7750 if (VT.getSizeInBits() == 8) {
7751 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7752 Op.getOperand(0), Op.getOperand(1));
7753 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7754 DAG.getValueType(VT));
7755 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7758 if (VT.getSizeInBits() == 16) {
7759 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7760 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7762 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7763 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7764 DAG.getNode(ISD::BITCAST, dl,
7768 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7769 Op.getOperand(0), Op.getOperand(1));
7770 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7771 DAG.getValueType(VT));
7772 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7775 if (VT == MVT::f32) {
7776 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7777 // the result back to FR32 register. It's only worth matching if the
7778 // result has a single use which is a store or a bitcast to i32. And in
7779 // the case of a store, it's not worth it if the index is a constant 0,
7780 // because a MOVSSmr can be used instead, which is smaller and faster.
7781 if (!Op.hasOneUse())
7783 SDNode *User = *Op.getNode()->use_begin();
7784 if ((User->getOpcode() != ISD::STORE ||
7785 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7786 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7787 (User->getOpcode() != ISD::BITCAST ||
7788 User->getValueType(0) != MVT::i32))
7790 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7791 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7794 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7797 if (VT == MVT::i32 || VT == MVT::i64) {
7798 // ExtractPS/pextrq works with constant index.
7799 if (isa<ConstantSDNode>(Op.getOperand(1)))
7805 /// Extract one bit from mask vector, like v16i1 or v8i1.
7806 /// AVX-512 feature.
7808 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7809 SDValue Vec = Op.getOperand(0);
7811 MVT VecVT = Vec.getSimpleValueType();
7812 SDValue Idx = Op.getOperand(1);
7813 MVT EltVT = Op.getSimpleValueType();
7815 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7817 // variable index can't be handled in mask registers,
7818 // extend vector to VR512
7819 if (!isa<ConstantSDNode>(Idx)) {
7820 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7821 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7822 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7823 ExtVT.getVectorElementType(), Ext, Idx);
7824 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7827 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7828 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7829 unsigned MaxSift = rc->getSize()*8 - 1;
7830 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7831 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7832 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7833 DAG.getConstant(MaxSift, MVT::i8));
7834 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7835 DAG.getIntPtrConstant(0));
7839 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7840 SelectionDAG &DAG) const {
7842 SDValue Vec = Op.getOperand(0);
7843 MVT VecVT = Vec.getSimpleValueType();
7844 SDValue Idx = Op.getOperand(1);
7846 if (Op.getSimpleValueType() == MVT::i1)
7847 return ExtractBitFromMaskVector(Op, DAG);
7849 if (!isa<ConstantSDNode>(Idx)) {
7850 if (VecVT.is512BitVector() ||
7851 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7852 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7855 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7856 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7857 MaskEltVT.getSizeInBits());
7859 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7860 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7861 getZeroVector(MaskVT, Subtarget, DAG, dl),
7862 Idx, DAG.getConstant(0, getPointerTy()));
7863 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7864 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7865 Perm, DAG.getConstant(0, getPointerTy()));
7870 // If this is a 256-bit vector result, first extract the 128-bit vector and
7871 // then extract the element from the 128-bit vector.
7872 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7874 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7875 // Get the 128-bit vector.
7876 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7877 MVT EltVT = VecVT.getVectorElementType();
7879 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7881 //if (IdxVal >= NumElems/2)
7882 // IdxVal -= NumElems/2;
7883 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7884 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7885 DAG.getConstant(IdxVal, MVT::i32));
7888 assert(VecVT.is128BitVector() && "Unexpected vector length");
7890 if (Subtarget->hasSSE41()) {
7891 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7896 MVT VT = Op.getSimpleValueType();
7897 // TODO: handle v16i8.
7898 if (VT.getSizeInBits() == 16) {
7899 SDValue Vec = Op.getOperand(0);
7900 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7902 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7903 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7904 DAG.getNode(ISD::BITCAST, dl,
7907 // Transform it so it match pextrw which produces a 32-bit result.
7908 MVT EltVT = MVT::i32;
7909 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7910 Op.getOperand(0), Op.getOperand(1));
7911 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7912 DAG.getValueType(VT));
7913 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7916 if (VT.getSizeInBits() == 32) {
7917 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7921 // SHUFPS the element to the lowest double word, then movss.
7922 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7923 MVT VVT = Op.getOperand(0).getSimpleValueType();
7924 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7925 DAG.getUNDEF(VVT), Mask);
7926 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7927 DAG.getIntPtrConstant(0));
7930 if (VT.getSizeInBits() == 64) {
7931 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7932 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7933 // to match extract_elt for f64.
7934 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7938 // UNPCKHPD the element to the lowest double word, then movsd.
7939 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7940 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7941 int Mask[2] = { 1, -1 };
7942 MVT VVT = Op.getOperand(0).getSimpleValueType();
7943 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7944 DAG.getUNDEF(VVT), Mask);
7945 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7946 DAG.getIntPtrConstant(0));
7952 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7953 MVT VT = Op.getSimpleValueType();
7954 MVT EltVT = VT.getVectorElementType();
7957 SDValue N0 = Op.getOperand(0);
7958 SDValue N1 = Op.getOperand(1);
7959 SDValue N2 = Op.getOperand(2);
7961 if (!VT.is128BitVector())
7964 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7965 isa<ConstantSDNode>(N2)) {
7967 if (VT == MVT::v8i16)
7968 Opc = X86ISD::PINSRW;
7969 else if (VT == MVT::v16i8)
7970 Opc = X86ISD::PINSRB;
7972 Opc = X86ISD::PINSRB;
7974 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7976 if (N1.getValueType() != MVT::i32)
7977 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7978 if (N2.getValueType() != MVT::i32)
7979 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7980 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7983 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7984 // Bits [7:6] of the constant are the source select. This will always be
7985 // zero here. The DAG Combiner may combine an extract_elt index into these
7986 // bits. For example (insert (extract, 3), 2) could be matched by putting
7987 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7988 // Bits [5:4] of the constant are the destination select. This is the
7989 // value of the incoming immediate.
7990 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7991 // combine either bitwise AND or insert of float 0.0 to set these bits.
7992 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7993 // Create this as a scalar to vector..
7994 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7995 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7998 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7999 // PINSR* works with constant index.
8005 /// Insert one bit to mask vector, like v16i1 or v8i1.
8006 /// AVX-512 feature.
8008 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8010 SDValue Vec = Op.getOperand(0);
8011 SDValue Elt = Op.getOperand(1);
8012 SDValue Idx = Op.getOperand(2);
8013 MVT VecVT = Vec.getSimpleValueType();
8015 if (!isa<ConstantSDNode>(Idx)) {
8016 // Non constant index. Extend source and destination,
8017 // insert element and then truncate the result.
8018 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8019 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8020 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8021 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8022 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8023 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8026 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8027 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8028 if (Vec.getOpcode() == ISD::UNDEF)
8029 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8030 DAG.getConstant(IdxVal, MVT::i8));
8031 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8032 unsigned MaxSift = rc->getSize()*8 - 1;
8033 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8034 DAG.getConstant(MaxSift, MVT::i8));
8035 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8036 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8037 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8040 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8041 MVT VT = Op.getSimpleValueType();
8042 MVT EltVT = VT.getVectorElementType();
8044 if (EltVT == MVT::i1)
8045 return InsertBitToMaskVector(Op, DAG);
8048 SDValue N0 = Op.getOperand(0);
8049 SDValue N1 = Op.getOperand(1);
8050 SDValue N2 = Op.getOperand(2);
8052 // If this is a 256-bit vector result, first extract the 128-bit vector,
8053 // insert the element into the extracted half and then place it back.
8054 if (VT.is256BitVector() || VT.is512BitVector()) {
8055 if (!isa<ConstantSDNode>(N2))
8058 // Get the desired 128-bit vector half.
8059 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8060 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8062 // Insert the element into the desired half.
8063 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8064 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8066 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8067 DAG.getConstant(IdxIn128, MVT::i32));
8069 // Insert the changed part back to the 256-bit vector
8070 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8073 if (Subtarget->hasSSE41())
8074 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8076 if (EltVT == MVT::i8)
8079 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8080 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8081 // as its second argument.
8082 if (N1.getValueType() != MVT::i32)
8083 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8084 if (N2.getValueType() != MVT::i32)
8085 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8086 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8091 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8093 MVT OpVT = Op.getSimpleValueType();
8095 // If this is a 256-bit vector result, first insert into a 128-bit
8096 // vector and then insert into the 256-bit vector.
8097 if (!OpVT.is128BitVector()) {
8098 // Insert into a 128-bit vector.
8099 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8100 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8101 OpVT.getVectorNumElements() / SizeFactor);
8103 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8105 // Insert the 128-bit vector.
8106 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8109 if (OpVT == MVT::v1i64 &&
8110 Op.getOperand(0).getValueType() == MVT::i64)
8111 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8113 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8114 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8115 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8116 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8119 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8120 // a simple subregister reference or explicit instructions to grab
8121 // upper bits of a vector.
8122 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8123 SelectionDAG &DAG) {
8125 SDValue In = Op.getOperand(0);
8126 SDValue Idx = Op.getOperand(1);
8127 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8128 MVT ResVT = Op.getSimpleValueType();
8129 MVT InVT = In.getSimpleValueType();
8131 if (Subtarget->hasFp256()) {
8132 if (ResVT.is128BitVector() &&
8133 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8134 isa<ConstantSDNode>(Idx)) {
8135 return Extract128BitVector(In, IdxVal, DAG, dl);
8137 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8138 isa<ConstantSDNode>(Idx)) {
8139 return Extract256BitVector(In, IdxVal, DAG, dl);
8145 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8146 // simple superregister reference or explicit instructions to insert
8147 // the upper bits of a vector.
8148 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8149 SelectionDAG &DAG) {
8150 if (Subtarget->hasFp256()) {
8151 SDLoc dl(Op.getNode());
8152 SDValue Vec = Op.getNode()->getOperand(0);
8153 SDValue SubVec = Op.getNode()->getOperand(1);
8154 SDValue Idx = Op.getNode()->getOperand(2);
8156 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8157 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8158 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8159 isa<ConstantSDNode>(Idx)) {
8160 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8161 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8164 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8165 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8166 isa<ConstantSDNode>(Idx)) {
8167 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8168 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8174 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8175 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8176 // one of the above mentioned nodes. It has to be wrapped because otherwise
8177 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8178 // be used to form addressing mode. These wrapped nodes will be selected
8181 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8182 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8184 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8186 unsigned char OpFlag = 0;
8187 unsigned WrapperKind = X86ISD::Wrapper;
8188 CodeModel::Model M = getTargetMachine().getCodeModel();
8190 if (Subtarget->isPICStyleRIPRel() &&
8191 (M == CodeModel::Small || M == CodeModel::Kernel))
8192 WrapperKind = X86ISD::WrapperRIP;
8193 else if (Subtarget->isPICStyleGOT())
8194 OpFlag = X86II::MO_GOTOFF;
8195 else if (Subtarget->isPICStyleStubPIC())
8196 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8198 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8200 CP->getOffset(), OpFlag);
8202 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8203 // With PIC, the address is actually $g + Offset.
8205 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8206 DAG.getNode(X86ISD::GlobalBaseReg,
8207 SDLoc(), getPointerTy()),
8214 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8215 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8217 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8219 unsigned char OpFlag = 0;
8220 unsigned WrapperKind = X86ISD::Wrapper;
8221 CodeModel::Model M = getTargetMachine().getCodeModel();
8223 if (Subtarget->isPICStyleRIPRel() &&
8224 (M == CodeModel::Small || M == CodeModel::Kernel))
8225 WrapperKind = X86ISD::WrapperRIP;
8226 else if (Subtarget->isPICStyleGOT())
8227 OpFlag = X86II::MO_GOTOFF;
8228 else if (Subtarget->isPICStyleStubPIC())
8229 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8231 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8234 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8236 // With PIC, the address is actually $g + Offset.
8238 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8239 DAG.getNode(X86ISD::GlobalBaseReg,
8240 SDLoc(), getPointerTy()),
8247 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8248 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8250 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8252 unsigned char OpFlag = 0;
8253 unsigned WrapperKind = X86ISD::Wrapper;
8254 CodeModel::Model M = getTargetMachine().getCodeModel();
8256 if (Subtarget->isPICStyleRIPRel() &&
8257 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8258 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8259 OpFlag = X86II::MO_GOTPCREL;
8260 WrapperKind = X86ISD::WrapperRIP;
8261 } else if (Subtarget->isPICStyleGOT()) {
8262 OpFlag = X86II::MO_GOT;
8263 } else if (Subtarget->isPICStyleStubPIC()) {
8264 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8265 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8266 OpFlag = X86II::MO_DARWIN_NONLAZY;
8269 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8272 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8274 // With PIC, the address is actually $g + Offset.
8275 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8276 !Subtarget->is64Bit()) {
8277 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8278 DAG.getNode(X86ISD::GlobalBaseReg,
8279 SDLoc(), getPointerTy()),
8283 // For symbols that require a load from a stub to get the address, emit the
8285 if (isGlobalStubReference(OpFlag))
8286 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8287 MachinePointerInfo::getGOT(), false, false, false, 0);
8293 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8294 // Create the TargetBlockAddressAddress node.
8295 unsigned char OpFlags =
8296 Subtarget->ClassifyBlockAddressReference();
8297 CodeModel::Model M = getTargetMachine().getCodeModel();
8298 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8299 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8301 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8304 if (Subtarget->isPICStyleRIPRel() &&
8305 (M == CodeModel::Small || M == CodeModel::Kernel))
8306 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8308 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8310 // With PIC, the address is actually $g + Offset.
8311 if (isGlobalRelativeToPICBase(OpFlags)) {
8312 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8313 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8321 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8322 int64_t Offset, SelectionDAG &DAG) const {
8323 // Create the TargetGlobalAddress node, folding in the constant
8324 // offset if it is legal.
8325 unsigned char OpFlags =
8326 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8327 CodeModel::Model M = getTargetMachine().getCodeModel();
8329 if (OpFlags == X86II::MO_NO_FLAG &&
8330 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8331 // A direct static reference to a global.
8332 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8335 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8338 if (Subtarget->isPICStyleRIPRel() &&
8339 (M == CodeModel::Small || M == CodeModel::Kernel))
8340 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8342 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8344 // With PIC, the address is actually $g + Offset.
8345 if (isGlobalRelativeToPICBase(OpFlags)) {
8346 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8347 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8351 // For globals that require a load from a stub to get the address, emit the
8353 if (isGlobalStubReference(OpFlags))
8354 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8355 MachinePointerInfo::getGOT(), false, false, false, 0);
8357 // If there was a non-zero offset that we didn't fold, create an explicit
8360 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8361 DAG.getConstant(Offset, getPointerTy()));
8367 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8368 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8369 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8370 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8374 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8375 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8376 unsigned char OperandFlags, bool LocalDynamic = false) {
8377 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8378 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8380 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8381 GA->getValueType(0),
8385 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8389 SDValue Ops[] = { Chain, TGA, *InFlag };
8390 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8392 SDValue Ops[] = { Chain, TGA };
8393 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8396 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8397 MFI->setAdjustsStack(true);
8399 SDValue Flag = Chain.getValue(1);
8400 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8403 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8405 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8408 SDLoc dl(GA); // ? function entry point might be better
8409 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8410 DAG.getNode(X86ISD::GlobalBaseReg,
8411 SDLoc(), PtrVT), InFlag);
8412 InFlag = Chain.getValue(1);
8414 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8417 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8419 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8421 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8422 X86::RAX, X86II::MO_TLSGD);
8425 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8431 // Get the start address of the TLS block for this module.
8432 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8433 .getInfo<X86MachineFunctionInfo>();
8434 MFI->incNumLocalDynamicTLSAccesses();
8438 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8439 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8442 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8443 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8444 InFlag = Chain.getValue(1);
8445 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8446 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8449 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8453 unsigned char OperandFlags = X86II::MO_DTPOFF;
8454 unsigned WrapperKind = X86ISD::Wrapper;
8455 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8456 GA->getValueType(0),
8457 GA->getOffset(), OperandFlags);
8458 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8460 // Add x@dtpoff with the base.
8461 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8464 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8465 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8466 const EVT PtrVT, TLSModel::Model model,
8467 bool is64Bit, bool isPIC) {
8470 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8471 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8472 is64Bit ? 257 : 256));
8474 SDValue ThreadPointer =
8475 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8476 MachinePointerInfo(Ptr), false, false, false, 0);
8478 unsigned char OperandFlags = 0;
8479 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8481 unsigned WrapperKind = X86ISD::Wrapper;
8482 if (model == TLSModel::LocalExec) {
8483 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8484 } else if (model == TLSModel::InitialExec) {
8486 OperandFlags = X86II::MO_GOTTPOFF;
8487 WrapperKind = X86ISD::WrapperRIP;
8489 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8492 llvm_unreachable("Unexpected model");
8495 // emit "addl x@ntpoff,%eax" (local exec)
8496 // or "addl x@indntpoff,%eax" (initial exec)
8497 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8499 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8500 GA->getOffset(), OperandFlags);
8501 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8503 if (model == TLSModel::InitialExec) {
8504 if (isPIC && !is64Bit) {
8505 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8506 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8510 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8511 MachinePointerInfo::getGOT(), false, false, false, 0);
8514 // The address of the thread local variable is the add of the thread
8515 // pointer with the offset of the variable.
8516 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8520 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8522 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8523 const GlobalValue *GV = GA->getGlobal();
8525 if (Subtarget->isTargetELF()) {
8526 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8529 case TLSModel::GeneralDynamic:
8530 if (Subtarget->is64Bit())
8531 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8532 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8533 case TLSModel::LocalDynamic:
8534 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8535 Subtarget->is64Bit());
8536 case TLSModel::InitialExec:
8537 case TLSModel::LocalExec:
8538 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8539 Subtarget->is64Bit(),
8540 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8542 llvm_unreachable("Unknown TLS model.");
8545 if (Subtarget->isTargetDarwin()) {
8546 // Darwin only has one model of TLS. Lower to that.
8547 unsigned char OpFlag = 0;
8548 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8549 X86ISD::WrapperRIP : X86ISD::Wrapper;
8551 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8553 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8554 !Subtarget->is64Bit();
8556 OpFlag = X86II::MO_TLVP_PIC_BASE;
8558 OpFlag = X86II::MO_TLVP;
8560 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8561 GA->getValueType(0),
8562 GA->getOffset(), OpFlag);
8563 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8565 // With PIC32, the address is actually $g + Offset.
8567 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8568 DAG.getNode(X86ISD::GlobalBaseReg,
8569 SDLoc(), getPointerTy()),
8572 // Lowering the machine isd will make sure everything is in the right
8574 SDValue Chain = DAG.getEntryNode();
8575 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8576 SDValue Args[] = { Chain, Offset };
8577 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8579 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8580 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8581 MFI->setAdjustsStack(true);
8583 // And our return value (tls address) is in the standard call return value
8585 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8586 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8590 if (Subtarget->isTargetKnownWindowsMSVC() ||
8591 Subtarget->isTargetWindowsGNU()) {
8592 // Just use the implicit TLS architecture
8593 // Need to generate someting similar to:
8594 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8596 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8597 // mov rcx, qword [rdx+rcx*8]
8598 // mov eax, .tls$:tlsvar
8599 // [rax+rcx] contains the address
8600 // Windows 64bit: gs:0x58
8601 // Windows 32bit: fs:__tls_array
8603 // If GV is an alias then use the aliasee for determining
8604 // thread-localness.
8605 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8606 GV = GA->getAliasedGlobal();
8608 SDValue Chain = DAG.getEntryNode();
8610 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8611 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8612 // use its literal value of 0x2C.
8613 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8614 ? Type::getInt8PtrTy(*DAG.getContext(),
8616 : Type::getInt32PtrTy(*DAG.getContext(),
8620 Subtarget->is64Bit()
8621 ? DAG.getIntPtrConstant(0x58)
8622 : (Subtarget->isTargetWindowsGNU()
8623 ? DAG.getIntPtrConstant(0x2C)
8624 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8626 SDValue ThreadPointer =
8627 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8628 MachinePointerInfo(Ptr), false, false, false, 0);
8630 // Load the _tls_index variable
8631 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8632 if (Subtarget->is64Bit())
8633 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8634 IDX, MachinePointerInfo(), MVT::i32,
8637 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8638 false, false, false, 0);
8640 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8642 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8644 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8645 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8646 false, false, false, 0);
8648 // Get the offset of start of .tls section
8649 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8650 GA->getValueType(0),
8651 GA->getOffset(), X86II::MO_SECREL);
8652 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8654 // The address of the thread local variable is the add of the thread
8655 // pointer with the offset of the variable.
8656 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8659 llvm_unreachable("TLS not implemented for this target.");
8662 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8663 /// and take a 2 x i32 value to shift plus a shift amount.
8664 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8665 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8666 MVT VT = Op.getSimpleValueType();
8667 unsigned VTBits = VT.getSizeInBits();
8669 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8670 SDValue ShOpLo = Op.getOperand(0);
8671 SDValue ShOpHi = Op.getOperand(1);
8672 SDValue ShAmt = Op.getOperand(2);
8673 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8674 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8676 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8677 DAG.getConstant(VTBits - 1, MVT::i8));
8678 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8679 DAG.getConstant(VTBits - 1, MVT::i8))
8680 : DAG.getConstant(0, VT);
8683 if (Op.getOpcode() == ISD::SHL_PARTS) {
8684 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8685 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8687 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8688 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8691 // If the shift amount is larger or equal than the width of a part we can't
8692 // rely on the results of shld/shrd. Insert a test and select the appropriate
8693 // values for large shift amounts.
8694 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8695 DAG.getConstant(VTBits, MVT::i8));
8696 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8697 AndNode, DAG.getConstant(0, MVT::i8));
8700 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8701 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8702 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8704 if (Op.getOpcode() == ISD::SHL_PARTS) {
8705 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8706 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8708 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8709 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8712 SDValue Ops[2] = { Lo, Hi };
8713 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8716 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8717 SelectionDAG &DAG) const {
8718 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8720 if (SrcVT.isVector())
8723 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8724 "Unknown SINT_TO_FP to lower!");
8726 // These are really Legal; return the operand so the caller accepts it as
8728 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8730 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8731 Subtarget->is64Bit()) {
8736 unsigned Size = SrcVT.getSizeInBits()/8;
8737 MachineFunction &MF = DAG.getMachineFunction();
8738 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8739 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8740 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8742 MachinePointerInfo::getFixedStack(SSFI),
8744 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8747 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8749 SelectionDAG &DAG) const {
8753 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8755 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8757 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8759 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8761 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8762 MachineMemOperand *MMO;
8764 int SSFI = FI->getIndex();
8766 DAG.getMachineFunction()
8767 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8768 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8770 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8771 StackSlot = StackSlot.getOperand(1);
8773 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8774 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8776 Tys, Ops, array_lengthof(Ops),
8780 Chain = Result.getValue(1);
8781 SDValue InFlag = Result.getValue(2);
8783 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8784 // shouldn't be necessary except that RFP cannot be live across
8785 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8786 MachineFunction &MF = DAG.getMachineFunction();
8787 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8788 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8789 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8790 Tys = DAG.getVTList(MVT::Other);
8792 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8794 MachineMemOperand *MMO =
8795 DAG.getMachineFunction()
8796 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8797 MachineMemOperand::MOStore, SSFISize, SSFISize);
8799 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8800 Ops, array_lengthof(Ops),
8801 Op.getValueType(), MMO);
8802 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8803 MachinePointerInfo::getFixedStack(SSFI),
8804 false, false, false, 0);
8810 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8811 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8812 SelectionDAG &DAG) const {
8813 // This algorithm is not obvious. Here it is what we're trying to output:
8816 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8817 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8821 pshufd $0x4e, %xmm0, %xmm1
8827 LLVMContext *Context = DAG.getContext();
8829 // Build some magic constants.
8830 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8831 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8832 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8834 SmallVector<Constant*,2> CV1;
8836 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8837 APInt(64, 0x4330000000000000ULL))));
8839 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8840 APInt(64, 0x4530000000000000ULL))));
8841 Constant *C1 = ConstantVector::get(CV1);
8842 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8844 // Load the 64-bit value into an XMM register.
8845 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8847 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8848 MachinePointerInfo::getConstantPool(),
8849 false, false, false, 16);
8850 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8851 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8854 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8855 MachinePointerInfo::getConstantPool(),
8856 false, false, false, 16);
8857 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8858 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8861 if (Subtarget->hasSSE3()) {
8862 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8863 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8865 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8866 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8868 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8869 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8873 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8874 DAG.getIntPtrConstant(0));
8877 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8878 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8879 SelectionDAG &DAG) const {
8881 // FP constant to bias correct the final result.
8882 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8885 // Load the 32-bit value into an XMM register.
8886 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8889 // Zero out the upper parts of the register.
8890 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8892 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8893 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8894 DAG.getIntPtrConstant(0));
8896 // Or the load with the bias.
8897 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8898 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8899 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8901 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8902 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8903 MVT::v2f64, Bias)));
8904 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8905 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8906 DAG.getIntPtrConstant(0));
8908 // Subtract the bias.
8909 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8911 // Handle final rounding.
8912 EVT DestVT = Op.getValueType();
8914 if (DestVT.bitsLT(MVT::f64))
8915 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8916 DAG.getIntPtrConstant(0));
8917 if (DestVT.bitsGT(MVT::f64))
8918 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8920 // Handle final rounding.
8924 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8925 SelectionDAG &DAG) const {
8926 SDValue N0 = Op.getOperand(0);
8927 MVT SVT = N0.getSimpleValueType();
8930 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8931 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8932 "Custom UINT_TO_FP is not supported!");
8934 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8935 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8936 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8939 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8940 SelectionDAG &DAG) const {
8941 SDValue N0 = Op.getOperand(0);
8944 if (Op.getValueType().isVector())
8945 return lowerUINT_TO_FP_vec(Op, DAG);
8947 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8948 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8949 // the optimization here.
8950 if (DAG.SignBitIsZero(N0))
8951 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8953 MVT SrcVT = N0.getSimpleValueType();
8954 MVT DstVT = Op.getSimpleValueType();
8955 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8956 return LowerUINT_TO_FP_i64(Op, DAG);
8957 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8958 return LowerUINT_TO_FP_i32(Op, DAG);
8959 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8962 // Make a 64-bit buffer, and use it to build an FILD.
8963 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8964 if (SrcVT == MVT::i32) {
8965 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8966 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8967 getPointerTy(), StackSlot, WordOff);
8968 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8969 StackSlot, MachinePointerInfo(),
8971 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8972 OffsetSlot, MachinePointerInfo(),
8974 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8978 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8979 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8980 StackSlot, MachinePointerInfo(),
8982 // For i64 source, we need to add the appropriate power of 2 if the input
8983 // was negative. This is the same as the optimization in
8984 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8985 // we must be careful to do the computation in x87 extended precision, not
8986 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8987 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8988 MachineMemOperand *MMO =
8989 DAG.getMachineFunction()
8990 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8991 MachineMemOperand::MOLoad, 8, 8);
8993 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8994 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8995 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8996 array_lengthof(Ops), MVT::i64, MMO);
8998 APInt FF(32, 0x5F800000ULL);
9000 // Check whether the sign bit is set.
9001 SDValue SignSet = DAG.getSetCC(dl,
9002 getSetCCResultType(*DAG.getContext(), MVT::i64),
9003 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9006 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9007 SDValue FudgePtr = DAG.getConstantPool(
9008 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9011 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9012 SDValue Zero = DAG.getIntPtrConstant(0);
9013 SDValue Four = DAG.getIntPtrConstant(4);
9014 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9016 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9018 // Load the value out, extending it from f32 to f80.
9019 // FIXME: Avoid the extend by constructing the right constant pool?
9020 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9021 FudgePtr, MachinePointerInfo::getConstantPool(),
9022 MVT::f32, false, false, 4);
9023 // Extend everything to 80 bits to force it to be done on x87.
9024 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9025 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9028 std::pair<SDValue,SDValue>
9029 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9030 bool IsSigned, bool IsReplace) const {
9033 EVT DstTy = Op.getValueType();
9035 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9036 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9040 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9041 DstTy.getSimpleVT() >= MVT::i16 &&
9042 "Unknown FP_TO_INT to lower!");
9044 // These are really Legal.
9045 if (DstTy == MVT::i32 &&
9046 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9047 return std::make_pair(SDValue(), SDValue());
9048 if (Subtarget->is64Bit() &&
9049 DstTy == MVT::i64 &&
9050 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9051 return std::make_pair(SDValue(), SDValue());
9053 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9054 // stack slot, or into the FTOL runtime function.
9055 MachineFunction &MF = DAG.getMachineFunction();
9056 unsigned MemSize = DstTy.getSizeInBits()/8;
9057 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9058 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9061 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9062 Opc = X86ISD::WIN_FTOL;
9064 switch (DstTy.getSimpleVT().SimpleTy) {
9065 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9066 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9067 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9068 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9071 SDValue Chain = DAG.getEntryNode();
9072 SDValue Value = Op.getOperand(0);
9073 EVT TheVT = Op.getOperand(0).getValueType();
9074 // FIXME This causes a redundant load/store if the SSE-class value is already
9075 // in memory, such as if it is on the callstack.
9076 if (isScalarFPTypeInSSEReg(TheVT)) {
9077 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9078 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9079 MachinePointerInfo::getFixedStack(SSFI),
9081 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9083 Chain, StackSlot, DAG.getValueType(TheVT)
9086 MachineMemOperand *MMO =
9087 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9088 MachineMemOperand::MOLoad, MemSize, MemSize);
9089 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9090 array_lengthof(Ops), DstTy, MMO);
9091 Chain = Value.getValue(1);
9092 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9093 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9096 MachineMemOperand *MMO =
9097 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9098 MachineMemOperand::MOStore, MemSize, MemSize);
9100 if (Opc != X86ISD::WIN_FTOL) {
9101 // Build the FP_TO_INT*_IN_MEM
9102 SDValue Ops[] = { Chain, Value, StackSlot };
9103 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9104 Ops, array_lengthof(Ops), DstTy,
9106 return std::make_pair(FIST, StackSlot);
9108 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9109 DAG.getVTList(MVT::Other, MVT::Glue),
9111 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9112 MVT::i32, ftol.getValue(1));
9113 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9114 MVT::i32, eax.getValue(2));
9115 SDValue Ops[] = { eax, edx };
9116 SDValue pair = IsReplace
9117 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9118 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9119 return std::make_pair(pair, SDValue());
9123 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9124 const X86Subtarget *Subtarget) {
9125 MVT VT = Op->getSimpleValueType(0);
9126 SDValue In = Op->getOperand(0);
9127 MVT InVT = In.getSimpleValueType();
9130 // Optimize vectors in AVX mode:
9133 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9134 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9135 // Concat upper and lower parts.
9138 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9139 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9140 // Concat upper and lower parts.
9143 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9144 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9145 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9148 if (Subtarget->hasInt256())
9149 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9151 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9152 SDValue Undef = DAG.getUNDEF(InVT);
9153 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9154 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9155 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9157 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9158 VT.getVectorNumElements()/2);
9160 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9161 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9163 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9166 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9167 SelectionDAG &DAG) {
9168 MVT VT = Op->getSimpleValueType(0);
9169 SDValue In = Op->getOperand(0);
9170 MVT InVT = In.getSimpleValueType();
9172 unsigned int NumElts = VT.getVectorNumElements();
9173 if (NumElts != 8 && NumElts != 16)
9176 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9177 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9179 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9180 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9181 // Now we have only mask extension
9182 assert(InVT.getVectorElementType() == MVT::i1);
9183 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9184 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9185 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9186 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9187 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9188 MachinePointerInfo::getConstantPool(),
9189 false, false, false, Alignment);
9191 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9192 if (VT.is512BitVector())
9194 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9197 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9198 SelectionDAG &DAG) {
9199 if (Subtarget->hasFp256()) {
9200 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9208 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9209 SelectionDAG &DAG) {
9211 MVT VT = Op.getSimpleValueType();
9212 SDValue In = Op.getOperand(0);
9213 MVT SVT = In.getSimpleValueType();
9215 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9216 return LowerZERO_EXTEND_AVX512(Op, DAG);
9218 if (Subtarget->hasFp256()) {
9219 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9224 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9225 VT.getVectorNumElements() != SVT.getVectorNumElements());
9229 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9231 MVT VT = Op.getSimpleValueType();
9232 SDValue In = Op.getOperand(0);
9233 MVT InVT = In.getSimpleValueType();
9235 if (VT == MVT::i1) {
9236 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9237 "Invalid scalar TRUNCATE operation");
9238 if (InVT == MVT::i32)
9240 if (InVT.getSizeInBits() == 64)
9241 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9242 else if (InVT.getSizeInBits() < 32)
9243 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9244 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9246 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9247 "Invalid TRUNCATE operation");
9249 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9250 if (VT.getVectorElementType().getSizeInBits() >=8)
9251 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9253 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9254 unsigned NumElts = InVT.getVectorNumElements();
9255 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9256 if (InVT.getSizeInBits() < 512) {
9257 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9258 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9262 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9263 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9264 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9265 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9266 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9267 MachinePointerInfo::getConstantPool(),
9268 false, false, false, Alignment);
9269 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9270 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9271 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9274 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9275 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9276 if (Subtarget->hasInt256()) {
9277 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9278 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9279 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9281 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9282 DAG.getIntPtrConstant(0));
9285 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9286 DAG.getIntPtrConstant(0));
9287 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9288 DAG.getIntPtrConstant(2));
9289 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9290 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9291 static const int ShufMask[] = {0, 2, 4, 6};
9292 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9295 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9296 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9297 if (Subtarget->hasInt256()) {
9298 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9300 SmallVector<SDValue,32> pshufbMask;
9301 for (unsigned i = 0; i < 2; ++i) {
9302 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9303 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9304 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9305 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9306 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9307 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9308 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9309 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9310 for (unsigned j = 0; j < 8; ++j)
9311 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9313 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9314 &pshufbMask[0], 32);
9315 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9316 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9318 static const int ShufMask[] = {0, 2, -1, -1};
9319 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9321 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9322 DAG.getIntPtrConstant(0));
9323 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9326 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9327 DAG.getIntPtrConstant(0));
9329 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9330 DAG.getIntPtrConstant(4));
9332 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9333 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9336 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9337 -1, -1, -1, -1, -1, -1, -1, -1};
9339 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9340 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9341 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9343 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9344 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9346 // The MOVLHPS Mask:
9347 static const int ShufMask2[] = {0, 1, 4, 5};
9348 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9349 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9352 // Handle truncation of V256 to V128 using shuffles.
9353 if (!VT.is128BitVector() || !InVT.is256BitVector())
9356 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9358 unsigned NumElems = VT.getVectorNumElements();
9359 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9361 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9362 // Prepare truncation shuffle mask
9363 for (unsigned i = 0; i != NumElems; ++i)
9365 SDValue V = DAG.getVectorShuffle(NVT, DL,
9366 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9367 DAG.getUNDEF(NVT), &MaskVec[0]);
9368 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9369 DAG.getIntPtrConstant(0));
9372 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9373 SelectionDAG &DAG) const {
9374 assert(!Op.getSimpleValueType().isVector());
9376 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9377 /*IsSigned=*/ true, /*IsReplace=*/ false);
9378 SDValue FIST = Vals.first, StackSlot = Vals.second;
9379 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9380 if (FIST.getNode() == 0) return Op;
9382 if (StackSlot.getNode())
9384 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9385 FIST, StackSlot, MachinePointerInfo(),
9386 false, false, false, 0);
9388 // The node is the result.
9392 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9393 SelectionDAG &DAG) const {
9394 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9395 /*IsSigned=*/ false, /*IsReplace=*/ false);
9396 SDValue FIST = Vals.first, StackSlot = Vals.second;
9397 assert(FIST.getNode() && "Unexpected failure");
9399 if (StackSlot.getNode())
9401 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9402 FIST, StackSlot, MachinePointerInfo(),
9403 false, false, false, 0);
9405 // The node is the result.
9409 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9411 MVT VT = Op.getSimpleValueType();
9412 SDValue In = Op.getOperand(0);
9413 MVT SVT = In.getSimpleValueType();
9415 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9417 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9418 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9419 In, DAG.getUNDEF(SVT)));
9422 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9423 LLVMContext *Context = DAG.getContext();
9425 MVT VT = Op.getSimpleValueType();
9427 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9428 if (VT.isVector()) {
9429 EltVT = VT.getVectorElementType();
9430 NumElts = VT.getVectorNumElements();
9433 if (EltVT == MVT::f64)
9434 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9435 APInt(64, ~(1ULL << 63))));
9437 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9438 APInt(32, ~(1U << 31))));
9439 C = ConstantVector::getSplat(NumElts, C);
9440 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9441 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9442 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9443 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9444 MachinePointerInfo::getConstantPool(),
9445 false, false, false, Alignment);
9446 if (VT.isVector()) {
9447 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9448 return DAG.getNode(ISD::BITCAST, dl, VT,
9449 DAG.getNode(ISD::AND, dl, ANDVT,
9450 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9452 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9454 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9457 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9458 LLVMContext *Context = DAG.getContext();
9460 MVT VT = Op.getSimpleValueType();
9462 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9463 if (VT.isVector()) {
9464 EltVT = VT.getVectorElementType();
9465 NumElts = VT.getVectorNumElements();
9468 if (EltVT == MVT::f64)
9469 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9470 APInt(64, 1ULL << 63)));
9472 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9473 APInt(32, 1U << 31)));
9474 C = ConstantVector::getSplat(NumElts, C);
9475 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9476 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9477 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9478 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9479 MachinePointerInfo::getConstantPool(),
9480 false, false, false, Alignment);
9481 if (VT.isVector()) {
9482 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9483 return DAG.getNode(ISD::BITCAST, dl, VT,
9484 DAG.getNode(ISD::XOR, dl, XORVT,
9485 DAG.getNode(ISD::BITCAST, dl, XORVT,
9487 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9490 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9493 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9494 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9495 LLVMContext *Context = DAG.getContext();
9496 SDValue Op0 = Op.getOperand(0);
9497 SDValue Op1 = Op.getOperand(1);
9499 MVT VT = Op.getSimpleValueType();
9500 MVT SrcVT = Op1.getSimpleValueType();
9502 // If second operand is smaller, extend it first.
9503 if (SrcVT.bitsLT(VT)) {
9504 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9507 // And if it is bigger, shrink it first.
9508 if (SrcVT.bitsGT(VT)) {
9509 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9513 // At this point the operands and the result should have the same
9514 // type, and that won't be f80 since that is not custom lowered.
9516 // First get the sign bit of second operand.
9517 SmallVector<Constant*,4> CV;
9518 if (SrcVT == MVT::f64) {
9519 const fltSemantics &Sem = APFloat::IEEEdouble;
9520 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9521 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9523 const fltSemantics &Sem = APFloat::IEEEsingle;
9524 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9525 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9526 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9527 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9529 Constant *C = ConstantVector::get(CV);
9530 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9531 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9532 MachinePointerInfo::getConstantPool(),
9533 false, false, false, 16);
9534 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9536 // Shift sign bit right or left if the two operands have different types.
9537 if (SrcVT.bitsGT(VT)) {
9538 // Op0 is MVT::f32, Op1 is MVT::f64.
9539 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9540 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9541 DAG.getConstant(32, MVT::i32));
9542 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9543 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9544 DAG.getIntPtrConstant(0));
9547 // Clear first operand sign bit.
9549 if (VT == MVT::f64) {
9550 const fltSemantics &Sem = APFloat::IEEEdouble;
9551 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9552 APInt(64, ~(1ULL << 63)))));
9553 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9555 const fltSemantics &Sem = APFloat::IEEEsingle;
9556 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9557 APInt(32, ~(1U << 31)))));
9558 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9559 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9560 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9562 C = ConstantVector::get(CV);
9563 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9564 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9565 MachinePointerInfo::getConstantPool(),
9566 false, false, false, 16);
9567 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9569 // Or the value with the sign bit.
9570 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9573 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9574 SDValue N0 = Op.getOperand(0);
9576 MVT VT = Op.getSimpleValueType();
9578 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9579 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9580 DAG.getConstant(1, VT));
9581 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9584 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9586 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9587 SelectionDAG &DAG) {
9588 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9590 if (!Subtarget->hasSSE41())
9593 if (!Op->hasOneUse())
9596 SDNode *N = Op.getNode();
9599 SmallVector<SDValue, 8> Opnds;
9600 DenseMap<SDValue, unsigned> VecInMap;
9601 SmallVector<SDValue, 8> VecIns;
9602 EVT VT = MVT::Other;
9604 // Recognize a special case where a vector is casted into wide integer to
9606 Opnds.push_back(N->getOperand(0));
9607 Opnds.push_back(N->getOperand(1));
9609 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9610 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9611 // BFS traverse all OR'd operands.
9612 if (I->getOpcode() == ISD::OR) {
9613 Opnds.push_back(I->getOperand(0));
9614 Opnds.push_back(I->getOperand(1));
9615 // Re-evaluate the number of nodes to be traversed.
9616 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9620 // Quit if a non-EXTRACT_VECTOR_ELT
9621 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9624 // Quit if without a constant index.
9625 SDValue Idx = I->getOperand(1);
9626 if (!isa<ConstantSDNode>(Idx))
9629 SDValue ExtractedFromVec = I->getOperand(0);
9630 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9631 if (M == VecInMap.end()) {
9632 VT = ExtractedFromVec.getValueType();
9633 // Quit if not 128/256-bit vector.
9634 if (!VT.is128BitVector() && !VT.is256BitVector())
9636 // Quit if not the same type.
9637 if (VecInMap.begin() != VecInMap.end() &&
9638 VT != VecInMap.begin()->first.getValueType())
9640 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9641 VecIns.push_back(ExtractedFromVec);
9643 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9646 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9647 "Not extracted from 128-/256-bit vector.");
9649 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9651 for (DenseMap<SDValue, unsigned>::const_iterator
9652 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9653 // Quit if not all elements are used.
9654 if (I->second != FullMask)
9658 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9660 // Cast all vectors into TestVT for PTEST.
9661 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9662 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9664 // If more than one full vectors are evaluated, OR them first before PTEST.
9665 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9666 // Each iteration will OR 2 nodes and append the result until there is only
9667 // 1 node left, i.e. the final OR'd value of all vectors.
9668 SDValue LHS = VecIns[Slot];
9669 SDValue RHS = VecIns[Slot + 1];
9670 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9673 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9674 VecIns.back(), VecIns.back());
9677 /// \brief return true if \c Op has a use that doesn't just read flags.
9678 static bool hasNonFlagsUse(SDValue Op) {
9679 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9682 unsigned UOpNo = UI.getOperandNo();
9683 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9684 // Look pass truncate.
9685 UOpNo = User->use_begin().getOperandNo();
9686 User = *User->use_begin();
9689 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9690 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9696 /// Emit nodes that will be selected as "test Op0,Op0", or something
9698 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9699 SelectionDAG &DAG) const {
9700 if (Op.getValueType() == MVT::i1)
9701 // KORTEST instruction should be selected
9702 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9703 DAG.getConstant(0, Op.getValueType()));
9705 // CF and OF aren't always set the way we want. Determine which
9706 // of these we need.
9707 bool NeedCF = false;
9708 bool NeedOF = false;
9711 case X86::COND_A: case X86::COND_AE:
9712 case X86::COND_B: case X86::COND_BE:
9715 case X86::COND_G: case X86::COND_GE:
9716 case X86::COND_L: case X86::COND_LE:
9717 case X86::COND_O: case X86::COND_NO:
9721 // See if we can use the EFLAGS value from the operand instead of
9722 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9723 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9724 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9725 // Emit a CMP with 0, which is the TEST pattern.
9726 //if (Op.getValueType() == MVT::i1)
9727 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9728 // DAG.getConstant(0, MVT::i1));
9729 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9730 DAG.getConstant(0, Op.getValueType()));
9732 unsigned Opcode = 0;
9733 unsigned NumOperands = 0;
9735 // Truncate operations may prevent the merge of the SETCC instruction
9736 // and the arithmetic instruction before it. Attempt to truncate the operands
9737 // of the arithmetic instruction and use a reduced bit-width instruction.
9738 bool NeedTruncation = false;
9739 SDValue ArithOp = Op;
9740 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9741 SDValue Arith = Op->getOperand(0);
9742 // Both the trunc and the arithmetic op need to have one user each.
9743 if (Arith->hasOneUse())
9744 switch (Arith.getOpcode()) {
9751 NeedTruncation = true;
9757 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9758 // which may be the result of a CAST. We use the variable 'Op', which is the
9759 // non-casted variable when we check for possible users.
9760 switch (ArithOp.getOpcode()) {
9762 // Due to an isel shortcoming, be conservative if this add is likely to be
9763 // selected as part of a load-modify-store instruction. When the root node
9764 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9765 // uses of other nodes in the match, such as the ADD in this case. This
9766 // leads to the ADD being left around and reselected, with the result being
9767 // two adds in the output. Alas, even if none our users are stores, that
9768 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9769 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9770 // climbing the DAG back to the root, and it doesn't seem to be worth the
9772 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9773 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9774 if (UI->getOpcode() != ISD::CopyToReg &&
9775 UI->getOpcode() != ISD::SETCC &&
9776 UI->getOpcode() != ISD::STORE)
9779 if (ConstantSDNode *C =
9780 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9781 // An add of one will be selected as an INC.
9782 if (C->getAPIntValue() == 1) {
9783 Opcode = X86ISD::INC;
9788 // An add of negative one (subtract of one) will be selected as a DEC.
9789 if (C->getAPIntValue().isAllOnesValue()) {
9790 Opcode = X86ISD::DEC;
9796 // Otherwise use a regular EFLAGS-setting add.
9797 Opcode = X86ISD::ADD;
9802 // If we have a constant logical shift that's only used in a comparison
9803 // against zero turn it into an equivalent AND. This allows turning it into
9804 // a TEST instruction later.
9805 if (isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9806 EVT VT = Op.getValueType();
9807 unsigned BitWidth = VT.getSizeInBits();
9808 unsigned ShAmt = Op->getConstantOperandVal(1);
9809 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9811 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9812 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9813 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9814 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9816 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9817 DAG.getConstant(Mask, VT));
9818 DAG.ReplaceAllUsesWith(Op, New);
9824 // If the primary and result isn't used, don't bother using X86ISD::AND,
9825 // because a TEST instruction will be better.
9826 if (!hasNonFlagsUse(Op))
9832 // Due to the ISEL shortcoming noted above, be conservative if this op is
9833 // likely to be selected as part of a load-modify-store instruction.
9834 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9835 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9836 if (UI->getOpcode() == ISD::STORE)
9839 // Otherwise use a regular EFLAGS-setting instruction.
9840 switch (ArithOp.getOpcode()) {
9841 default: llvm_unreachable("unexpected operator!");
9842 case ISD::SUB: Opcode = X86ISD::SUB; break;
9843 case ISD::XOR: Opcode = X86ISD::XOR; break;
9844 case ISD::AND: Opcode = X86ISD::AND; break;
9846 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9847 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9848 if (EFLAGS.getNode())
9851 Opcode = X86ISD::OR;
9865 return SDValue(Op.getNode(), 1);
9871 // If we found that truncation is beneficial, perform the truncation and
9873 if (NeedTruncation) {
9874 EVT VT = Op.getValueType();
9875 SDValue WideVal = Op->getOperand(0);
9876 EVT WideVT = WideVal.getValueType();
9877 unsigned ConvertedOp = 0;
9878 // Use a target machine opcode to prevent further DAGCombine
9879 // optimizations that may separate the arithmetic operations
9880 // from the setcc node.
9881 switch (WideVal.getOpcode()) {
9883 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9884 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9885 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9886 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9887 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9891 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9892 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9893 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9894 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9895 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9901 // Emit a CMP with 0, which is the TEST pattern.
9902 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9903 DAG.getConstant(0, Op.getValueType()));
9905 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9906 SmallVector<SDValue, 4> Ops;
9907 for (unsigned i = 0; i != NumOperands; ++i)
9908 Ops.push_back(Op.getOperand(i));
9910 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9911 DAG.ReplaceAllUsesWith(Op, New);
9912 return SDValue(New.getNode(), 1);
9915 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9917 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9918 SDLoc dl, SelectionDAG &DAG) const {
9919 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9920 if (C->getAPIntValue() == 0)
9921 return EmitTest(Op0, X86CC, dl, DAG);
9923 if (Op0.getValueType() == MVT::i1)
9924 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
9927 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9928 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9929 // Do the comparison at i32 if it's smaller, besides the Atom case.
9930 // This avoids subregister aliasing issues. Keep the smaller reference
9931 // if we're optimizing for size, however, as that'll allow better folding
9932 // of memory operations.
9933 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9934 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9935 AttributeSet::FunctionIndex, Attribute::MinSize) &&
9936 !Subtarget->isAtom()) {
9938 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9939 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9940 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9942 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9943 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9944 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9946 return SDValue(Sub.getNode(), 1);
9948 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9951 /// Convert a comparison if required by the subtarget.
9952 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9953 SelectionDAG &DAG) const {
9954 // If the subtarget does not support the FUCOMI instruction, floating-point
9955 // comparisons have to be converted.
9956 if (Subtarget->hasCMov() ||
9957 Cmp.getOpcode() != X86ISD::CMP ||
9958 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9959 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9962 // The instruction selector will select an FUCOM instruction instead of
9963 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9964 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9965 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9967 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9968 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9969 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9970 DAG.getConstant(8, MVT::i8));
9971 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9972 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9975 static bool isAllOnes(SDValue V) {
9976 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9977 return C && C->isAllOnesValue();
9980 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9981 /// if it's possible.
9982 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9983 SDLoc dl, SelectionDAG &DAG) const {
9984 SDValue Op0 = And.getOperand(0);
9985 SDValue Op1 = And.getOperand(1);
9986 if (Op0.getOpcode() == ISD::TRUNCATE)
9987 Op0 = Op0.getOperand(0);
9988 if (Op1.getOpcode() == ISD::TRUNCATE)
9989 Op1 = Op1.getOperand(0);
9992 if (Op1.getOpcode() == ISD::SHL)
9993 std::swap(Op0, Op1);
9994 if (Op0.getOpcode() == ISD::SHL) {
9995 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9996 if (And00C->getZExtValue() == 1) {
9997 // If we looked past a truncate, check that it's only truncating away
9999 unsigned BitWidth = Op0.getValueSizeInBits();
10000 unsigned AndBitWidth = And.getValueSizeInBits();
10001 if (BitWidth > AndBitWidth) {
10003 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10004 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10008 RHS = Op0.getOperand(1);
10010 } else if (Op1.getOpcode() == ISD::Constant) {
10011 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10012 uint64_t AndRHSVal = AndRHS->getZExtValue();
10013 SDValue AndLHS = Op0;
10015 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10016 LHS = AndLHS.getOperand(0);
10017 RHS = AndLHS.getOperand(1);
10020 // Use BT if the immediate can't be encoded in a TEST instruction.
10021 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10023 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10027 if (LHS.getNode()) {
10028 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10029 // instruction. Since the shift amount is in-range-or-undefined, we know
10030 // that doing a bittest on the i32 value is ok. We extend to i32 because
10031 // the encoding for the i16 version is larger than the i32 version.
10032 // Also promote i16 to i32 for performance / code size reason.
10033 if (LHS.getValueType() == MVT::i8 ||
10034 LHS.getValueType() == MVT::i16)
10035 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10037 // If the operand types disagree, extend the shift amount to match. Since
10038 // BT ignores high bits (like shifts) we can use anyextend.
10039 if (LHS.getValueType() != RHS.getValueType())
10040 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10042 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10043 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10044 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10045 DAG.getConstant(Cond, MVT::i8), BT);
10051 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10053 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10058 // SSE Condition code mapping:
10067 switch (SetCCOpcode) {
10068 default: llvm_unreachable("Unexpected SETCC condition");
10070 case ISD::SETEQ: SSECC = 0; break;
10072 case ISD::SETGT: Swap = true; // Fallthrough
10074 case ISD::SETOLT: SSECC = 1; break;
10076 case ISD::SETGE: Swap = true; // Fallthrough
10078 case ISD::SETOLE: SSECC = 2; break;
10079 case ISD::SETUO: SSECC = 3; break;
10081 case ISD::SETNE: SSECC = 4; break;
10082 case ISD::SETULE: Swap = true; // Fallthrough
10083 case ISD::SETUGE: SSECC = 5; break;
10084 case ISD::SETULT: Swap = true; // Fallthrough
10085 case ISD::SETUGT: SSECC = 6; break;
10086 case ISD::SETO: SSECC = 7; break;
10088 case ISD::SETONE: SSECC = 8; break;
10091 std::swap(Op0, Op1);
10096 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10097 // ones, and then concatenate the result back.
10098 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10099 MVT VT = Op.getSimpleValueType();
10101 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10102 "Unsupported value type for operation");
10104 unsigned NumElems = VT.getVectorNumElements();
10106 SDValue CC = Op.getOperand(2);
10108 // Extract the LHS vectors
10109 SDValue LHS = Op.getOperand(0);
10110 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10111 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10113 // Extract the RHS vectors
10114 SDValue RHS = Op.getOperand(1);
10115 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10116 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10118 // Issue the operation on the smaller types and concatenate the result back
10119 MVT EltVT = VT.getVectorElementType();
10120 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10121 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10122 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10123 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10126 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10127 const X86Subtarget *Subtarget) {
10128 SDValue Op0 = Op.getOperand(0);
10129 SDValue Op1 = Op.getOperand(1);
10130 SDValue CC = Op.getOperand(2);
10131 MVT VT = Op.getSimpleValueType();
10134 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10135 Op.getValueType().getScalarType() == MVT::i1 &&
10136 "Cannot set masked compare for this operation");
10138 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10140 bool Unsigned = false;
10143 switch (SetCCOpcode) {
10144 default: llvm_unreachable("Unexpected SETCC condition");
10145 case ISD::SETNE: SSECC = 4; break;
10146 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10147 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10148 case ISD::SETLT: Swap = true; //fall-through
10149 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10150 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10151 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10152 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10153 case ISD::SETULE: Unsigned = true; //fall-through
10154 case ISD::SETLE: SSECC = 2; break;
10158 std::swap(Op0, Op1);
10160 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10161 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10162 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10163 DAG.getConstant(SSECC, MVT::i8));
10166 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10167 /// operand \p Op1. If non-trivial (for example because it's not constant)
10168 /// return an empty value.
10169 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10171 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10175 MVT VT = Op1.getSimpleValueType();
10176 MVT EVT = VT.getVectorElementType();
10177 unsigned n = VT.getVectorNumElements();
10178 SmallVector<SDValue, 8> ULTOp1;
10180 for (unsigned i = 0; i < n; ++i) {
10181 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10182 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10185 // Avoid underflow.
10186 APInt Val = Elt->getAPIntValue();
10190 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10193 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1.data(), ULTOp1.size());
10196 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10197 SelectionDAG &DAG) {
10198 SDValue Op0 = Op.getOperand(0);
10199 SDValue Op1 = Op.getOperand(1);
10200 SDValue CC = Op.getOperand(2);
10201 MVT VT = Op.getSimpleValueType();
10202 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10203 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10208 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10209 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10212 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10213 unsigned Opc = X86ISD::CMPP;
10214 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10215 assert(VT.getVectorNumElements() <= 16);
10216 Opc = X86ISD::CMPM;
10218 // In the two special cases we can't handle, emit two comparisons.
10221 unsigned CombineOpc;
10222 if (SetCCOpcode == ISD::SETUEQ) {
10223 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10225 assert(SetCCOpcode == ISD::SETONE);
10226 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10229 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10230 DAG.getConstant(CC0, MVT::i8));
10231 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10232 DAG.getConstant(CC1, MVT::i8));
10233 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10235 // Handle all other FP comparisons here.
10236 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10237 DAG.getConstant(SSECC, MVT::i8));
10240 // Break 256-bit integer vector compare into smaller ones.
10241 if (VT.is256BitVector() && !Subtarget->hasInt256())
10242 return Lower256IntVSETCC(Op, DAG);
10244 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10245 EVT OpVT = Op1.getValueType();
10246 if (Subtarget->hasAVX512()) {
10247 if (Op1.getValueType().is512BitVector() ||
10248 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10249 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10251 // In AVX-512 architecture setcc returns mask with i1 elements,
10252 // But there is no compare instruction for i8 and i16 elements.
10253 // We are not talking about 512-bit operands in this case, these
10254 // types are illegal.
10256 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10257 OpVT.getVectorElementType().getSizeInBits() >= 8))
10258 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10259 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10262 // We are handling one of the integer comparisons here. Since SSE only has
10263 // GT and EQ comparisons for integer, swapping operands and multiple
10264 // operations may be required for some comparisons.
10266 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10267 bool Subus = false;
10269 switch (SetCCOpcode) {
10270 default: llvm_unreachable("Unexpected SETCC condition");
10271 case ISD::SETNE: Invert = true;
10272 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10273 case ISD::SETLT: Swap = true;
10274 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10275 case ISD::SETGE: Swap = true;
10276 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10277 Invert = true; break;
10278 case ISD::SETULT: Swap = true;
10279 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10280 FlipSigns = true; break;
10281 case ISD::SETUGE: Swap = true;
10282 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10283 FlipSigns = true; Invert = true; break;
10286 // Special case: Use min/max operations for SETULE/SETUGE
10287 MVT VET = VT.getVectorElementType();
10289 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10290 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10293 switch (SetCCOpcode) {
10295 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10296 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10299 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10302 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10303 if (!MinMax && hasSubus) {
10304 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10306 // t = psubus Op0, Op1
10307 // pcmpeq t, <0..0>
10308 switch (SetCCOpcode) {
10310 case ISD::SETULT: {
10311 // If the comparison is against a constant we can turn this into a
10312 // setule. With psubus, setule does not require a swap. This is
10313 // beneficial because the constant in the register is no longer
10314 // destructed as the destination so it can be hoisted out of a loop.
10315 // Only do this pre-AVX since vpcmp* is no longer destructive.
10316 if (Subtarget->hasAVX())
10318 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10319 if (ULEOp1.getNode()) {
10321 Subus = true; Invert = false; Swap = false;
10325 // Psubus is better than flip-sign because it requires no inversion.
10326 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10327 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10331 Opc = X86ISD::SUBUS;
10337 std::swap(Op0, Op1);
10339 // Check that the operation in question is available (most are plain SSE2,
10340 // but PCMPGTQ and PCMPEQQ have different requirements).
10341 if (VT == MVT::v2i64) {
10342 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10343 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10345 // First cast everything to the right type.
10346 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10347 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10349 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10350 // bits of the inputs before performing those operations. The lower
10351 // compare is always unsigned.
10354 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10356 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10357 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10358 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10359 Sign, Zero, Sign, Zero);
10361 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10362 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10364 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10365 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10366 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10368 // Create masks for only the low parts/high parts of the 64 bit integers.
10369 static const int MaskHi[] = { 1, 1, 3, 3 };
10370 static const int MaskLo[] = { 0, 0, 2, 2 };
10371 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10372 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10373 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10375 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10376 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10379 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10381 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10384 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10385 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10386 // pcmpeqd + pshufd + pand.
10387 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10389 // First cast everything to the right type.
10390 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10391 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10394 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10396 // Make sure the lower and upper halves are both all-ones.
10397 static const int Mask[] = { 1, 0, 3, 2 };
10398 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10399 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10402 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10404 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10408 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10409 // bits of the inputs before performing those operations.
10411 EVT EltVT = VT.getVectorElementType();
10412 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10413 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10414 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10417 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10419 // If the logical-not of the result is required, perform that now.
10421 Result = DAG.getNOT(dl, Result, VT);
10424 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10427 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10428 getZeroVector(VT, Subtarget, DAG, dl));
10433 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10435 MVT VT = Op.getSimpleValueType();
10437 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10439 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10440 && "SetCC type must be 8-bit or 1-bit integer");
10441 SDValue Op0 = Op.getOperand(0);
10442 SDValue Op1 = Op.getOperand(1);
10444 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10446 // Optimize to BT if possible.
10447 // Lower (X & (1 << N)) == 0 to BT(X, N).
10448 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10449 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10450 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10451 Op1.getOpcode() == ISD::Constant &&
10452 cast<ConstantSDNode>(Op1)->isNullValue() &&
10453 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10454 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10455 if (NewSetCC.getNode())
10459 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10461 if (Op1.getOpcode() == ISD::Constant &&
10462 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10463 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10464 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10466 // If the input is a setcc, then reuse the input setcc or use a new one with
10467 // the inverted condition.
10468 if (Op0.getOpcode() == X86ISD::SETCC) {
10469 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10470 bool Invert = (CC == ISD::SETNE) ^
10471 cast<ConstantSDNode>(Op1)->isNullValue();
10475 CCode = X86::GetOppositeBranchCondition(CCode);
10476 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10477 DAG.getConstant(CCode, MVT::i8),
10478 Op0.getOperand(1));
10480 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10484 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10485 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10486 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10488 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10489 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10492 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10493 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10494 if (X86CC == X86::COND_INVALID)
10497 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10498 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10499 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10500 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10502 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10506 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10507 static bool isX86LogicalCmp(SDValue Op) {
10508 unsigned Opc = Op.getNode()->getOpcode();
10509 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10510 Opc == X86ISD::SAHF)
10512 if (Op.getResNo() == 1 &&
10513 (Opc == X86ISD::ADD ||
10514 Opc == X86ISD::SUB ||
10515 Opc == X86ISD::ADC ||
10516 Opc == X86ISD::SBB ||
10517 Opc == X86ISD::SMUL ||
10518 Opc == X86ISD::UMUL ||
10519 Opc == X86ISD::INC ||
10520 Opc == X86ISD::DEC ||
10521 Opc == X86ISD::OR ||
10522 Opc == X86ISD::XOR ||
10523 Opc == X86ISD::AND))
10526 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10532 static bool isZero(SDValue V) {
10533 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10534 return C && C->isNullValue();
10537 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10538 if (V.getOpcode() != ISD::TRUNCATE)
10541 SDValue VOp0 = V.getOperand(0);
10542 unsigned InBits = VOp0.getValueSizeInBits();
10543 unsigned Bits = V.getValueSizeInBits();
10544 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10547 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10548 bool addTest = true;
10549 SDValue Cond = Op.getOperand(0);
10550 SDValue Op1 = Op.getOperand(1);
10551 SDValue Op2 = Op.getOperand(2);
10553 EVT VT = Op1.getValueType();
10556 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10557 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10558 // sequence later on.
10559 if (Cond.getOpcode() == ISD::SETCC &&
10560 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10561 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10562 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10563 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10564 int SSECC = translateX86FSETCC(
10565 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10568 if (Subtarget->hasAVX512()) {
10569 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10570 DAG.getConstant(SSECC, MVT::i8));
10571 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10573 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10574 DAG.getConstant(SSECC, MVT::i8));
10575 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10576 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10577 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10581 if (Cond.getOpcode() == ISD::SETCC) {
10582 SDValue NewCond = LowerSETCC(Cond, DAG);
10583 if (NewCond.getNode())
10587 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10588 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10589 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10590 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10591 if (Cond.getOpcode() == X86ISD::SETCC &&
10592 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10593 isZero(Cond.getOperand(1).getOperand(1))) {
10594 SDValue Cmp = Cond.getOperand(1);
10596 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10598 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10599 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10600 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10602 SDValue CmpOp0 = Cmp.getOperand(0);
10603 // Apply further optimizations for special cases
10604 // (select (x != 0), -1, 0) -> neg & sbb
10605 // (select (x == 0), 0, -1) -> neg & sbb
10606 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10607 if (YC->isNullValue() &&
10608 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10609 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10610 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10611 DAG.getConstant(0, CmpOp0.getValueType()),
10613 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10614 DAG.getConstant(X86::COND_B, MVT::i8),
10615 SDValue(Neg.getNode(), 1));
10619 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10620 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10621 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10623 SDValue Res = // Res = 0 or -1.
10624 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10625 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10627 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10628 Res = DAG.getNOT(DL, Res, Res.getValueType());
10630 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10631 if (N2C == 0 || !N2C->isNullValue())
10632 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10637 // Look past (and (setcc_carry (cmp ...)), 1).
10638 if (Cond.getOpcode() == ISD::AND &&
10639 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10640 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10641 if (C && C->getAPIntValue() == 1)
10642 Cond = Cond.getOperand(0);
10645 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10646 // setting operand in place of the X86ISD::SETCC.
10647 unsigned CondOpcode = Cond.getOpcode();
10648 if (CondOpcode == X86ISD::SETCC ||
10649 CondOpcode == X86ISD::SETCC_CARRY) {
10650 CC = Cond.getOperand(0);
10652 SDValue Cmp = Cond.getOperand(1);
10653 unsigned Opc = Cmp.getOpcode();
10654 MVT VT = Op.getSimpleValueType();
10656 bool IllegalFPCMov = false;
10657 if (VT.isFloatingPoint() && !VT.isVector() &&
10658 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10659 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10661 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10662 Opc == X86ISD::BT) { // FIXME
10666 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10667 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10668 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10669 Cond.getOperand(0).getValueType() != MVT::i8)) {
10670 SDValue LHS = Cond.getOperand(0);
10671 SDValue RHS = Cond.getOperand(1);
10672 unsigned X86Opcode;
10675 switch (CondOpcode) {
10676 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10677 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10678 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10679 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10680 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10681 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10682 default: llvm_unreachable("unexpected overflowing operator");
10684 if (CondOpcode == ISD::UMULO)
10685 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10688 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10690 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10692 if (CondOpcode == ISD::UMULO)
10693 Cond = X86Op.getValue(2);
10695 Cond = X86Op.getValue(1);
10697 CC = DAG.getConstant(X86Cond, MVT::i8);
10702 // Look pass the truncate if the high bits are known zero.
10703 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10704 Cond = Cond.getOperand(0);
10706 // We know the result of AND is compared against zero. Try to match
10708 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10709 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10710 if (NewSetCC.getNode()) {
10711 CC = NewSetCC.getOperand(0);
10712 Cond = NewSetCC.getOperand(1);
10719 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10720 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10723 // a < b ? -1 : 0 -> RES = ~setcc_carry
10724 // a < b ? 0 : -1 -> RES = setcc_carry
10725 // a >= b ? -1 : 0 -> RES = setcc_carry
10726 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10727 if (Cond.getOpcode() == X86ISD::SUB) {
10728 Cond = ConvertCmpIfNecessary(Cond, DAG);
10729 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10731 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10732 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10733 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10734 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10735 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10736 return DAG.getNOT(DL, Res, Res.getValueType());
10741 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10742 // widen the cmov and push the truncate through. This avoids introducing a new
10743 // branch during isel and doesn't add any extensions.
10744 if (Op.getValueType() == MVT::i8 &&
10745 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10746 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10747 if (T1.getValueType() == T2.getValueType() &&
10748 // Blacklist CopyFromReg to avoid partial register stalls.
10749 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10750 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10751 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10752 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10756 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10757 // condition is true.
10758 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10759 SDValue Ops[] = { Op2, Op1, CC, Cond };
10760 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10763 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10764 MVT VT = Op->getSimpleValueType(0);
10765 SDValue In = Op->getOperand(0);
10766 MVT InVT = In.getSimpleValueType();
10769 unsigned int NumElts = VT.getVectorNumElements();
10770 if (NumElts != 8 && NumElts != 16)
10773 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10774 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10776 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10777 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10779 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10780 Constant *C = ConstantInt::get(*DAG.getContext(),
10781 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10783 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10784 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10785 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10786 MachinePointerInfo::getConstantPool(),
10787 false, false, false, Alignment);
10788 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10789 if (VT.is512BitVector())
10791 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10794 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10795 SelectionDAG &DAG) {
10796 MVT VT = Op->getSimpleValueType(0);
10797 SDValue In = Op->getOperand(0);
10798 MVT InVT = In.getSimpleValueType();
10801 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10802 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10804 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10805 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10806 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10809 if (Subtarget->hasInt256())
10810 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10812 // Optimize vectors in AVX mode
10813 // Sign extend v8i16 to v8i32 and
10816 // Divide input vector into two parts
10817 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10818 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10819 // concat the vectors to original VT
10821 unsigned NumElems = InVT.getVectorNumElements();
10822 SDValue Undef = DAG.getUNDEF(InVT);
10824 SmallVector<int,8> ShufMask1(NumElems, -1);
10825 for (unsigned i = 0; i != NumElems/2; ++i)
10828 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10830 SmallVector<int,8> ShufMask2(NumElems, -1);
10831 for (unsigned i = 0; i != NumElems/2; ++i)
10832 ShufMask2[i] = i + NumElems/2;
10834 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10836 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10837 VT.getVectorNumElements()/2);
10839 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10840 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10842 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10845 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10846 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10847 // from the AND / OR.
10848 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10849 Opc = Op.getOpcode();
10850 if (Opc != ISD::OR && Opc != ISD::AND)
10852 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10853 Op.getOperand(0).hasOneUse() &&
10854 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10855 Op.getOperand(1).hasOneUse());
10858 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10859 // 1 and that the SETCC node has a single use.
10860 static bool isXor1OfSetCC(SDValue Op) {
10861 if (Op.getOpcode() != ISD::XOR)
10863 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10864 if (N1C && N1C->getAPIntValue() == 1) {
10865 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10866 Op.getOperand(0).hasOneUse();
10871 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10872 bool addTest = true;
10873 SDValue Chain = Op.getOperand(0);
10874 SDValue Cond = Op.getOperand(1);
10875 SDValue Dest = Op.getOperand(2);
10878 bool Inverted = false;
10880 if (Cond.getOpcode() == ISD::SETCC) {
10881 // Check for setcc([su]{add,sub,mul}o == 0).
10882 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10883 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10884 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10885 Cond.getOperand(0).getResNo() == 1 &&
10886 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10887 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10888 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10889 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10890 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10891 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10893 Cond = Cond.getOperand(0);
10895 SDValue NewCond = LowerSETCC(Cond, DAG);
10896 if (NewCond.getNode())
10901 // FIXME: LowerXALUO doesn't handle these!!
10902 else if (Cond.getOpcode() == X86ISD::ADD ||
10903 Cond.getOpcode() == X86ISD::SUB ||
10904 Cond.getOpcode() == X86ISD::SMUL ||
10905 Cond.getOpcode() == X86ISD::UMUL)
10906 Cond = LowerXALUO(Cond, DAG);
10909 // Look pass (and (setcc_carry (cmp ...)), 1).
10910 if (Cond.getOpcode() == ISD::AND &&
10911 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10912 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10913 if (C && C->getAPIntValue() == 1)
10914 Cond = Cond.getOperand(0);
10917 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10918 // setting operand in place of the X86ISD::SETCC.
10919 unsigned CondOpcode = Cond.getOpcode();
10920 if (CondOpcode == X86ISD::SETCC ||
10921 CondOpcode == X86ISD::SETCC_CARRY) {
10922 CC = Cond.getOperand(0);
10924 SDValue Cmp = Cond.getOperand(1);
10925 unsigned Opc = Cmp.getOpcode();
10926 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10927 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10931 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10935 // These can only come from an arithmetic instruction with overflow,
10936 // e.g. SADDO, UADDO.
10937 Cond = Cond.getNode()->getOperand(1);
10943 CondOpcode = Cond.getOpcode();
10944 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10945 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10946 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10947 Cond.getOperand(0).getValueType() != MVT::i8)) {
10948 SDValue LHS = Cond.getOperand(0);
10949 SDValue RHS = Cond.getOperand(1);
10950 unsigned X86Opcode;
10953 // Keep this in sync with LowerXALUO, otherwise we might create redundant
10954 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10956 switch (CondOpcode) {
10957 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10959 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10961 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10964 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10965 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10967 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10969 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10972 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10973 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10974 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10975 default: llvm_unreachable("unexpected overflowing operator");
10978 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10979 if (CondOpcode == ISD::UMULO)
10980 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10983 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10985 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10987 if (CondOpcode == ISD::UMULO)
10988 Cond = X86Op.getValue(2);
10990 Cond = X86Op.getValue(1);
10992 CC = DAG.getConstant(X86Cond, MVT::i8);
10996 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10997 SDValue Cmp = Cond.getOperand(0).getOperand(1);
10998 if (CondOpc == ISD::OR) {
10999 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11000 // two branches instead of an explicit OR instruction with a
11002 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11003 isX86LogicalCmp(Cmp)) {
11004 CC = Cond.getOperand(0).getOperand(0);
11005 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11006 Chain, Dest, CC, Cmp);
11007 CC = Cond.getOperand(1).getOperand(0);
11011 } else { // ISD::AND
11012 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11013 // two branches instead of an explicit AND instruction with a
11014 // separate test. However, we only do this if this block doesn't
11015 // have a fall-through edge, because this requires an explicit
11016 // jmp when the condition is false.
11017 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11018 isX86LogicalCmp(Cmp) &&
11019 Op.getNode()->hasOneUse()) {
11020 X86::CondCode CCode =
11021 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11022 CCode = X86::GetOppositeBranchCondition(CCode);
11023 CC = DAG.getConstant(CCode, MVT::i8);
11024 SDNode *User = *Op.getNode()->use_begin();
11025 // Look for an unconditional branch following this conditional branch.
11026 // We need this because we need to reverse the successors in order
11027 // to implement FCMP_OEQ.
11028 if (User->getOpcode() == ISD::BR) {
11029 SDValue FalseBB = User->getOperand(1);
11031 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11032 assert(NewBR == User);
11036 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11037 Chain, Dest, CC, Cmp);
11038 X86::CondCode CCode =
11039 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11040 CCode = X86::GetOppositeBranchCondition(CCode);
11041 CC = DAG.getConstant(CCode, MVT::i8);
11047 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11048 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11049 // It should be transformed during dag combiner except when the condition
11050 // is set by a arithmetics with overflow node.
11051 X86::CondCode CCode =
11052 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11053 CCode = X86::GetOppositeBranchCondition(CCode);
11054 CC = DAG.getConstant(CCode, MVT::i8);
11055 Cond = Cond.getOperand(0).getOperand(1);
11057 } else if (Cond.getOpcode() == ISD::SETCC &&
11058 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11059 // For FCMP_OEQ, we can emit
11060 // two branches instead of an explicit AND instruction with a
11061 // separate test. However, we only do this if this block doesn't
11062 // have a fall-through edge, because this requires an explicit
11063 // jmp when the condition is false.
11064 if (Op.getNode()->hasOneUse()) {
11065 SDNode *User = *Op.getNode()->use_begin();
11066 // Look for an unconditional branch following this conditional branch.
11067 // We need this because we need to reverse the successors in order
11068 // to implement FCMP_OEQ.
11069 if (User->getOpcode() == ISD::BR) {
11070 SDValue FalseBB = User->getOperand(1);
11072 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11073 assert(NewBR == User);
11077 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11078 Cond.getOperand(0), Cond.getOperand(1));
11079 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11080 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11081 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11082 Chain, Dest, CC, Cmp);
11083 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11088 } else if (Cond.getOpcode() == ISD::SETCC &&
11089 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11090 // For FCMP_UNE, we can emit
11091 // two branches instead of an explicit AND instruction with a
11092 // separate test. However, we only do this if this block doesn't
11093 // have a fall-through edge, because this requires an explicit
11094 // jmp when the condition is false.
11095 if (Op.getNode()->hasOneUse()) {
11096 SDNode *User = *Op.getNode()->use_begin();
11097 // Look for an unconditional branch following this conditional branch.
11098 // We need this because we need to reverse the successors in order
11099 // to implement FCMP_UNE.
11100 if (User->getOpcode() == ISD::BR) {
11101 SDValue FalseBB = User->getOperand(1);
11103 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11104 assert(NewBR == User);
11107 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11108 Cond.getOperand(0), Cond.getOperand(1));
11109 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11110 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11111 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11112 Chain, Dest, CC, Cmp);
11113 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11123 // Look pass the truncate if the high bits are known zero.
11124 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11125 Cond = Cond.getOperand(0);
11127 // We know the result of AND is compared against zero. Try to match
11129 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11130 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11131 if (NewSetCC.getNode()) {
11132 CC = NewSetCC.getOperand(0);
11133 Cond = NewSetCC.getOperand(1);
11140 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11141 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11143 Cond = ConvertCmpIfNecessary(Cond, DAG);
11144 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11145 Chain, Dest, CC, Cond);
11148 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11149 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11150 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11151 // that the guard pages used by the OS virtual memory manager are allocated in
11152 // correct sequence.
11154 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11155 SelectionDAG &DAG) const {
11156 MachineFunction &MF = DAG.getMachineFunction();
11157 bool SplitStack = MF.shouldSplitStack();
11158 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11163 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11164 SDNode* Node = Op.getNode();
11166 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11167 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11168 " not tell us which reg is the stack pointer!");
11169 EVT VT = Node->getValueType(0);
11170 SDValue Tmp1 = SDValue(Node, 0);
11171 SDValue Tmp2 = SDValue(Node, 1);
11172 SDValue Tmp3 = Node->getOperand(2);
11173 SDValue Chain = Tmp1.getOperand(0);
11175 // Chain the dynamic stack allocation so that it doesn't modify the stack
11176 // pointer when other instructions are using the stack.
11177 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11180 SDValue Size = Tmp2.getOperand(1);
11181 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11182 Chain = SP.getValue(1);
11183 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11184 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11185 unsigned StackAlign = TFI.getStackAlignment();
11186 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11187 if (Align > StackAlign)
11188 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11189 DAG.getConstant(-(uint64_t)Align, VT));
11190 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11192 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11193 DAG.getIntPtrConstant(0, true), SDValue(),
11196 SDValue Ops[2] = { Tmp1, Tmp2 };
11197 return DAG.getMergeValues(Ops, 2, dl);
11201 SDValue Chain = Op.getOperand(0);
11202 SDValue Size = Op.getOperand(1);
11203 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11204 EVT VT = Op.getNode()->getValueType(0);
11206 bool Is64Bit = Subtarget->is64Bit();
11207 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11210 MachineRegisterInfo &MRI = MF.getRegInfo();
11213 // The 64 bit implementation of segmented stacks needs to clobber both r10
11214 // r11. This makes it impossible to use it along with nested parameters.
11215 const Function *F = MF.getFunction();
11217 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11219 if (I->hasNestAttr())
11220 report_fatal_error("Cannot use segmented stacks with functions that "
11221 "have nested arguments.");
11224 const TargetRegisterClass *AddrRegClass =
11225 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11226 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11227 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11228 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11229 DAG.getRegister(Vreg, SPTy));
11230 SDValue Ops1[2] = { Value, Chain };
11231 return DAG.getMergeValues(Ops1, 2, dl);
11234 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11236 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11237 Flag = Chain.getValue(1);
11238 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11240 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11242 const X86RegisterInfo *RegInfo =
11243 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11244 unsigned SPReg = RegInfo->getStackRegister();
11245 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11246 Chain = SP.getValue(1);
11249 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11250 DAG.getConstant(-(uint64_t)Align, VT));
11251 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11254 SDValue Ops1[2] = { SP, Chain };
11255 return DAG.getMergeValues(Ops1, 2, dl);
11259 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11260 MachineFunction &MF = DAG.getMachineFunction();
11261 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11263 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11266 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11267 // vastart just stores the address of the VarArgsFrameIndex slot into the
11268 // memory location argument.
11269 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11271 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11272 MachinePointerInfo(SV), false, false, 0);
11276 // gp_offset (0 - 6 * 8)
11277 // fp_offset (48 - 48 + 8 * 16)
11278 // overflow_arg_area (point to parameters coming in memory).
11280 SmallVector<SDValue, 8> MemOps;
11281 SDValue FIN = Op.getOperand(1);
11283 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11284 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11286 FIN, MachinePointerInfo(SV), false, false, 0);
11287 MemOps.push_back(Store);
11290 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11291 FIN, DAG.getIntPtrConstant(4));
11292 Store = DAG.getStore(Op.getOperand(0), DL,
11293 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11295 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11296 MemOps.push_back(Store);
11298 // Store ptr to overflow_arg_area
11299 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11300 FIN, DAG.getIntPtrConstant(4));
11301 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11303 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11304 MachinePointerInfo(SV, 8),
11306 MemOps.push_back(Store);
11308 // Store ptr to reg_save_area.
11309 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11310 FIN, DAG.getIntPtrConstant(8));
11311 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11313 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11314 MachinePointerInfo(SV, 16), false, false, 0);
11315 MemOps.push_back(Store);
11316 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11317 &MemOps[0], MemOps.size());
11320 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11321 assert(Subtarget->is64Bit() &&
11322 "LowerVAARG only handles 64-bit va_arg!");
11323 assert((Subtarget->isTargetLinux() ||
11324 Subtarget->isTargetDarwin()) &&
11325 "Unhandled target in LowerVAARG");
11326 assert(Op.getNode()->getNumOperands() == 4);
11327 SDValue Chain = Op.getOperand(0);
11328 SDValue SrcPtr = Op.getOperand(1);
11329 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11330 unsigned Align = Op.getConstantOperandVal(3);
11333 EVT ArgVT = Op.getNode()->getValueType(0);
11334 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11335 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11338 // Decide which area this value should be read from.
11339 // TODO: Implement the AMD64 ABI in its entirety. This simple
11340 // selection mechanism works only for the basic types.
11341 if (ArgVT == MVT::f80) {
11342 llvm_unreachable("va_arg for f80 not yet implemented");
11343 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11344 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11345 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11346 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11348 llvm_unreachable("Unhandled argument type in LowerVAARG");
11351 if (ArgMode == 2) {
11352 // Sanity Check: Make sure using fp_offset makes sense.
11353 assert(!getTargetMachine().Options.UseSoftFloat &&
11354 !(DAG.getMachineFunction()
11355 .getFunction()->getAttributes()
11356 .hasAttribute(AttributeSet::FunctionIndex,
11357 Attribute::NoImplicitFloat)) &&
11358 Subtarget->hasSSE1());
11361 // Insert VAARG_64 node into the DAG
11362 // VAARG_64 returns two values: Variable Argument Address, Chain
11363 SmallVector<SDValue, 11> InstOps;
11364 InstOps.push_back(Chain);
11365 InstOps.push_back(SrcPtr);
11366 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11367 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11368 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11369 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11370 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11371 VTs, &InstOps[0], InstOps.size(),
11373 MachinePointerInfo(SV),
11375 /*Volatile=*/false,
11377 /*WriteMem=*/true);
11378 Chain = VAARG.getValue(1);
11380 // Load the next argument and return it
11381 return DAG.getLoad(ArgVT, dl,
11384 MachinePointerInfo(),
11385 false, false, false, 0);
11388 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11389 SelectionDAG &DAG) {
11390 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11391 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11392 SDValue Chain = Op.getOperand(0);
11393 SDValue DstPtr = Op.getOperand(1);
11394 SDValue SrcPtr = Op.getOperand(2);
11395 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11396 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11399 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11400 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11402 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11405 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11406 // amount is a constant. Takes immediate version of shift as input.
11407 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11408 SDValue SrcOp, uint64_t ShiftAmt,
11409 SelectionDAG &DAG) {
11410 MVT ElementType = VT.getVectorElementType();
11412 // Check for ShiftAmt >= element width
11413 if (ShiftAmt >= ElementType.getSizeInBits()) {
11414 if (Opc == X86ISD::VSRAI)
11415 ShiftAmt = ElementType.getSizeInBits() - 1;
11417 return DAG.getConstant(0, VT);
11420 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11421 && "Unknown target vector shift-by-constant node");
11423 // Fold this packed vector shift into a build vector if SrcOp is a
11424 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11425 if (VT == SrcOp.getSimpleValueType() &&
11426 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11427 SmallVector<SDValue, 8> Elts;
11428 unsigned NumElts = SrcOp->getNumOperands();
11429 ConstantSDNode *ND;
11432 default: llvm_unreachable(0);
11433 case X86ISD::VSHLI:
11434 for (unsigned i=0; i!=NumElts; ++i) {
11435 SDValue CurrentOp = SrcOp->getOperand(i);
11436 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11437 Elts.push_back(CurrentOp);
11440 ND = cast<ConstantSDNode>(CurrentOp);
11441 const APInt &C = ND->getAPIntValue();
11442 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11445 case X86ISD::VSRLI:
11446 for (unsigned i=0; i!=NumElts; ++i) {
11447 SDValue CurrentOp = SrcOp->getOperand(i);
11448 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11449 Elts.push_back(CurrentOp);
11452 ND = cast<ConstantSDNode>(CurrentOp);
11453 const APInt &C = ND->getAPIntValue();
11454 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11457 case X86ISD::VSRAI:
11458 for (unsigned i=0; i!=NumElts; ++i) {
11459 SDValue CurrentOp = SrcOp->getOperand(i);
11460 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11461 Elts.push_back(CurrentOp);
11464 ND = cast<ConstantSDNode>(CurrentOp);
11465 const APInt &C = ND->getAPIntValue();
11466 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11471 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11474 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11477 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11478 // may or may not be a constant. Takes immediate version of shift as input.
11479 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11480 SDValue SrcOp, SDValue ShAmt,
11481 SelectionDAG &DAG) {
11482 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11484 // Catch shift-by-constant.
11485 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11486 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11487 CShAmt->getZExtValue(), DAG);
11489 // Change opcode to non-immediate version
11491 default: llvm_unreachable("Unknown target vector shift node");
11492 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11493 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11494 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11497 // Need to build a vector containing shift amount
11498 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11501 ShOps[1] = DAG.getConstant(0, MVT::i32);
11502 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11503 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11505 // The return type has to be a 128-bit type with the same element
11506 // type as the input type.
11507 MVT EltVT = VT.getVectorElementType();
11508 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11510 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11511 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11514 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11516 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11518 default: return SDValue(); // Don't custom lower most intrinsics.
11519 // Comparison intrinsics.
11520 case Intrinsic::x86_sse_comieq_ss:
11521 case Intrinsic::x86_sse_comilt_ss:
11522 case Intrinsic::x86_sse_comile_ss:
11523 case Intrinsic::x86_sse_comigt_ss:
11524 case Intrinsic::x86_sse_comige_ss:
11525 case Intrinsic::x86_sse_comineq_ss:
11526 case Intrinsic::x86_sse_ucomieq_ss:
11527 case Intrinsic::x86_sse_ucomilt_ss:
11528 case Intrinsic::x86_sse_ucomile_ss:
11529 case Intrinsic::x86_sse_ucomigt_ss:
11530 case Intrinsic::x86_sse_ucomige_ss:
11531 case Intrinsic::x86_sse_ucomineq_ss:
11532 case Intrinsic::x86_sse2_comieq_sd:
11533 case Intrinsic::x86_sse2_comilt_sd:
11534 case Intrinsic::x86_sse2_comile_sd:
11535 case Intrinsic::x86_sse2_comigt_sd:
11536 case Intrinsic::x86_sse2_comige_sd:
11537 case Intrinsic::x86_sse2_comineq_sd:
11538 case Intrinsic::x86_sse2_ucomieq_sd:
11539 case Intrinsic::x86_sse2_ucomilt_sd:
11540 case Intrinsic::x86_sse2_ucomile_sd:
11541 case Intrinsic::x86_sse2_ucomigt_sd:
11542 case Intrinsic::x86_sse2_ucomige_sd:
11543 case Intrinsic::x86_sse2_ucomineq_sd: {
11547 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11548 case Intrinsic::x86_sse_comieq_ss:
11549 case Intrinsic::x86_sse2_comieq_sd:
11550 Opc = X86ISD::COMI;
11553 case Intrinsic::x86_sse_comilt_ss:
11554 case Intrinsic::x86_sse2_comilt_sd:
11555 Opc = X86ISD::COMI;
11558 case Intrinsic::x86_sse_comile_ss:
11559 case Intrinsic::x86_sse2_comile_sd:
11560 Opc = X86ISD::COMI;
11563 case Intrinsic::x86_sse_comigt_ss:
11564 case Intrinsic::x86_sse2_comigt_sd:
11565 Opc = X86ISD::COMI;
11568 case Intrinsic::x86_sse_comige_ss:
11569 case Intrinsic::x86_sse2_comige_sd:
11570 Opc = X86ISD::COMI;
11573 case Intrinsic::x86_sse_comineq_ss:
11574 case Intrinsic::x86_sse2_comineq_sd:
11575 Opc = X86ISD::COMI;
11578 case Intrinsic::x86_sse_ucomieq_ss:
11579 case Intrinsic::x86_sse2_ucomieq_sd:
11580 Opc = X86ISD::UCOMI;
11583 case Intrinsic::x86_sse_ucomilt_ss:
11584 case Intrinsic::x86_sse2_ucomilt_sd:
11585 Opc = X86ISD::UCOMI;
11588 case Intrinsic::x86_sse_ucomile_ss:
11589 case Intrinsic::x86_sse2_ucomile_sd:
11590 Opc = X86ISD::UCOMI;
11593 case Intrinsic::x86_sse_ucomigt_ss:
11594 case Intrinsic::x86_sse2_ucomigt_sd:
11595 Opc = X86ISD::UCOMI;
11598 case Intrinsic::x86_sse_ucomige_ss:
11599 case Intrinsic::x86_sse2_ucomige_sd:
11600 Opc = X86ISD::UCOMI;
11603 case Intrinsic::x86_sse_ucomineq_ss:
11604 case Intrinsic::x86_sse2_ucomineq_sd:
11605 Opc = X86ISD::UCOMI;
11610 SDValue LHS = Op.getOperand(1);
11611 SDValue RHS = Op.getOperand(2);
11612 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11613 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11614 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11615 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11616 DAG.getConstant(X86CC, MVT::i8), Cond);
11617 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11620 // Arithmetic intrinsics.
11621 case Intrinsic::x86_sse2_pmulu_dq:
11622 case Intrinsic::x86_avx2_pmulu_dq:
11623 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11624 Op.getOperand(1), Op.getOperand(2));
11626 // SSE2/AVX2 sub with unsigned saturation intrinsics
11627 case Intrinsic::x86_sse2_psubus_b:
11628 case Intrinsic::x86_sse2_psubus_w:
11629 case Intrinsic::x86_avx2_psubus_b:
11630 case Intrinsic::x86_avx2_psubus_w:
11631 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11632 Op.getOperand(1), Op.getOperand(2));
11634 // SSE3/AVX horizontal add/sub intrinsics
11635 case Intrinsic::x86_sse3_hadd_ps:
11636 case Intrinsic::x86_sse3_hadd_pd:
11637 case Intrinsic::x86_avx_hadd_ps_256:
11638 case Intrinsic::x86_avx_hadd_pd_256:
11639 case Intrinsic::x86_sse3_hsub_ps:
11640 case Intrinsic::x86_sse3_hsub_pd:
11641 case Intrinsic::x86_avx_hsub_ps_256:
11642 case Intrinsic::x86_avx_hsub_pd_256:
11643 case Intrinsic::x86_ssse3_phadd_w_128:
11644 case Intrinsic::x86_ssse3_phadd_d_128:
11645 case Intrinsic::x86_avx2_phadd_w:
11646 case Intrinsic::x86_avx2_phadd_d:
11647 case Intrinsic::x86_ssse3_phsub_w_128:
11648 case Intrinsic::x86_ssse3_phsub_d_128:
11649 case Intrinsic::x86_avx2_phsub_w:
11650 case Intrinsic::x86_avx2_phsub_d: {
11653 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11654 case Intrinsic::x86_sse3_hadd_ps:
11655 case Intrinsic::x86_sse3_hadd_pd:
11656 case Intrinsic::x86_avx_hadd_ps_256:
11657 case Intrinsic::x86_avx_hadd_pd_256:
11658 Opcode = X86ISD::FHADD;
11660 case Intrinsic::x86_sse3_hsub_ps:
11661 case Intrinsic::x86_sse3_hsub_pd:
11662 case Intrinsic::x86_avx_hsub_ps_256:
11663 case Intrinsic::x86_avx_hsub_pd_256:
11664 Opcode = X86ISD::FHSUB;
11666 case Intrinsic::x86_ssse3_phadd_w_128:
11667 case Intrinsic::x86_ssse3_phadd_d_128:
11668 case Intrinsic::x86_avx2_phadd_w:
11669 case Intrinsic::x86_avx2_phadd_d:
11670 Opcode = X86ISD::HADD;
11672 case Intrinsic::x86_ssse3_phsub_w_128:
11673 case Intrinsic::x86_ssse3_phsub_d_128:
11674 case Intrinsic::x86_avx2_phsub_w:
11675 case Intrinsic::x86_avx2_phsub_d:
11676 Opcode = X86ISD::HSUB;
11679 return DAG.getNode(Opcode, dl, Op.getValueType(),
11680 Op.getOperand(1), Op.getOperand(2));
11683 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11684 case Intrinsic::x86_sse2_pmaxu_b:
11685 case Intrinsic::x86_sse41_pmaxuw:
11686 case Intrinsic::x86_sse41_pmaxud:
11687 case Intrinsic::x86_avx2_pmaxu_b:
11688 case Intrinsic::x86_avx2_pmaxu_w:
11689 case Intrinsic::x86_avx2_pmaxu_d:
11690 case Intrinsic::x86_sse2_pminu_b:
11691 case Intrinsic::x86_sse41_pminuw:
11692 case Intrinsic::x86_sse41_pminud:
11693 case Intrinsic::x86_avx2_pminu_b:
11694 case Intrinsic::x86_avx2_pminu_w:
11695 case Intrinsic::x86_avx2_pminu_d:
11696 case Intrinsic::x86_sse41_pmaxsb:
11697 case Intrinsic::x86_sse2_pmaxs_w:
11698 case Intrinsic::x86_sse41_pmaxsd:
11699 case Intrinsic::x86_avx2_pmaxs_b:
11700 case Intrinsic::x86_avx2_pmaxs_w:
11701 case Intrinsic::x86_avx2_pmaxs_d:
11702 case Intrinsic::x86_sse41_pminsb:
11703 case Intrinsic::x86_sse2_pmins_w:
11704 case Intrinsic::x86_sse41_pminsd:
11705 case Intrinsic::x86_avx2_pmins_b:
11706 case Intrinsic::x86_avx2_pmins_w:
11707 case Intrinsic::x86_avx2_pmins_d: {
11710 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11711 case Intrinsic::x86_sse2_pmaxu_b:
11712 case Intrinsic::x86_sse41_pmaxuw:
11713 case Intrinsic::x86_sse41_pmaxud:
11714 case Intrinsic::x86_avx2_pmaxu_b:
11715 case Intrinsic::x86_avx2_pmaxu_w:
11716 case Intrinsic::x86_avx2_pmaxu_d:
11717 Opcode = X86ISD::UMAX;
11719 case Intrinsic::x86_sse2_pminu_b:
11720 case Intrinsic::x86_sse41_pminuw:
11721 case Intrinsic::x86_sse41_pminud:
11722 case Intrinsic::x86_avx2_pminu_b:
11723 case Intrinsic::x86_avx2_pminu_w:
11724 case Intrinsic::x86_avx2_pminu_d:
11725 Opcode = X86ISD::UMIN;
11727 case Intrinsic::x86_sse41_pmaxsb:
11728 case Intrinsic::x86_sse2_pmaxs_w:
11729 case Intrinsic::x86_sse41_pmaxsd:
11730 case Intrinsic::x86_avx2_pmaxs_b:
11731 case Intrinsic::x86_avx2_pmaxs_w:
11732 case Intrinsic::x86_avx2_pmaxs_d:
11733 Opcode = X86ISD::SMAX;
11735 case Intrinsic::x86_sse41_pminsb:
11736 case Intrinsic::x86_sse2_pmins_w:
11737 case Intrinsic::x86_sse41_pminsd:
11738 case Intrinsic::x86_avx2_pmins_b:
11739 case Intrinsic::x86_avx2_pmins_w:
11740 case Intrinsic::x86_avx2_pmins_d:
11741 Opcode = X86ISD::SMIN;
11744 return DAG.getNode(Opcode, dl, Op.getValueType(),
11745 Op.getOperand(1), Op.getOperand(2));
11748 // SSE/SSE2/AVX floating point max/min intrinsics.
11749 case Intrinsic::x86_sse_max_ps:
11750 case Intrinsic::x86_sse2_max_pd:
11751 case Intrinsic::x86_avx_max_ps_256:
11752 case Intrinsic::x86_avx_max_pd_256:
11753 case Intrinsic::x86_sse_min_ps:
11754 case Intrinsic::x86_sse2_min_pd:
11755 case Intrinsic::x86_avx_min_ps_256:
11756 case Intrinsic::x86_avx_min_pd_256: {
11759 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11760 case Intrinsic::x86_sse_max_ps:
11761 case Intrinsic::x86_sse2_max_pd:
11762 case Intrinsic::x86_avx_max_ps_256:
11763 case Intrinsic::x86_avx_max_pd_256:
11764 Opcode = X86ISD::FMAX;
11766 case Intrinsic::x86_sse_min_ps:
11767 case Intrinsic::x86_sse2_min_pd:
11768 case Intrinsic::x86_avx_min_ps_256:
11769 case Intrinsic::x86_avx_min_pd_256:
11770 Opcode = X86ISD::FMIN;
11773 return DAG.getNode(Opcode, dl, Op.getValueType(),
11774 Op.getOperand(1), Op.getOperand(2));
11777 // AVX2 variable shift intrinsics
11778 case Intrinsic::x86_avx2_psllv_d:
11779 case Intrinsic::x86_avx2_psllv_q:
11780 case Intrinsic::x86_avx2_psllv_d_256:
11781 case Intrinsic::x86_avx2_psllv_q_256:
11782 case Intrinsic::x86_avx2_psrlv_d:
11783 case Intrinsic::x86_avx2_psrlv_q:
11784 case Intrinsic::x86_avx2_psrlv_d_256:
11785 case Intrinsic::x86_avx2_psrlv_q_256:
11786 case Intrinsic::x86_avx2_psrav_d:
11787 case Intrinsic::x86_avx2_psrav_d_256: {
11790 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11791 case Intrinsic::x86_avx2_psllv_d:
11792 case Intrinsic::x86_avx2_psllv_q:
11793 case Intrinsic::x86_avx2_psllv_d_256:
11794 case Intrinsic::x86_avx2_psllv_q_256:
11797 case Intrinsic::x86_avx2_psrlv_d:
11798 case Intrinsic::x86_avx2_psrlv_q:
11799 case Intrinsic::x86_avx2_psrlv_d_256:
11800 case Intrinsic::x86_avx2_psrlv_q_256:
11803 case Intrinsic::x86_avx2_psrav_d:
11804 case Intrinsic::x86_avx2_psrav_d_256:
11808 return DAG.getNode(Opcode, dl, Op.getValueType(),
11809 Op.getOperand(1), Op.getOperand(2));
11812 case Intrinsic::x86_ssse3_pshuf_b_128:
11813 case Intrinsic::x86_avx2_pshuf_b:
11814 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11815 Op.getOperand(1), Op.getOperand(2));
11817 case Intrinsic::x86_ssse3_psign_b_128:
11818 case Intrinsic::x86_ssse3_psign_w_128:
11819 case Intrinsic::x86_ssse3_psign_d_128:
11820 case Intrinsic::x86_avx2_psign_b:
11821 case Intrinsic::x86_avx2_psign_w:
11822 case Intrinsic::x86_avx2_psign_d:
11823 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11824 Op.getOperand(1), Op.getOperand(2));
11826 case Intrinsic::x86_sse41_insertps:
11827 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11828 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11830 case Intrinsic::x86_avx_vperm2f128_ps_256:
11831 case Intrinsic::x86_avx_vperm2f128_pd_256:
11832 case Intrinsic::x86_avx_vperm2f128_si_256:
11833 case Intrinsic::x86_avx2_vperm2i128:
11834 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11835 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11837 case Intrinsic::x86_avx2_permd:
11838 case Intrinsic::x86_avx2_permps:
11839 // Operands intentionally swapped. Mask is last operand to intrinsic,
11840 // but second operand for node/instruction.
11841 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11842 Op.getOperand(2), Op.getOperand(1));
11844 case Intrinsic::x86_sse_sqrt_ps:
11845 case Intrinsic::x86_sse2_sqrt_pd:
11846 case Intrinsic::x86_avx_sqrt_ps_256:
11847 case Intrinsic::x86_avx_sqrt_pd_256:
11848 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11850 // ptest and testp intrinsics. The intrinsic these come from are designed to
11851 // return an integer value, not just an instruction so lower it to the ptest
11852 // or testp pattern and a setcc for the result.
11853 case Intrinsic::x86_sse41_ptestz:
11854 case Intrinsic::x86_sse41_ptestc:
11855 case Intrinsic::x86_sse41_ptestnzc:
11856 case Intrinsic::x86_avx_ptestz_256:
11857 case Intrinsic::x86_avx_ptestc_256:
11858 case Intrinsic::x86_avx_ptestnzc_256:
11859 case Intrinsic::x86_avx_vtestz_ps:
11860 case Intrinsic::x86_avx_vtestc_ps:
11861 case Intrinsic::x86_avx_vtestnzc_ps:
11862 case Intrinsic::x86_avx_vtestz_pd:
11863 case Intrinsic::x86_avx_vtestc_pd:
11864 case Intrinsic::x86_avx_vtestnzc_pd:
11865 case Intrinsic::x86_avx_vtestz_ps_256:
11866 case Intrinsic::x86_avx_vtestc_ps_256:
11867 case Intrinsic::x86_avx_vtestnzc_ps_256:
11868 case Intrinsic::x86_avx_vtestz_pd_256:
11869 case Intrinsic::x86_avx_vtestc_pd_256:
11870 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11871 bool IsTestPacked = false;
11874 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11875 case Intrinsic::x86_avx_vtestz_ps:
11876 case Intrinsic::x86_avx_vtestz_pd:
11877 case Intrinsic::x86_avx_vtestz_ps_256:
11878 case Intrinsic::x86_avx_vtestz_pd_256:
11879 IsTestPacked = true; // Fallthrough
11880 case Intrinsic::x86_sse41_ptestz:
11881 case Intrinsic::x86_avx_ptestz_256:
11883 X86CC = X86::COND_E;
11885 case Intrinsic::x86_avx_vtestc_ps:
11886 case Intrinsic::x86_avx_vtestc_pd:
11887 case Intrinsic::x86_avx_vtestc_ps_256:
11888 case Intrinsic::x86_avx_vtestc_pd_256:
11889 IsTestPacked = true; // Fallthrough
11890 case Intrinsic::x86_sse41_ptestc:
11891 case Intrinsic::x86_avx_ptestc_256:
11893 X86CC = X86::COND_B;
11895 case Intrinsic::x86_avx_vtestnzc_ps:
11896 case Intrinsic::x86_avx_vtestnzc_pd:
11897 case Intrinsic::x86_avx_vtestnzc_ps_256:
11898 case Intrinsic::x86_avx_vtestnzc_pd_256:
11899 IsTestPacked = true; // Fallthrough
11900 case Intrinsic::x86_sse41_ptestnzc:
11901 case Intrinsic::x86_avx_ptestnzc_256:
11903 X86CC = X86::COND_A;
11907 SDValue LHS = Op.getOperand(1);
11908 SDValue RHS = Op.getOperand(2);
11909 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11910 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11911 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11912 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11913 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11915 case Intrinsic::x86_avx512_kortestz_w:
11916 case Intrinsic::x86_avx512_kortestc_w: {
11917 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11918 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11919 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11920 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11921 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11922 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11923 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11926 // SSE/AVX shift intrinsics
11927 case Intrinsic::x86_sse2_psll_w:
11928 case Intrinsic::x86_sse2_psll_d:
11929 case Intrinsic::x86_sse2_psll_q:
11930 case Intrinsic::x86_avx2_psll_w:
11931 case Intrinsic::x86_avx2_psll_d:
11932 case Intrinsic::x86_avx2_psll_q:
11933 case Intrinsic::x86_sse2_psrl_w:
11934 case Intrinsic::x86_sse2_psrl_d:
11935 case Intrinsic::x86_sse2_psrl_q:
11936 case Intrinsic::x86_avx2_psrl_w:
11937 case Intrinsic::x86_avx2_psrl_d:
11938 case Intrinsic::x86_avx2_psrl_q:
11939 case Intrinsic::x86_sse2_psra_w:
11940 case Intrinsic::x86_sse2_psra_d:
11941 case Intrinsic::x86_avx2_psra_w:
11942 case Intrinsic::x86_avx2_psra_d: {
11945 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11946 case Intrinsic::x86_sse2_psll_w:
11947 case Intrinsic::x86_sse2_psll_d:
11948 case Intrinsic::x86_sse2_psll_q:
11949 case Intrinsic::x86_avx2_psll_w:
11950 case Intrinsic::x86_avx2_psll_d:
11951 case Intrinsic::x86_avx2_psll_q:
11952 Opcode = X86ISD::VSHL;
11954 case Intrinsic::x86_sse2_psrl_w:
11955 case Intrinsic::x86_sse2_psrl_d:
11956 case Intrinsic::x86_sse2_psrl_q:
11957 case Intrinsic::x86_avx2_psrl_w:
11958 case Intrinsic::x86_avx2_psrl_d:
11959 case Intrinsic::x86_avx2_psrl_q:
11960 Opcode = X86ISD::VSRL;
11962 case Intrinsic::x86_sse2_psra_w:
11963 case Intrinsic::x86_sse2_psra_d:
11964 case Intrinsic::x86_avx2_psra_w:
11965 case Intrinsic::x86_avx2_psra_d:
11966 Opcode = X86ISD::VSRA;
11969 return DAG.getNode(Opcode, dl, Op.getValueType(),
11970 Op.getOperand(1), Op.getOperand(2));
11973 // SSE/AVX immediate shift intrinsics
11974 case Intrinsic::x86_sse2_pslli_w:
11975 case Intrinsic::x86_sse2_pslli_d:
11976 case Intrinsic::x86_sse2_pslli_q:
11977 case Intrinsic::x86_avx2_pslli_w:
11978 case Intrinsic::x86_avx2_pslli_d:
11979 case Intrinsic::x86_avx2_pslli_q:
11980 case Intrinsic::x86_sse2_psrli_w:
11981 case Intrinsic::x86_sse2_psrli_d:
11982 case Intrinsic::x86_sse2_psrli_q:
11983 case Intrinsic::x86_avx2_psrli_w:
11984 case Intrinsic::x86_avx2_psrli_d:
11985 case Intrinsic::x86_avx2_psrli_q:
11986 case Intrinsic::x86_sse2_psrai_w:
11987 case Intrinsic::x86_sse2_psrai_d:
11988 case Intrinsic::x86_avx2_psrai_w:
11989 case Intrinsic::x86_avx2_psrai_d: {
11992 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11993 case Intrinsic::x86_sse2_pslli_w:
11994 case Intrinsic::x86_sse2_pslli_d:
11995 case Intrinsic::x86_sse2_pslli_q:
11996 case Intrinsic::x86_avx2_pslli_w:
11997 case Intrinsic::x86_avx2_pslli_d:
11998 case Intrinsic::x86_avx2_pslli_q:
11999 Opcode = X86ISD::VSHLI;
12001 case Intrinsic::x86_sse2_psrli_w:
12002 case Intrinsic::x86_sse2_psrli_d:
12003 case Intrinsic::x86_sse2_psrli_q:
12004 case Intrinsic::x86_avx2_psrli_w:
12005 case Intrinsic::x86_avx2_psrli_d:
12006 case Intrinsic::x86_avx2_psrli_q:
12007 Opcode = X86ISD::VSRLI;
12009 case Intrinsic::x86_sse2_psrai_w:
12010 case Intrinsic::x86_sse2_psrai_d:
12011 case Intrinsic::x86_avx2_psrai_w:
12012 case Intrinsic::x86_avx2_psrai_d:
12013 Opcode = X86ISD::VSRAI;
12016 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12017 Op.getOperand(1), Op.getOperand(2), DAG);
12020 case Intrinsic::x86_sse42_pcmpistria128:
12021 case Intrinsic::x86_sse42_pcmpestria128:
12022 case Intrinsic::x86_sse42_pcmpistric128:
12023 case Intrinsic::x86_sse42_pcmpestric128:
12024 case Intrinsic::x86_sse42_pcmpistrio128:
12025 case Intrinsic::x86_sse42_pcmpestrio128:
12026 case Intrinsic::x86_sse42_pcmpistris128:
12027 case Intrinsic::x86_sse42_pcmpestris128:
12028 case Intrinsic::x86_sse42_pcmpistriz128:
12029 case Intrinsic::x86_sse42_pcmpestriz128: {
12033 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12034 case Intrinsic::x86_sse42_pcmpistria128:
12035 Opcode = X86ISD::PCMPISTRI;
12036 X86CC = X86::COND_A;
12038 case Intrinsic::x86_sse42_pcmpestria128:
12039 Opcode = X86ISD::PCMPESTRI;
12040 X86CC = X86::COND_A;
12042 case Intrinsic::x86_sse42_pcmpistric128:
12043 Opcode = X86ISD::PCMPISTRI;
12044 X86CC = X86::COND_B;
12046 case Intrinsic::x86_sse42_pcmpestric128:
12047 Opcode = X86ISD::PCMPESTRI;
12048 X86CC = X86::COND_B;
12050 case Intrinsic::x86_sse42_pcmpistrio128:
12051 Opcode = X86ISD::PCMPISTRI;
12052 X86CC = X86::COND_O;
12054 case Intrinsic::x86_sse42_pcmpestrio128:
12055 Opcode = X86ISD::PCMPESTRI;
12056 X86CC = X86::COND_O;
12058 case Intrinsic::x86_sse42_pcmpistris128:
12059 Opcode = X86ISD::PCMPISTRI;
12060 X86CC = X86::COND_S;
12062 case Intrinsic::x86_sse42_pcmpestris128:
12063 Opcode = X86ISD::PCMPESTRI;
12064 X86CC = X86::COND_S;
12066 case Intrinsic::x86_sse42_pcmpistriz128:
12067 Opcode = X86ISD::PCMPISTRI;
12068 X86CC = X86::COND_E;
12070 case Intrinsic::x86_sse42_pcmpestriz128:
12071 Opcode = X86ISD::PCMPESTRI;
12072 X86CC = X86::COND_E;
12075 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12076 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12077 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12078 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12079 DAG.getConstant(X86CC, MVT::i8),
12080 SDValue(PCMP.getNode(), 1));
12081 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12084 case Intrinsic::x86_sse42_pcmpistri128:
12085 case Intrinsic::x86_sse42_pcmpestri128: {
12087 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12088 Opcode = X86ISD::PCMPISTRI;
12090 Opcode = X86ISD::PCMPESTRI;
12092 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12093 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12094 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12096 case Intrinsic::x86_fma_vfmadd_ps:
12097 case Intrinsic::x86_fma_vfmadd_pd:
12098 case Intrinsic::x86_fma_vfmsub_ps:
12099 case Intrinsic::x86_fma_vfmsub_pd:
12100 case Intrinsic::x86_fma_vfnmadd_ps:
12101 case Intrinsic::x86_fma_vfnmadd_pd:
12102 case Intrinsic::x86_fma_vfnmsub_ps:
12103 case Intrinsic::x86_fma_vfnmsub_pd:
12104 case Intrinsic::x86_fma_vfmaddsub_ps:
12105 case Intrinsic::x86_fma_vfmaddsub_pd:
12106 case Intrinsic::x86_fma_vfmsubadd_ps:
12107 case Intrinsic::x86_fma_vfmsubadd_pd:
12108 case Intrinsic::x86_fma_vfmadd_ps_256:
12109 case Intrinsic::x86_fma_vfmadd_pd_256:
12110 case Intrinsic::x86_fma_vfmsub_ps_256:
12111 case Intrinsic::x86_fma_vfmsub_pd_256:
12112 case Intrinsic::x86_fma_vfnmadd_ps_256:
12113 case Intrinsic::x86_fma_vfnmadd_pd_256:
12114 case Intrinsic::x86_fma_vfnmsub_ps_256:
12115 case Intrinsic::x86_fma_vfnmsub_pd_256:
12116 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12117 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12118 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12119 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12120 case Intrinsic::x86_fma_vfmadd_ps_512:
12121 case Intrinsic::x86_fma_vfmadd_pd_512:
12122 case Intrinsic::x86_fma_vfmsub_ps_512:
12123 case Intrinsic::x86_fma_vfmsub_pd_512:
12124 case Intrinsic::x86_fma_vfnmadd_ps_512:
12125 case Intrinsic::x86_fma_vfnmadd_pd_512:
12126 case Intrinsic::x86_fma_vfnmsub_ps_512:
12127 case Intrinsic::x86_fma_vfnmsub_pd_512:
12128 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12129 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12130 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12131 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12134 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12135 case Intrinsic::x86_fma_vfmadd_ps:
12136 case Intrinsic::x86_fma_vfmadd_pd:
12137 case Intrinsic::x86_fma_vfmadd_ps_256:
12138 case Intrinsic::x86_fma_vfmadd_pd_256:
12139 case Intrinsic::x86_fma_vfmadd_ps_512:
12140 case Intrinsic::x86_fma_vfmadd_pd_512:
12141 Opc = X86ISD::FMADD;
12143 case Intrinsic::x86_fma_vfmsub_ps:
12144 case Intrinsic::x86_fma_vfmsub_pd:
12145 case Intrinsic::x86_fma_vfmsub_ps_256:
12146 case Intrinsic::x86_fma_vfmsub_pd_256:
12147 case Intrinsic::x86_fma_vfmsub_ps_512:
12148 case Intrinsic::x86_fma_vfmsub_pd_512:
12149 Opc = X86ISD::FMSUB;
12151 case Intrinsic::x86_fma_vfnmadd_ps:
12152 case Intrinsic::x86_fma_vfnmadd_pd:
12153 case Intrinsic::x86_fma_vfnmadd_ps_256:
12154 case Intrinsic::x86_fma_vfnmadd_pd_256:
12155 case Intrinsic::x86_fma_vfnmadd_ps_512:
12156 case Intrinsic::x86_fma_vfnmadd_pd_512:
12157 Opc = X86ISD::FNMADD;
12159 case Intrinsic::x86_fma_vfnmsub_ps:
12160 case Intrinsic::x86_fma_vfnmsub_pd:
12161 case Intrinsic::x86_fma_vfnmsub_ps_256:
12162 case Intrinsic::x86_fma_vfnmsub_pd_256:
12163 case Intrinsic::x86_fma_vfnmsub_ps_512:
12164 case Intrinsic::x86_fma_vfnmsub_pd_512:
12165 Opc = X86ISD::FNMSUB;
12167 case Intrinsic::x86_fma_vfmaddsub_ps:
12168 case Intrinsic::x86_fma_vfmaddsub_pd:
12169 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12170 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12171 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12172 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12173 Opc = X86ISD::FMADDSUB;
12175 case Intrinsic::x86_fma_vfmsubadd_ps:
12176 case Intrinsic::x86_fma_vfmsubadd_pd:
12177 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12178 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12179 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12180 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12181 Opc = X86ISD::FMSUBADD;
12185 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12186 Op.getOperand(2), Op.getOperand(3));
12191 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12192 SDValue Base, SDValue Index,
12193 SDValue ScaleOp, SDValue Chain,
12194 const X86Subtarget * Subtarget) {
12196 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12197 assert(C && "Invalid scale type");
12198 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12199 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12200 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12201 Index.getSimpleValueType().getVectorNumElements());
12202 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12203 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12204 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12205 SDValue Segment = DAG.getRegister(0, MVT::i32);
12206 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12207 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12208 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12209 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12212 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12213 SDValue Src, SDValue Mask, SDValue Base,
12214 SDValue Index, SDValue ScaleOp, SDValue Chain,
12215 const X86Subtarget * Subtarget) {
12217 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12218 assert(C && "Invalid scale type");
12219 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12220 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12221 Index.getSimpleValueType().getVectorNumElements());
12222 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12223 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12224 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12225 SDValue Segment = DAG.getRegister(0, MVT::i32);
12226 if (Src.getOpcode() == ISD::UNDEF)
12227 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12228 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12229 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12230 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12231 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12234 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12235 SDValue Src, SDValue Base, SDValue Index,
12236 SDValue ScaleOp, SDValue Chain) {
12238 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12239 assert(C && "Invalid scale type");
12240 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12241 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12242 SDValue Segment = DAG.getRegister(0, MVT::i32);
12243 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12244 Index.getSimpleValueType().getVectorNumElements());
12245 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12246 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12247 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12248 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12249 return SDValue(Res, 1);
12252 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12253 SDValue Src, SDValue Mask, SDValue Base,
12254 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12256 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12257 assert(C && "Invalid scale type");
12258 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12259 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12260 SDValue Segment = DAG.getRegister(0, MVT::i32);
12261 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12262 Index.getSimpleValueType().getVectorNumElements());
12263 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12264 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12265 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12266 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12267 return SDValue(Res, 1);
12270 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12271 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12272 // also used to custom lower READCYCLECOUNTER nodes.
12273 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12274 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12275 SmallVectorImpl<SDValue> &Results) {
12276 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12277 SDValue TheChain = N->getOperand(0);
12278 SDValue rd = DAG.getNode(Opcode, DL, Tys, &TheChain, 1);
12281 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12282 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12283 // and the EAX register is loaded with the low-order 32 bits.
12284 if (Subtarget->is64Bit()) {
12285 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12286 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12289 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12290 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12293 SDValue Chain = HI.getValue(1);
12295 if (Opcode == X86ISD::RDTSCP_DAG) {
12296 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12298 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12299 // the ECX register. Add 'ecx' explicitly to the chain.
12300 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12302 // Explicitly store the content of ECX at the location passed in input
12303 // to the 'rdtscp' intrinsic.
12304 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12305 MachinePointerInfo(), false, false, 0);
12308 if (Subtarget->is64Bit()) {
12309 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12310 // the EAX register is loaded with the low-order 32 bits.
12311 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12312 DAG.getConstant(32, MVT::i8));
12313 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12314 Results.push_back(Chain);
12318 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12319 SDValue Ops[] = { LO, HI };
12320 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops,
12321 array_lengthof(Ops));
12322 Results.push_back(Pair);
12323 Results.push_back(Chain);
12326 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12327 SelectionDAG &DAG) {
12328 SmallVector<SDValue, 2> Results;
12330 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12332 return DAG.getMergeValues(&Results[0], Results.size(), DL);
12335 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12336 SelectionDAG &DAG) {
12338 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12340 default: return SDValue(); // Don't custom lower most intrinsics.
12342 // RDRAND/RDSEED intrinsics.
12343 case Intrinsic::x86_rdrand_16:
12344 case Intrinsic::x86_rdrand_32:
12345 case Intrinsic::x86_rdrand_64:
12346 case Intrinsic::x86_rdseed_16:
12347 case Intrinsic::x86_rdseed_32:
12348 case Intrinsic::x86_rdseed_64: {
12349 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12350 IntNo == Intrinsic::x86_rdseed_32 ||
12351 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12353 // Emit the node with the right value type.
12354 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12355 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12357 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12358 // Otherwise return the value from Rand, which is always 0, casted to i32.
12359 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12360 DAG.getConstant(1, Op->getValueType(1)),
12361 DAG.getConstant(X86::COND_B, MVT::i32),
12362 SDValue(Result.getNode(), 1) };
12363 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12364 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12365 Ops, array_lengthof(Ops));
12367 // Return { result, isValid, chain }.
12368 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12369 SDValue(Result.getNode(), 2));
12371 //int_gather(index, base, scale);
12372 case Intrinsic::x86_avx512_gather_qpd_512:
12373 case Intrinsic::x86_avx512_gather_qps_512:
12374 case Intrinsic::x86_avx512_gather_dpd_512:
12375 case Intrinsic::x86_avx512_gather_qpi_512:
12376 case Intrinsic::x86_avx512_gather_qpq_512:
12377 case Intrinsic::x86_avx512_gather_dpq_512:
12378 case Intrinsic::x86_avx512_gather_dps_512:
12379 case Intrinsic::x86_avx512_gather_dpi_512: {
12382 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12383 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12384 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12385 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12386 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12387 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12388 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12389 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12390 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12392 SDValue Chain = Op.getOperand(0);
12393 SDValue Index = Op.getOperand(2);
12394 SDValue Base = Op.getOperand(3);
12395 SDValue Scale = Op.getOperand(4);
12396 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12398 //int_gather_mask(v1, mask, index, base, scale);
12399 case Intrinsic::x86_avx512_gather_qps_mask_512:
12400 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12401 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12402 case Intrinsic::x86_avx512_gather_dps_mask_512:
12403 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12404 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12405 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12406 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12409 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12410 case Intrinsic::x86_avx512_gather_qps_mask_512:
12411 Opc = X86::VGATHERQPSZrm; break;
12412 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12413 Opc = X86::VGATHERQPDZrm; break;
12414 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12415 Opc = X86::VGATHERDPDZrm; break;
12416 case Intrinsic::x86_avx512_gather_dps_mask_512:
12417 Opc = X86::VGATHERDPSZrm; break;
12418 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12419 Opc = X86::VPGATHERQDZrm; break;
12420 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12421 Opc = X86::VPGATHERQQZrm; break;
12422 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12423 Opc = X86::VPGATHERDDZrm; break;
12424 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12425 Opc = X86::VPGATHERDQZrm; break;
12427 SDValue Chain = Op.getOperand(0);
12428 SDValue Src = Op.getOperand(2);
12429 SDValue Mask = Op.getOperand(3);
12430 SDValue Index = Op.getOperand(4);
12431 SDValue Base = Op.getOperand(5);
12432 SDValue Scale = Op.getOperand(6);
12433 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12436 //int_scatter(base, index, v1, scale);
12437 case Intrinsic::x86_avx512_scatter_qpd_512:
12438 case Intrinsic::x86_avx512_scatter_qps_512:
12439 case Intrinsic::x86_avx512_scatter_dpd_512:
12440 case Intrinsic::x86_avx512_scatter_qpi_512:
12441 case Intrinsic::x86_avx512_scatter_qpq_512:
12442 case Intrinsic::x86_avx512_scatter_dpq_512:
12443 case Intrinsic::x86_avx512_scatter_dps_512:
12444 case Intrinsic::x86_avx512_scatter_dpi_512: {
12447 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12448 case Intrinsic::x86_avx512_scatter_qpd_512:
12449 Opc = X86::VSCATTERQPDZmr; break;
12450 case Intrinsic::x86_avx512_scatter_qps_512:
12451 Opc = X86::VSCATTERQPSZmr; break;
12452 case Intrinsic::x86_avx512_scatter_dpd_512:
12453 Opc = X86::VSCATTERDPDZmr; break;
12454 case Intrinsic::x86_avx512_scatter_dps_512:
12455 Opc = X86::VSCATTERDPSZmr; break;
12456 case Intrinsic::x86_avx512_scatter_qpi_512:
12457 Opc = X86::VPSCATTERQDZmr; break;
12458 case Intrinsic::x86_avx512_scatter_qpq_512:
12459 Opc = X86::VPSCATTERQQZmr; break;
12460 case Intrinsic::x86_avx512_scatter_dpq_512:
12461 Opc = X86::VPSCATTERDQZmr; break;
12462 case Intrinsic::x86_avx512_scatter_dpi_512:
12463 Opc = X86::VPSCATTERDDZmr; break;
12465 SDValue Chain = Op.getOperand(0);
12466 SDValue Base = Op.getOperand(2);
12467 SDValue Index = Op.getOperand(3);
12468 SDValue Src = Op.getOperand(4);
12469 SDValue Scale = Op.getOperand(5);
12470 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12472 //int_scatter_mask(base, mask, index, v1, scale);
12473 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12474 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12475 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12476 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12477 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12478 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12479 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12480 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12483 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12484 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12485 Opc = X86::VSCATTERQPDZmr; break;
12486 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12487 Opc = X86::VSCATTERQPSZmr; break;
12488 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12489 Opc = X86::VSCATTERDPDZmr; break;
12490 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12491 Opc = X86::VSCATTERDPSZmr; break;
12492 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12493 Opc = X86::VPSCATTERQDZmr; break;
12494 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12495 Opc = X86::VPSCATTERQQZmr; break;
12496 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12497 Opc = X86::VPSCATTERDQZmr; break;
12498 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12499 Opc = X86::VPSCATTERDDZmr; break;
12501 SDValue Chain = Op.getOperand(0);
12502 SDValue Base = Op.getOperand(2);
12503 SDValue Mask = Op.getOperand(3);
12504 SDValue Index = Op.getOperand(4);
12505 SDValue Src = Op.getOperand(5);
12506 SDValue Scale = Op.getOperand(6);
12507 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12509 // Read Time Stamp Counter (RDTSC).
12510 case Intrinsic::x86_rdtsc:
12511 // Read Time Stamp Counter and Processor ID (RDTSCP).
12512 case Intrinsic::x86_rdtscp: {
12515 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12516 case Intrinsic::x86_rdtsc:
12517 Opc = X86ISD::RDTSC_DAG; break;
12518 case Intrinsic::x86_rdtscp:
12519 Opc = X86ISD::RDTSCP_DAG; break;
12521 SmallVector<SDValue, 2> Results;
12522 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12523 return DAG.getMergeValues(&Results[0], Results.size(), dl);
12525 // XTEST intrinsics.
12526 case Intrinsic::x86_xtest: {
12527 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12528 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12529 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12530 DAG.getConstant(X86::COND_NE, MVT::i8),
12532 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12533 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12534 Ret, SDValue(InTrans.getNode(), 1));
12539 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12540 SelectionDAG &DAG) const {
12541 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12542 MFI->setReturnAddressIsTaken(true);
12544 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12547 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12549 EVT PtrVT = getPointerTy();
12552 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12553 const X86RegisterInfo *RegInfo =
12554 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12555 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12556 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12557 DAG.getNode(ISD::ADD, dl, PtrVT,
12558 FrameAddr, Offset),
12559 MachinePointerInfo(), false, false, false, 0);
12562 // Just load the return address.
12563 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12564 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12565 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12568 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12569 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12570 MFI->setFrameAddressIsTaken(true);
12572 EVT VT = Op.getValueType();
12573 SDLoc dl(Op); // FIXME probably not meaningful
12574 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12575 const X86RegisterInfo *RegInfo =
12576 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12577 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12578 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12579 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12580 "Invalid Frame Register!");
12581 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12583 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12584 MachinePointerInfo(),
12585 false, false, false, 0);
12589 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12590 SelectionDAG &DAG) const {
12591 const X86RegisterInfo *RegInfo =
12592 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12593 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12596 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12597 SDValue Chain = Op.getOperand(0);
12598 SDValue Offset = Op.getOperand(1);
12599 SDValue Handler = Op.getOperand(2);
12602 EVT PtrVT = getPointerTy();
12603 const X86RegisterInfo *RegInfo =
12604 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12605 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12606 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12607 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12608 "Invalid Frame Register!");
12609 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12610 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12612 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12613 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12614 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12615 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12617 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12619 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12620 DAG.getRegister(StoreAddrReg, PtrVT));
12623 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12624 SelectionDAG &DAG) const {
12626 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12627 DAG.getVTList(MVT::i32, MVT::Other),
12628 Op.getOperand(0), Op.getOperand(1));
12631 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12632 SelectionDAG &DAG) const {
12634 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12635 Op.getOperand(0), Op.getOperand(1));
12638 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12639 return Op.getOperand(0);
12642 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12643 SelectionDAG &DAG) const {
12644 SDValue Root = Op.getOperand(0);
12645 SDValue Trmp = Op.getOperand(1); // trampoline
12646 SDValue FPtr = Op.getOperand(2); // nested function
12647 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12650 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12651 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12653 if (Subtarget->is64Bit()) {
12654 SDValue OutChains[6];
12656 // Large code-model.
12657 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12658 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12660 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12661 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12663 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12665 // Load the pointer to the nested function into R11.
12666 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12667 SDValue Addr = Trmp;
12668 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12669 Addr, MachinePointerInfo(TrmpAddr),
12672 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12673 DAG.getConstant(2, MVT::i64));
12674 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12675 MachinePointerInfo(TrmpAddr, 2),
12678 // Load the 'nest' parameter value into R10.
12679 // R10 is specified in X86CallingConv.td
12680 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12681 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12682 DAG.getConstant(10, MVT::i64));
12683 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12684 Addr, MachinePointerInfo(TrmpAddr, 10),
12687 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12688 DAG.getConstant(12, MVT::i64));
12689 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12690 MachinePointerInfo(TrmpAddr, 12),
12693 // Jump to the nested function.
12694 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12695 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12696 DAG.getConstant(20, MVT::i64));
12697 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12698 Addr, MachinePointerInfo(TrmpAddr, 20),
12701 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12702 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12703 DAG.getConstant(22, MVT::i64));
12704 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12705 MachinePointerInfo(TrmpAddr, 22),
12708 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12710 const Function *Func =
12711 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12712 CallingConv::ID CC = Func->getCallingConv();
12717 llvm_unreachable("Unsupported calling convention");
12718 case CallingConv::C:
12719 case CallingConv::X86_StdCall: {
12720 // Pass 'nest' parameter in ECX.
12721 // Must be kept in sync with X86CallingConv.td
12722 NestReg = X86::ECX;
12724 // Check that ECX wasn't needed by an 'inreg' parameter.
12725 FunctionType *FTy = Func->getFunctionType();
12726 const AttributeSet &Attrs = Func->getAttributes();
12728 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12729 unsigned InRegCount = 0;
12732 for (FunctionType::param_iterator I = FTy->param_begin(),
12733 E = FTy->param_end(); I != E; ++I, ++Idx)
12734 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12735 // FIXME: should only count parameters that are lowered to integers.
12736 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12738 if (InRegCount > 2) {
12739 report_fatal_error("Nest register in use - reduce number of inreg"
12745 case CallingConv::X86_FastCall:
12746 case CallingConv::X86_ThisCall:
12747 case CallingConv::Fast:
12748 // Pass 'nest' parameter in EAX.
12749 // Must be kept in sync with X86CallingConv.td
12750 NestReg = X86::EAX;
12754 SDValue OutChains[4];
12755 SDValue Addr, Disp;
12757 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12758 DAG.getConstant(10, MVT::i32));
12759 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12761 // This is storing the opcode for MOV32ri.
12762 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12763 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12764 OutChains[0] = DAG.getStore(Root, dl,
12765 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12766 Trmp, MachinePointerInfo(TrmpAddr),
12769 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12770 DAG.getConstant(1, MVT::i32));
12771 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12772 MachinePointerInfo(TrmpAddr, 1),
12775 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12776 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12777 DAG.getConstant(5, MVT::i32));
12778 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12779 MachinePointerInfo(TrmpAddr, 5),
12782 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12783 DAG.getConstant(6, MVT::i32));
12784 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12785 MachinePointerInfo(TrmpAddr, 6),
12788 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12792 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12793 SelectionDAG &DAG) const {
12795 The rounding mode is in bits 11:10 of FPSR, and has the following
12797 00 Round to nearest
12802 FLT_ROUNDS, on the other hand, expects the following:
12809 To perform the conversion, we do:
12810 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12813 MachineFunction &MF = DAG.getMachineFunction();
12814 const TargetMachine &TM = MF.getTarget();
12815 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12816 unsigned StackAlignment = TFI.getStackAlignment();
12817 MVT VT = Op.getSimpleValueType();
12820 // Save FP Control Word to stack slot
12821 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12822 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12824 MachineMemOperand *MMO =
12825 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12826 MachineMemOperand::MOStore, 2, 2);
12828 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12829 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12830 DAG.getVTList(MVT::Other),
12831 Ops, array_lengthof(Ops), MVT::i16,
12834 // Load FP Control Word from stack slot
12835 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12836 MachinePointerInfo(), false, false, false, 0);
12838 // Transform as necessary
12840 DAG.getNode(ISD::SRL, DL, MVT::i16,
12841 DAG.getNode(ISD::AND, DL, MVT::i16,
12842 CWD, DAG.getConstant(0x800, MVT::i16)),
12843 DAG.getConstant(11, MVT::i8));
12845 DAG.getNode(ISD::SRL, DL, MVT::i16,
12846 DAG.getNode(ISD::AND, DL, MVT::i16,
12847 CWD, DAG.getConstant(0x400, MVT::i16)),
12848 DAG.getConstant(9, MVT::i8));
12851 DAG.getNode(ISD::AND, DL, MVT::i16,
12852 DAG.getNode(ISD::ADD, DL, MVT::i16,
12853 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12854 DAG.getConstant(1, MVT::i16)),
12855 DAG.getConstant(3, MVT::i16));
12857 return DAG.getNode((VT.getSizeInBits() < 16 ?
12858 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12861 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12862 MVT VT = Op.getSimpleValueType();
12864 unsigned NumBits = VT.getSizeInBits();
12867 Op = Op.getOperand(0);
12868 if (VT == MVT::i8) {
12869 // Zero extend to i32 since there is not an i8 bsr.
12871 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12874 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12875 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12876 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12878 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12881 DAG.getConstant(NumBits+NumBits-1, OpVT),
12882 DAG.getConstant(X86::COND_E, MVT::i8),
12885 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12887 // Finally xor with NumBits-1.
12888 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12891 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12895 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12896 MVT VT = Op.getSimpleValueType();
12898 unsigned NumBits = VT.getSizeInBits();
12901 Op = Op.getOperand(0);
12902 if (VT == MVT::i8) {
12903 // Zero extend to i32 since there is not an i8 bsr.
12905 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12908 // Issue a bsr (scan bits in reverse).
12909 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12910 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12912 // And xor with NumBits-1.
12913 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12916 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12920 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12921 MVT VT = Op.getSimpleValueType();
12922 unsigned NumBits = VT.getSizeInBits();
12924 Op = Op.getOperand(0);
12926 // Issue a bsf (scan bits forward) which also sets EFLAGS.
12927 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12928 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12930 // If src is zero (i.e. bsf sets ZF), returns NumBits.
12933 DAG.getConstant(NumBits, VT),
12934 DAG.getConstant(X86::COND_E, MVT::i8),
12937 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12940 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12941 // ones, and then concatenate the result back.
12942 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12943 MVT VT = Op.getSimpleValueType();
12945 assert(VT.is256BitVector() && VT.isInteger() &&
12946 "Unsupported value type for operation");
12948 unsigned NumElems = VT.getVectorNumElements();
12951 // Extract the LHS vectors
12952 SDValue LHS = Op.getOperand(0);
12953 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12954 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12956 // Extract the RHS vectors
12957 SDValue RHS = Op.getOperand(1);
12958 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12959 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12961 MVT EltVT = VT.getVectorElementType();
12962 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12964 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12965 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12966 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12969 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12970 assert(Op.getSimpleValueType().is256BitVector() &&
12971 Op.getSimpleValueType().isInteger() &&
12972 "Only handle AVX 256-bit vector integer operation");
12973 return Lower256IntArith(Op, DAG);
12976 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12977 assert(Op.getSimpleValueType().is256BitVector() &&
12978 Op.getSimpleValueType().isInteger() &&
12979 "Only handle AVX 256-bit vector integer operation");
12980 return Lower256IntArith(Op, DAG);
12983 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12984 SelectionDAG &DAG) {
12986 MVT VT = Op.getSimpleValueType();
12988 // Decompose 256-bit ops into smaller 128-bit ops.
12989 if (VT.is256BitVector() && !Subtarget->hasInt256())
12990 return Lower256IntArith(Op, DAG);
12992 SDValue A = Op.getOperand(0);
12993 SDValue B = Op.getOperand(1);
12995 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12996 if (VT == MVT::v4i32) {
12997 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12998 "Should not custom lower when pmuldq is available!");
13000 // Extract the odd parts.
13001 static const int UnpackMask[] = { 1, -1, 3, -1 };
13002 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13003 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13005 // Multiply the even parts.
13006 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13007 // Now multiply odd parts.
13008 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13010 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13011 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13013 // Merge the two vectors back together with a shuffle. This expands into 2
13015 static const int ShufMask[] = { 0, 4, 2, 6 };
13016 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13019 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13020 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13022 // Ahi = psrlqi(a, 32);
13023 // Bhi = psrlqi(b, 32);
13025 // AloBlo = pmuludq(a, b);
13026 // AloBhi = pmuludq(a, Bhi);
13027 // AhiBlo = pmuludq(Ahi, b);
13029 // AloBhi = psllqi(AloBhi, 32);
13030 // AhiBlo = psllqi(AhiBlo, 32);
13031 // return AloBlo + AloBhi + AhiBlo;
13033 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13034 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13036 // Bit cast to 32-bit vectors for MULUDQ
13037 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13038 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13039 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13040 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13041 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13042 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13044 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13045 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13046 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13048 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13049 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13051 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13052 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13055 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
13056 MVT VT = Op.getSimpleValueType();
13057 MVT EltTy = VT.getVectorElementType();
13058 unsigned NumElts = VT.getVectorNumElements();
13059 SDValue N0 = Op.getOperand(0);
13062 // Lower sdiv X, pow2-const.
13063 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
13067 APInt SplatValue, SplatUndef;
13068 unsigned SplatBitSize;
13070 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
13072 EltTy.getSizeInBits() < SplatBitSize)
13075 if ((SplatValue != 0) &&
13076 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
13077 unsigned Lg2 = SplatValue.countTrailingZeros();
13078 // Splat the sign bit.
13079 SmallVector<SDValue, 16> Sz(NumElts,
13080 DAG.getConstant(EltTy.getSizeInBits() - 1,
13082 SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
13083 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
13085 // Add (N0 < 0) ? abs2 - 1 : 0;
13086 SmallVector<SDValue, 16> Amt(NumElts,
13087 DAG.getConstant(EltTy.getSizeInBits() - Lg2,
13089 SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
13090 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
13092 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
13093 SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
13094 SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
13095 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
13098 // If we're dividing by a positive value, we're done. Otherwise, we must
13099 // negate the result.
13100 if (SplatValue.isNonNegative())
13103 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
13104 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
13105 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
13110 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13111 const X86Subtarget *Subtarget) {
13112 MVT VT = Op.getSimpleValueType();
13114 SDValue R = Op.getOperand(0);
13115 SDValue Amt = Op.getOperand(1);
13117 // Optimize shl/srl/sra with constant shift amount.
13118 if (isSplatVector(Amt.getNode())) {
13119 SDValue SclrAmt = Amt->getOperand(0);
13120 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13121 uint64_t ShiftAmt = C->getZExtValue();
13123 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13124 (Subtarget->hasInt256() &&
13125 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13126 (Subtarget->hasAVX512() &&
13127 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13128 if (Op.getOpcode() == ISD::SHL)
13129 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13131 if (Op.getOpcode() == ISD::SRL)
13132 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13134 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13135 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13139 if (VT == MVT::v16i8) {
13140 if (Op.getOpcode() == ISD::SHL) {
13141 // Make a large shift.
13142 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13143 MVT::v8i16, R, ShiftAmt,
13145 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13146 // Zero out the rightmost bits.
13147 SmallVector<SDValue, 16> V(16,
13148 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13150 return DAG.getNode(ISD::AND, dl, VT, SHL,
13151 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13153 if (Op.getOpcode() == ISD::SRL) {
13154 // Make a large shift.
13155 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13156 MVT::v8i16, R, ShiftAmt,
13158 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13159 // Zero out the leftmost bits.
13160 SmallVector<SDValue, 16> V(16,
13161 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13163 return DAG.getNode(ISD::AND, dl, VT, SRL,
13164 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13166 if (Op.getOpcode() == ISD::SRA) {
13167 if (ShiftAmt == 7) {
13168 // R s>> 7 === R s< 0
13169 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13170 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13173 // R s>> a === ((R u>> a) ^ m) - m
13174 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13175 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13177 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13178 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13179 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13182 llvm_unreachable("Unknown shift opcode.");
13185 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13186 if (Op.getOpcode() == ISD::SHL) {
13187 // Make a large shift.
13188 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13189 MVT::v16i16, R, ShiftAmt,
13191 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13192 // Zero out the rightmost bits.
13193 SmallVector<SDValue, 32> V(32,
13194 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13196 return DAG.getNode(ISD::AND, dl, VT, SHL,
13197 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13199 if (Op.getOpcode() == ISD::SRL) {
13200 // Make a large shift.
13201 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13202 MVT::v16i16, R, ShiftAmt,
13204 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13205 // Zero out the leftmost bits.
13206 SmallVector<SDValue, 32> V(32,
13207 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13209 return DAG.getNode(ISD::AND, dl, VT, SRL,
13210 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13212 if (Op.getOpcode() == ISD::SRA) {
13213 if (ShiftAmt == 7) {
13214 // R s>> 7 === R s< 0
13215 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13216 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13219 // R s>> a === ((R u>> a) ^ m) - m
13220 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13221 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13223 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13224 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13225 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13228 llvm_unreachable("Unknown shift opcode.");
13233 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13234 if (!Subtarget->is64Bit() &&
13235 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13236 Amt.getOpcode() == ISD::BITCAST &&
13237 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13238 Amt = Amt.getOperand(0);
13239 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13240 VT.getVectorNumElements();
13241 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13242 uint64_t ShiftAmt = 0;
13243 for (unsigned i = 0; i != Ratio; ++i) {
13244 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13248 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13250 // Check remaining shift amounts.
13251 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13252 uint64_t ShAmt = 0;
13253 for (unsigned j = 0; j != Ratio; ++j) {
13254 ConstantSDNode *C =
13255 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13259 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13261 if (ShAmt != ShiftAmt)
13264 switch (Op.getOpcode()) {
13266 llvm_unreachable("Unknown shift opcode!");
13268 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13271 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13274 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13282 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13283 const X86Subtarget* Subtarget) {
13284 MVT VT = Op.getSimpleValueType();
13286 SDValue R = Op.getOperand(0);
13287 SDValue Amt = Op.getOperand(1);
13289 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13290 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13291 (Subtarget->hasInt256() &&
13292 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13293 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13294 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13296 EVT EltVT = VT.getVectorElementType();
13298 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13299 unsigned NumElts = VT.getVectorNumElements();
13301 for (i = 0; i != NumElts; ++i) {
13302 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13306 for (j = i; j != NumElts; ++j) {
13307 SDValue Arg = Amt.getOperand(j);
13308 if (Arg.getOpcode() == ISD::UNDEF) continue;
13309 if (Arg != Amt.getOperand(i))
13312 if (i != NumElts && j == NumElts)
13313 BaseShAmt = Amt.getOperand(i);
13315 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13316 Amt = Amt.getOperand(0);
13317 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13318 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13319 SDValue InVec = Amt.getOperand(0);
13320 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13321 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13323 for (; i != NumElts; ++i) {
13324 SDValue Arg = InVec.getOperand(i);
13325 if (Arg.getOpcode() == ISD::UNDEF) continue;
13329 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13330 if (ConstantSDNode *C =
13331 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13332 unsigned SplatIdx =
13333 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13334 if (C->getZExtValue() == SplatIdx)
13335 BaseShAmt = InVec.getOperand(1);
13338 if (BaseShAmt.getNode() == 0)
13339 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13340 DAG.getIntPtrConstant(0));
13344 if (BaseShAmt.getNode()) {
13345 if (EltVT.bitsGT(MVT::i32))
13346 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13347 else if (EltVT.bitsLT(MVT::i32))
13348 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13350 switch (Op.getOpcode()) {
13352 llvm_unreachable("Unknown shift opcode!");
13354 switch (VT.SimpleTy) {
13355 default: return SDValue();
13364 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13367 switch (VT.SimpleTy) {
13368 default: return SDValue();
13375 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13378 switch (VT.SimpleTy) {
13379 default: return SDValue();
13388 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13394 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13395 if (!Subtarget->is64Bit() &&
13396 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13397 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13398 Amt.getOpcode() == ISD::BITCAST &&
13399 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13400 Amt = Amt.getOperand(0);
13401 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13402 VT.getVectorNumElements();
13403 std::vector<SDValue> Vals(Ratio);
13404 for (unsigned i = 0; i != Ratio; ++i)
13405 Vals[i] = Amt.getOperand(i);
13406 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13407 for (unsigned j = 0; j != Ratio; ++j)
13408 if (Vals[j] != Amt.getOperand(i + j))
13411 switch (Op.getOpcode()) {
13413 llvm_unreachable("Unknown shift opcode!");
13415 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13417 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13419 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13426 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13427 SelectionDAG &DAG) {
13429 MVT VT = Op.getSimpleValueType();
13431 SDValue R = Op.getOperand(0);
13432 SDValue Amt = Op.getOperand(1);
13435 if (!Subtarget->hasSSE2())
13438 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13442 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13446 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13448 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13449 if (Subtarget->hasInt256()) {
13450 if (Op.getOpcode() == ISD::SRL &&
13451 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13452 VT == MVT::v4i64 || VT == MVT::v8i32))
13454 if (Op.getOpcode() == ISD::SHL &&
13455 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13456 VT == MVT::v4i64 || VT == MVT::v8i32))
13458 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13462 // If possible, lower this packed shift into a vector multiply instead of
13463 // expanding it into a sequence of scalar shifts.
13464 // Do this only if the vector shift count is a constant build_vector.
13465 if (Op.getOpcode() == ISD::SHL &&
13466 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13467 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13468 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13469 SmallVector<SDValue, 8> Elts;
13470 EVT SVT = VT.getScalarType();
13471 unsigned SVTBits = SVT.getSizeInBits();
13472 const APInt &One = APInt(SVTBits, 1);
13473 unsigned NumElems = VT.getVectorNumElements();
13475 for (unsigned i=0; i !=NumElems; ++i) {
13476 SDValue Op = Amt->getOperand(i);
13477 if (Op->getOpcode() == ISD::UNDEF) {
13478 Elts.push_back(Op);
13482 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13483 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13484 uint64_t ShAmt = C.getZExtValue();
13485 if (ShAmt >= SVTBits) {
13486 Elts.push_back(DAG.getUNDEF(SVT));
13489 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13491 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13492 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13495 // Lower SHL with variable shift amount.
13496 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13497 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13499 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13500 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13501 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13502 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13505 // If possible, lower this shift as a sequence of two shifts by
13506 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13508 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13510 // Could be rewritten as:
13511 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13513 // The advantage is that the two shifts from the example would be
13514 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13515 // the vector shift into four scalar shifts plus four pairs of vector
13517 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13518 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13519 unsigned TargetOpcode = X86ISD::MOVSS;
13520 bool CanBeSimplified;
13521 // The splat value for the first packed shift (the 'X' from the example).
13522 SDValue Amt1 = Amt->getOperand(0);
13523 // The splat value for the second packed shift (the 'Y' from the example).
13524 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13525 Amt->getOperand(2);
13527 // See if it is possible to replace this node with a sequence of
13528 // two shifts followed by a MOVSS/MOVSD
13529 if (VT == MVT::v4i32) {
13530 // Check if it is legal to use a MOVSS.
13531 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13532 Amt2 == Amt->getOperand(3);
13533 if (!CanBeSimplified) {
13534 // Otherwise, check if we can still simplify this node using a MOVSD.
13535 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13536 Amt->getOperand(2) == Amt->getOperand(3);
13537 TargetOpcode = X86ISD::MOVSD;
13538 Amt2 = Amt->getOperand(2);
13541 // Do similar checks for the case where the machine value type
13543 CanBeSimplified = Amt1 == Amt->getOperand(1);
13544 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13545 CanBeSimplified = Amt2 == Amt->getOperand(i);
13547 if (!CanBeSimplified) {
13548 TargetOpcode = X86ISD::MOVSD;
13549 CanBeSimplified = true;
13550 Amt2 = Amt->getOperand(4);
13551 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13552 CanBeSimplified = Amt1 == Amt->getOperand(i);
13553 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13554 CanBeSimplified = Amt2 == Amt->getOperand(j);
13558 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13559 isa<ConstantSDNode>(Amt2)) {
13560 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13561 EVT CastVT = MVT::v4i32;
13563 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13564 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13566 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13567 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13568 if (TargetOpcode == X86ISD::MOVSD)
13569 CastVT = MVT::v2i64;
13570 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13571 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13572 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13574 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13578 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13579 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13582 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13583 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13585 // Turn 'a' into a mask suitable for VSELECT
13586 SDValue VSelM = DAG.getConstant(0x80, VT);
13587 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13588 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13590 SDValue CM1 = DAG.getConstant(0x0f, VT);
13591 SDValue CM2 = DAG.getConstant(0x3f, VT);
13593 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13594 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13595 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13596 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13597 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13600 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13601 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13602 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13604 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13605 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13606 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13607 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13608 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13611 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13612 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13613 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13615 // return VSELECT(r, r+r, a);
13616 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13617 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13621 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13622 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13623 // solution better.
13624 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13625 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13627 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13628 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13629 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13630 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13631 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13634 // Decompose 256-bit shifts into smaller 128-bit shifts.
13635 if (VT.is256BitVector()) {
13636 unsigned NumElems = VT.getVectorNumElements();
13637 MVT EltVT = VT.getVectorElementType();
13638 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13640 // Extract the two vectors
13641 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13642 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13644 // Recreate the shift amount vectors
13645 SDValue Amt1, Amt2;
13646 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13647 // Constant shift amount
13648 SmallVector<SDValue, 4> Amt1Csts;
13649 SmallVector<SDValue, 4> Amt2Csts;
13650 for (unsigned i = 0; i != NumElems/2; ++i)
13651 Amt1Csts.push_back(Amt->getOperand(i));
13652 for (unsigned i = NumElems/2; i != NumElems; ++i)
13653 Amt2Csts.push_back(Amt->getOperand(i));
13655 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13656 &Amt1Csts[0], NumElems/2);
13657 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13658 &Amt2Csts[0], NumElems/2);
13660 // Variable shift amount
13661 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13662 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13665 // Issue new vector shifts for the smaller types
13666 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13667 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13669 // Concatenate the result back
13670 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13676 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13677 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13678 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13679 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13680 // has only one use.
13681 SDNode *N = Op.getNode();
13682 SDValue LHS = N->getOperand(0);
13683 SDValue RHS = N->getOperand(1);
13684 unsigned BaseOp = 0;
13687 switch (Op.getOpcode()) {
13688 default: llvm_unreachable("Unknown ovf instruction!");
13690 // A subtract of one will be selected as a INC. Note that INC doesn't
13691 // set CF, so we can't do this for UADDO.
13692 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13694 BaseOp = X86ISD::INC;
13695 Cond = X86::COND_O;
13698 BaseOp = X86ISD::ADD;
13699 Cond = X86::COND_O;
13702 BaseOp = X86ISD::ADD;
13703 Cond = X86::COND_B;
13706 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13707 // set CF, so we can't do this for USUBO.
13708 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13710 BaseOp = X86ISD::DEC;
13711 Cond = X86::COND_O;
13714 BaseOp = X86ISD::SUB;
13715 Cond = X86::COND_O;
13718 BaseOp = X86ISD::SUB;
13719 Cond = X86::COND_B;
13722 BaseOp = X86ISD::SMUL;
13723 Cond = X86::COND_O;
13725 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13726 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13728 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13731 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13732 DAG.getConstant(X86::COND_O, MVT::i32),
13733 SDValue(Sum.getNode(), 2));
13735 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13739 // Also sets EFLAGS.
13740 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13741 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13744 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13745 DAG.getConstant(Cond, MVT::i32),
13746 SDValue(Sum.getNode(), 1));
13748 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13751 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13752 SelectionDAG &DAG) const {
13754 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13755 MVT VT = Op.getSimpleValueType();
13757 if (!Subtarget->hasSSE2() || !VT.isVector())
13760 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13761 ExtraVT.getScalarType().getSizeInBits();
13763 switch (VT.SimpleTy) {
13764 default: return SDValue();
13767 if (!Subtarget->hasFp256())
13769 if (!Subtarget->hasInt256()) {
13770 // needs to be split
13771 unsigned NumElems = VT.getVectorNumElements();
13773 // Extract the LHS vectors
13774 SDValue LHS = Op.getOperand(0);
13775 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13776 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13778 MVT EltVT = VT.getVectorElementType();
13779 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13781 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13782 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13783 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13785 SDValue Extra = DAG.getValueType(ExtraVT);
13787 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13788 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13790 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13795 SDValue Op0 = Op.getOperand(0);
13796 SDValue Op00 = Op0.getOperand(0);
13798 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13799 if (Op0.getOpcode() == ISD::BITCAST &&
13800 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13801 // (sext (vzext x)) -> (vsext x)
13802 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13803 if (Tmp1.getNode()) {
13804 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13805 // This folding is only valid when the in-reg type is a vector of i8,
13807 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13808 ExtraEltVT == MVT::i32) {
13809 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13810 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13811 "This optimization is invalid without a VZEXT.");
13812 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13818 // If the above didn't work, then just use Shift-Left + Shift-Right.
13819 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13821 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13827 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13828 SelectionDAG &DAG) {
13830 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13831 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13832 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13833 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13835 // The only fence that needs an instruction is a sequentially-consistent
13836 // cross-thread fence.
13837 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13838 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13839 // no-sse2). There isn't any reason to disable it if the target processor
13841 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13842 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13844 SDValue Chain = Op.getOperand(0);
13845 SDValue Zero = DAG.getConstant(0, MVT::i32);
13847 DAG.getRegister(X86::ESP, MVT::i32), // Base
13848 DAG.getTargetConstant(1, MVT::i8), // Scale
13849 DAG.getRegister(0, MVT::i32), // Index
13850 DAG.getTargetConstant(0, MVT::i32), // Disp
13851 DAG.getRegister(0, MVT::i32), // Segment.
13855 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13856 return SDValue(Res, 0);
13859 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13860 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13863 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13864 SelectionDAG &DAG) {
13865 MVT T = Op.getSimpleValueType();
13869 switch(T.SimpleTy) {
13870 default: llvm_unreachable("Invalid value type!");
13871 case MVT::i8: Reg = X86::AL; size = 1; break;
13872 case MVT::i16: Reg = X86::AX; size = 2; break;
13873 case MVT::i32: Reg = X86::EAX; size = 4; break;
13875 assert(Subtarget->is64Bit() && "Node not type legal!");
13876 Reg = X86::RAX; size = 8;
13879 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13880 Op.getOperand(2), SDValue());
13881 SDValue Ops[] = { cpIn.getValue(0),
13884 DAG.getTargetConstant(size, MVT::i8),
13885 cpIn.getValue(1) };
13886 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13887 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13888 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13889 Ops, array_lengthof(Ops), T, MMO);
13891 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13895 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13896 SelectionDAG &DAG) {
13897 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13898 MVT DstVT = Op.getSimpleValueType();
13899 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13900 Subtarget->hasMMX() && "Unexpected custom BITCAST");
13901 assert((DstVT == MVT::i64 ||
13902 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13903 "Unexpected custom BITCAST");
13904 // i64 <=> MMX conversions are Legal.
13905 if (SrcVT==MVT::i64 && DstVT.isVector())
13907 if (DstVT==MVT::i64 && SrcVT.isVector())
13909 // MMX <=> MMX conversions are Legal.
13910 if (SrcVT.isVector() && DstVT.isVector())
13912 // All other conversions need to be expanded.
13916 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13917 SDNode *Node = Op.getNode();
13919 EVT T = Node->getValueType(0);
13920 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13921 DAG.getConstant(0, T), Node->getOperand(2));
13922 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13923 cast<AtomicSDNode>(Node)->getMemoryVT(),
13924 Node->getOperand(0),
13925 Node->getOperand(1), negOp,
13926 cast<AtomicSDNode>(Node)->getMemOperand(),
13927 cast<AtomicSDNode>(Node)->getOrdering(),
13928 cast<AtomicSDNode>(Node)->getSynchScope());
13931 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13932 SDNode *Node = Op.getNode();
13934 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13936 // Convert seq_cst store -> xchg
13937 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13938 // FIXME: On 32-bit, store -> fist or movq would be more efficient
13939 // (The only way to get a 16-byte store is cmpxchg16b)
13940 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13941 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13942 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13943 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13944 cast<AtomicSDNode>(Node)->getMemoryVT(),
13945 Node->getOperand(0),
13946 Node->getOperand(1), Node->getOperand(2),
13947 cast<AtomicSDNode>(Node)->getMemOperand(),
13948 cast<AtomicSDNode>(Node)->getOrdering(),
13949 cast<AtomicSDNode>(Node)->getSynchScope());
13950 return Swap.getValue(1);
13952 // Other atomic stores have a simple pattern.
13956 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13957 EVT VT = Op.getNode()->getSimpleValueType(0);
13959 // Let legalize expand this if it isn't a legal type yet.
13960 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13963 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13966 bool ExtraOp = false;
13967 switch (Op.getOpcode()) {
13968 default: llvm_unreachable("Invalid code");
13969 case ISD::ADDC: Opc = X86ISD::ADD; break;
13970 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13971 case ISD::SUBC: Opc = X86ISD::SUB; break;
13972 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13976 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13978 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13979 Op.getOperand(1), Op.getOperand(2));
13982 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13983 SelectionDAG &DAG) {
13984 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13986 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13987 // which returns the values as { float, float } (in XMM0) or
13988 // { double, double } (which is returned in XMM0, XMM1).
13990 SDValue Arg = Op.getOperand(0);
13991 EVT ArgVT = Arg.getValueType();
13992 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13994 TargetLowering::ArgListTy Args;
13995 TargetLowering::ArgListEntry Entry;
13999 Entry.isSExt = false;
14000 Entry.isZExt = false;
14001 Args.push_back(Entry);
14003 bool isF64 = ArgVT == MVT::f64;
14004 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14005 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14006 // the results are returned via SRet in memory.
14007 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14008 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14009 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14011 Type *RetTy = isF64
14012 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14013 : (Type*)VectorType::get(ArgTy, 4);
14015 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14016 false, false, false, false, 0,
14017 CallingConv::C, /*isTaillCall=*/false,
14018 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14019 Callee, Args, DAG, dl);
14020 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14023 // Returned in xmm0 and xmm1.
14024 return CallResult.first;
14026 // Returned in bits 0:31 and 32:64 xmm0.
14027 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14028 CallResult.first, DAG.getIntPtrConstant(0));
14029 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14030 CallResult.first, DAG.getIntPtrConstant(1));
14031 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14032 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14035 /// LowerOperation - Provide custom lowering hooks for some operations.
14037 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14038 switch (Op.getOpcode()) {
14039 default: llvm_unreachable("Should not custom lower this!");
14040 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14041 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14042 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14043 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14044 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14045 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14046 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14047 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14048 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14049 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14050 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14051 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14052 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14053 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14054 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14055 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14056 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14057 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14058 case ISD::SHL_PARTS:
14059 case ISD::SRA_PARTS:
14060 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14061 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14062 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14063 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14064 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14065 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14066 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14067 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14068 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14069 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14070 case ISD::FABS: return LowerFABS(Op, DAG);
14071 case ISD::FNEG: return LowerFNEG(Op, DAG);
14072 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14073 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14074 case ISD::SETCC: return LowerSETCC(Op, DAG);
14075 case ISD::SELECT: return LowerSELECT(Op, DAG);
14076 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14077 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14078 case ISD::VASTART: return LowerVASTART(Op, DAG);
14079 case ISD::VAARG: return LowerVAARG(Op, DAG);
14080 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14081 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14082 case ISD::INTRINSIC_VOID:
14083 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14084 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14085 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14086 case ISD::FRAME_TO_ARGS_OFFSET:
14087 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14088 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14089 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14090 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14091 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14092 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14093 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14094 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14095 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14096 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14097 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14098 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14101 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14107 case ISD::UMULO: return LowerXALUO(Op, DAG);
14108 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14109 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14113 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14114 case ISD::ADD: return LowerADD(Op, DAG);
14115 case ISD::SUB: return LowerSUB(Op, DAG);
14116 case ISD::SDIV: return LowerSDIV(Op, DAG);
14117 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14121 static void ReplaceATOMIC_LOAD(SDNode *Node,
14122 SmallVectorImpl<SDValue> &Results,
14123 SelectionDAG &DAG) {
14125 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14127 // Convert wide load -> cmpxchg8b/cmpxchg16b
14128 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14129 // (The only way to get a 16-byte load is cmpxchg16b)
14130 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14131 SDValue Zero = DAG.getConstant(0, VT);
14132 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14133 Node->getOperand(0),
14134 Node->getOperand(1), Zero, Zero,
14135 cast<AtomicSDNode>(Node)->getMemOperand(),
14136 cast<AtomicSDNode>(Node)->getOrdering(),
14137 cast<AtomicSDNode>(Node)->getOrdering(),
14138 cast<AtomicSDNode>(Node)->getSynchScope());
14139 Results.push_back(Swap.getValue(0));
14140 Results.push_back(Swap.getValue(1));
14144 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14145 SelectionDAG &DAG, unsigned NewOp) {
14147 assert (Node->getValueType(0) == MVT::i64 &&
14148 "Only know how to expand i64 atomics");
14150 SDValue Chain = Node->getOperand(0);
14151 SDValue In1 = Node->getOperand(1);
14152 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14153 Node->getOperand(2), DAG.getIntPtrConstant(0));
14154 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14155 Node->getOperand(2), DAG.getIntPtrConstant(1));
14156 SDValue Ops[] = { Chain, In1, In2L, In2H };
14157 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14159 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14160 cast<MemSDNode>(Node)->getMemOperand());
14161 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14162 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
14163 Results.push_back(Result.getValue(2));
14166 /// ReplaceNodeResults - Replace a node with an illegal result type
14167 /// with a new node built out of custom code.
14168 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14169 SmallVectorImpl<SDValue>&Results,
14170 SelectionDAG &DAG) const {
14172 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14173 switch (N->getOpcode()) {
14175 llvm_unreachable("Do not know how to custom type legalize this operation!");
14176 case ISD::SIGN_EXTEND_INREG:
14181 // We don't want to expand or promote these.
14183 case ISD::FP_TO_SINT:
14184 case ISD::FP_TO_UINT: {
14185 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14187 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14190 std::pair<SDValue,SDValue> Vals =
14191 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14192 SDValue FIST = Vals.first, StackSlot = Vals.second;
14193 if (FIST.getNode() != 0) {
14194 EVT VT = N->getValueType(0);
14195 // Return a load from the stack slot.
14196 if (StackSlot.getNode() != 0)
14197 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14198 MachinePointerInfo(),
14199 false, false, false, 0));
14201 Results.push_back(FIST);
14205 case ISD::UINT_TO_FP: {
14206 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14207 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14208 N->getValueType(0) != MVT::v2f32)
14210 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14212 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14214 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14215 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14216 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14217 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14218 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14219 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14222 case ISD::FP_ROUND: {
14223 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14225 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14226 Results.push_back(V);
14229 case ISD::INTRINSIC_W_CHAIN: {
14230 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14232 default : llvm_unreachable("Do not know how to custom type "
14233 "legalize this intrinsic operation!");
14234 case Intrinsic::x86_rdtsc:
14235 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14237 case Intrinsic::x86_rdtscp:
14238 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14242 case ISD::READCYCLECOUNTER: {
14243 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14246 case ISD::ATOMIC_CMP_SWAP: {
14247 EVT T = N->getValueType(0);
14248 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14249 bool Regs64bit = T == MVT::i128;
14250 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14251 SDValue cpInL, cpInH;
14252 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14253 DAG.getConstant(0, HalfT));
14254 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14255 DAG.getConstant(1, HalfT));
14256 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14257 Regs64bit ? X86::RAX : X86::EAX,
14259 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14260 Regs64bit ? X86::RDX : X86::EDX,
14261 cpInH, cpInL.getValue(1));
14262 SDValue swapInL, swapInH;
14263 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14264 DAG.getConstant(0, HalfT));
14265 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14266 DAG.getConstant(1, HalfT));
14267 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14268 Regs64bit ? X86::RBX : X86::EBX,
14269 swapInL, cpInH.getValue(1));
14270 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14271 Regs64bit ? X86::RCX : X86::ECX,
14272 swapInH, swapInL.getValue(1));
14273 SDValue Ops[] = { swapInH.getValue(0),
14275 swapInH.getValue(1) };
14276 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14277 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14278 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14279 X86ISD::LCMPXCHG8_DAG;
14280 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14281 Ops, array_lengthof(Ops), T, MMO);
14282 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14283 Regs64bit ? X86::RAX : X86::EAX,
14284 HalfT, Result.getValue(1));
14285 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14286 Regs64bit ? X86::RDX : X86::EDX,
14287 HalfT, cpOutL.getValue(2));
14288 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14289 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14290 Results.push_back(cpOutH.getValue(1));
14293 case ISD::ATOMIC_LOAD_ADD:
14294 case ISD::ATOMIC_LOAD_AND:
14295 case ISD::ATOMIC_LOAD_NAND:
14296 case ISD::ATOMIC_LOAD_OR:
14297 case ISD::ATOMIC_LOAD_SUB:
14298 case ISD::ATOMIC_LOAD_XOR:
14299 case ISD::ATOMIC_LOAD_MAX:
14300 case ISD::ATOMIC_LOAD_MIN:
14301 case ISD::ATOMIC_LOAD_UMAX:
14302 case ISD::ATOMIC_LOAD_UMIN:
14303 case ISD::ATOMIC_SWAP: {
14305 switch (N->getOpcode()) {
14306 default: llvm_unreachable("Unexpected opcode");
14307 case ISD::ATOMIC_LOAD_ADD:
14308 Opc = X86ISD::ATOMADD64_DAG;
14310 case ISD::ATOMIC_LOAD_AND:
14311 Opc = X86ISD::ATOMAND64_DAG;
14313 case ISD::ATOMIC_LOAD_NAND:
14314 Opc = X86ISD::ATOMNAND64_DAG;
14316 case ISD::ATOMIC_LOAD_OR:
14317 Opc = X86ISD::ATOMOR64_DAG;
14319 case ISD::ATOMIC_LOAD_SUB:
14320 Opc = X86ISD::ATOMSUB64_DAG;
14322 case ISD::ATOMIC_LOAD_XOR:
14323 Opc = X86ISD::ATOMXOR64_DAG;
14325 case ISD::ATOMIC_LOAD_MAX:
14326 Opc = X86ISD::ATOMMAX64_DAG;
14328 case ISD::ATOMIC_LOAD_MIN:
14329 Opc = X86ISD::ATOMMIN64_DAG;
14331 case ISD::ATOMIC_LOAD_UMAX:
14332 Opc = X86ISD::ATOMUMAX64_DAG;
14334 case ISD::ATOMIC_LOAD_UMIN:
14335 Opc = X86ISD::ATOMUMIN64_DAG;
14337 case ISD::ATOMIC_SWAP:
14338 Opc = X86ISD::ATOMSWAP64_DAG;
14341 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14344 case ISD::ATOMIC_LOAD:
14345 ReplaceATOMIC_LOAD(N, Results, DAG);
14349 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14351 default: return NULL;
14352 case X86ISD::BSF: return "X86ISD::BSF";
14353 case X86ISD::BSR: return "X86ISD::BSR";
14354 case X86ISD::SHLD: return "X86ISD::SHLD";
14355 case X86ISD::SHRD: return "X86ISD::SHRD";
14356 case X86ISD::FAND: return "X86ISD::FAND";
14357 case X86ISD::FANDN: return "X86ISD::FANDN";
14358 case X86ISD::FOR: return "X86ISD::FOR";
14359 case X86ISD::FXOR: return "X86ISD::FXOR";
14360 case X86ISD::FSRL: return "X86ISD::FSRL";
14361 case X86ISD::FILD: return "X86ISD::FILD";
14362 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14363 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14364 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14365 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14366 case X86ISD::FLD: return "X86ISD::FLD";
14367 case X86ISD::FST: return "X86ISD::FST";
14368 case X86ISD::CALL: return "X86ISD::CALL";
14369 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14370 case X86ISD::BT: return "X86ISD::BT";
14371 case X86ISD::CMP: return "X86ISD::CMP";
14372 case X86ISD::COMI: return "X86ISD::COMI";
14373 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14374 case X86ISD::CMPM: return "X86ISD::CMPM";
14375 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14376 case X86ISD::SETCC: return "X86ISD::SETCC";
14377 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14378 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14379 case X86ISD::CMOV: return "X86ISD::CMOV";
14380 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14381 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14382 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14383 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14384 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14385 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14386 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14387 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14388 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14389 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14390 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14391 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14392 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14393 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14394 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14395 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14396 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14397 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14398 case X86ISD::HADD: return "X86ISD::HADD";
14399 case X86ISD::HSUB: return "X86ISD::HSUB";
14400 case X86ISD::FHADD: return "X86ISD::FHADD";
14401 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14402 case X86ISD::UMAX: return "X86ISD::UMAX";
14403 case X86ISD::UMIN: return "X86ISD::UMIN";
14404 case X86ISD::SMAX: return "X86ISD::SMAX";
14405 case X86ISD::SMIN: return "X86ISD::SMIN";
14406 case X86ISD::FMAX: return "X86ISD::FMAX";
14407 case X86ISD::FMIN: return "X86ISD::FMIN";
14408 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14409 case X86ISD::FMINC: return "X86ISD::FMINC";
14410 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14411 case X86ISD::FRCP: return "X86ISD::FRCP";
14412 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14413 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14414 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14415 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14416 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14417 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14418 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14419 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14420 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14421 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14422 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14423 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14424 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14425 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14426 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14427 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14428 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14429 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14430 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14431 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14432 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14433 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14434 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14435 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14436 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14437 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14438 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14439 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14440 case X86ISD::VSHL: return "X86ISD::VSHL";
14441 case X86ISD::VSRL: return "X86ISD::VSRL";
14442 case X86ISD::VSRA: return "X86ISD::VSRA";
14443 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14444 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14445 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14446 case X86ISD::CMPP: return "X86ISD::CMPP";
14447 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14448 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14449 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14450 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14451 case X86ISD::ADD: return "X86ISD::ADD";
14452 case X86ISD::SUB: return "X86ISD::SUB";
14453 case X86ISD::ADC: return "X86ISD::ADC";
14454 case X86ISD::SBB: return "X86ISD::SBB";
14455 case X86ISD::SMUL: return "X86ISD::SMUL";
14456 case X86ISD::UMUL: return "X86ISD::UMUL";
14457 case X86ISD::INC: return "X86ISD::INC";
14458 case X86ISD::DEC: return "X86ISD::DEC";
14459 case X86ISD::OR: return "X86ISD::OR";
14460 case X86ISD::XOR: return "X86ISD::XOR";
14461 case X86ISD::AND: return "X86ISD::AND";
14462 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14463 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14464 case X86ISD::PTEST: return "X86ISD::PTEST";
14465 case X86ISD::TESTP: return "X86ISD::TESTP";
14466 case X86ISD::TESTM: return "X86ISD::TESTM";
14467 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14468 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14469 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14470 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14471 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14472 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14473 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14474 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14475 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14476 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14477 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14478 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14479 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14480 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14481 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14482 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14483 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14484 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14485 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14486 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14487 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14488 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14489 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14490 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14491 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14492 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14493 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14494 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14495 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14496 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14497 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14498 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14499 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14500 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14501 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14502 case X86ISD::SAHF: return "X86ISD::SAHF";
14503 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14504 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14505 case X86ISD::FMADD: return "X86ISD::FMADD";
14506 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14507 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14508 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14509 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14510 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14511 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14512 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14513 case X86ISD::XTEST: return "X86ISD::XTEST";
14517 // isLegalAddressingMode - Return true if the addressing mode represented
14518 // by AM is legal for this target, for a load/store of the specified type.
14519 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14521 // X86 supports extremely general addressing modes.
14522 CodeModel::Model M = getTargetMachine().getCodeModel();
14523 Reloc::Model R = getTargetMachine().getRelocationModel();
14525 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14526 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14531 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14533 // If a reference to this global requires an extra load, we can't fold it.
14534 if (isGlobalStubReference(GVFlags))
14537 // If BaseGV requires a register for the PIC base, we cannot also have a
14538 // BaseReg specified.
14539 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14542 // If lower 4G is not available, then we must use rip-relative addressing.
14543 if ((M != CodeModel::Small || R != Reloc::Static) &&
14544 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14548 switch (AM.Scale) {
14554 // These scales always work.
14559 // These scales are formed with basereg+scalereg. Only accept if there is
14564 default: // Other stuff never works.
14571 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14572 unsigned Bits = Ty->getScalarSizeInBits();
14574 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14575 // particularly cheaper than those without.
14579 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14580 // variable shifts just as cheap as scalar ones.
14581 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14584 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14585 // fully general vector.
14589 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14590 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14592 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14593 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14594 return NumBits1 > NumBits2;
14597 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14598 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14601 if (!isTypeLegal(EVT::getEVT(Ty1)))
14604 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14606 // Assuming the caller doesn't have a zeroext or signext return parameter,
14607 // truncation all the way down to i1 is valid.
14611 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14612 return isInt<32>(Imm);
14615 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14616 // Can also use sub to handle negated immediates.
14617 return isInt<32>(Imm);
14620 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14621 if (!VT1.isInteger() || !VT2.isInteger())
14623 unsigned NumBits1 = VT1.getSizeInBits();
14624 unsigned NumBits2 = VT2.getSizeInBits();
14625 return NumBits1 > NumBits2;
14628 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14629 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14630 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14633 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14634 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14635 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14638 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14639 EVT VT1 = Val.getValueType();
14640 if (isZExtFree(VT1, VT2))
14643 if (Val.getOpcode() != ISD::LOAD)
14646 if (!VT1.isSimple() || !VT1.isInteger() ||
14647 !VT2.isSimple() || !VT2.isInteger())
14650 switch (VT1.getSimpleVT().SimpleTy) {
14655 // X86 has 8, 16, and 32-bit zero-extending loads.
14663 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14664 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14667 VT = VT.getScalarType();
14669 if (!VT.isSimple())
14672 switch (VT.getSimpleVT().SimpleTy) {
14683 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14684 // i16 instructions are longer (0x66 prefix) and potentially slower.
14685 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14688 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14689 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14690 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14691 /// are assumed to be legal.
14693 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14695 if (!VT.isSimple())
14698 MVT SVT = VT.getSimpleVT();
14700 // Very little shuffling can be done for 64-bit vectors right now.
14701 if (VT.getSizeInBits() == 64)
14704 // FIXME: pshufb, blends, shifts.
14705 return (SVT.getVectorNumElements() == 2 ||
14706 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14707 isMOVLMask(M, SVT) ||
14708 isSHUFPMask(M, SVT) ||
14709 isPSHUFDMask(M, SVT) ||
14710 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14711 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14712 isPALIGNRMask(M, SVT, Subtarget) ||
14713 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14714 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14715 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14716 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14720 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14722 if (!VT.isSimple())
14725 MVT SVT = VT.getSimpleVT();
14726 unsigned NumElts = SVT.getVectorNumElements();
14727 // FIXME: This collection of masks seems suspect.
14730 if (NumElts == 4 && SVT.is128BitVector()) {
14731 return (isMOVLMask(Mask, SVT) ||
14732 isCommutedMOVLMask(Mask, SVT, true) ||
14733 isSHUFPMask(Mask, SVT) ||
14734 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14739 //===----------------------------------------------------------------------===//
14740 // X86 Scheduler Hooks
14741 //===----------------------------------------------------------------------===//
14743 /// Utility function to emit xbegin specifying the start of an RTM region.
14744 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14745 const TargetInstrInfo *TII) {
14746 DebugLoc DL = MI->getDebugLoc();
14748 const BasicBlock *BB = MBB->getBasicBlock();
14749 MachineFunction::iterator I = MBB;
14752 // For the v = xbegin(), we generate
14763 MachineBasicBlock *thisMBB = MBB;
14764 MachineFunction *MF = MBB->getParent();
14765 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14766 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14767 MF->insert(I, mainMBB);
14768 MF->insert(I, sinkMBB);
14770 // Transfer the remainder of BB and its successor edges to sinkMBB.
14771 sinkMBB->splice(sinkMBB->begin(), MBB,
14772 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14773 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14777 // # fallthrough to mainMBB
14778 // # abortion to sinkMBB
14779 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14780 thisMBB->addSuccessor(mainMBB);
14781 thisMBB->addSuccessor(sinkMBB);
14785 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14786 mainMBB->addSuccessor(sinkMBB);
14789 // EAX is live into the sinkMBB
14790 sinkMBB->addLiveIn(X86::EAX);
14791 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14792 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14795 MI->eraseFromParent();
14799 // Get CMPXCHG opcode for the specified data type.
14800 static unsigned getCmpXChgOpcode(EVT VT) {
14801 switch (VT.getSimpleVT().SimpleTy) {
14802 case MVT::i8: return X86::LCMPXCHG8;
14803 case MVT::i16: return X86::LCMPXCHG16;
14804 case MVT::i32: return X86::LCMPXCHG32;
14805 case MVT::i64: return X86::LCMPXCHG64;
14809 llvm_unreachable("Invalid operand size!");
14812 // Get LOAD opcode for the specified data type.
14813 static unsigned getLoadOpcode(EVT VT) {
14814 switch (VT.getSimpleVT().SimpleTy) {
14815 case MVT::i8: return X86::MOV8rm;
14816 case MVT::i16: return X86::MOV16rm;
14817 case MVT::i32: return X86::MOV32rm;
14818 case MVT::i64: return X86::MOV64rm;
14822 llvm_unreachable("Invalid operand size!");
14825 // Get opcode of the non-atomic one from the specified atomic instruction.
14826 static unsigned getNonAtomicOpcode(unsigned Opc) {
14828 case X86::ATOMAND8: return X86::AND8rr;
14829 case X86::ATOMAND16: return X86::AND16rr;
14830 case X86::ATOMAND32: return X86::AND32rr;
14831 case X86::ATOMAND64: return X86::AND64rr;
14832 case X86::ATOMOR8: return X86::OR8rr;
14833 case X86::ATOMOR16: return X86::OR16rr;
14834 case X86::ATOMOR32: return X86::OR32rr;
14835 case X86::ATOMOR64: return X86::OR64rr;
14836 case X86::ATOMXOR8: return X86::XOR8rr;
14837 case X86::ATOMXOR16: return X86::XOR16rr;
14838 case X86::ATOMXOR32: return X86::XOR32rr;
14839 case X86::ATOMXOR64: return X86::XOR64rr;
14841 llvm_unreachable("Unhandled atomic-load-op opcode!");
14844 // Get opcode of the non-atomic one from the specified atomic instruction with
14846 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14847 unsigned &ExtraOpc) {
14849 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14850 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14851 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14852 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14853 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14854 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14855 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14856 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14857 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14858 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14859 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14860 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14861 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14862 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14863 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14864 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14865 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14866 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14867 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14868 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14870 llvm_unreachable("Unhandled atomic-load-op opcode!");
14873 // Get opcode of the non-atomic one from the specified atomic instruction for
14874 // 64-bit data type on 32-bit target.
14875 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14877 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14878 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14879 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14880 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14881 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14882 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14883 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14884 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14885 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14886 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14888 llvm_unreachable("Unhandled atomic-load-op opcode!");
14891 // Get opcode of the non-atomic one from the specified atomic instruction for
14892 // 64-bit data type on 32-bit target with extra opcode.
14893 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14895 unsigned &ExtraOpc) {
14897 case X86::ATOMNAND6432:
14898 ExtraOpc = X86::NOT32r;
14899 HiOpc = X86::AND32rr;
14900 return X86::AND32rr;
14902 llvm_unreachable("Unhandled atomic-load-op opcode!");
14905 // Get pseudo CMOV opcode from the specified data type.
14906 static unsigned getPseudoCMOVOpc(EVT VT) {
14907 switch (VT.getSimpleVT().SimpleTy) {
14908 case MVT::i8: return X86::CMOV_GR8;
14909 case MVT::i16: return X86::CMOV_GR16;
14910 case MVT::i32: return X86::CMOV_GR32;
14914 llvm_unreachable("Unknown CMOV opcode!");
14917 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14918 // They will be translated into a spin-loop or compare-exchange loop from
14921 // dst = atomic-fetch-op MI.addr, MI.val
14927 // t1 = LOAD MI.addr
14929 // t4 = phi(t1, t3 / loop)
14930 // t2 = OP MI.val, t4
14932 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14938 MachineBasicBlock *
14939 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14940 MachineBasicBlock *MBB) const {
14941 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14942 DebugLoc DL = MI->getDebugLoc();
14944 MachineFunction *MF = MBB->getParent();
14945 MachineRegisterInfo &MRI = MF->getRegInfo();
14947 const BasicBlock *BB = MBB->getBasicBlock();
14948 MachineFunction::iterator I = MBB;
14951 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14952 "Unexpected number of operands");
14954 assert(MI->hasOneMemOperand() &&
14955 "Expected atomic-load-op to have one memoperand");
14957 // Memory Reference
14958 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14959 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14961 unsigned DstReg, SrcReg;
14962 unsigned MemOpndSlot;
14964 unsigned CurOp = 0;
14966 DstReg = MI->getOperand(CurOp++).getReg();
14967 MemOpndSlot = CurOp;
14968 CurOp += X86::AddrNumOperands;
14969 SrcReg = MI->getOperand(CurOp++).getReg();
14971 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14972 MVT::SimpleValueType VT = *RC->vt_begin();
14973 unsigned t1 = MRI.createVirtualRegister(RC);
14974 unsigned t2 = MRI.createVirtualRegister(RC);
14975 unsigned t3 = MRI.createVirtualRegister(RC);
14976 unsigned t4 = MRI.createVirtualRegister(RC);
14977 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14979 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14980 unsigned LOADOpc = getLoadOpcode(VT);
14982 // For the atomic load-arith operator, we generate
14985 // t1 = LOAD [MI.addr]
14987 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
14988 // t1 = OP MI.val, EAX
14990 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14996 MachineBasicBlock *thisMBB = MBB;
14997 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14998 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14999 MF->insert(I, mainMBB);
15000 MF->insert(I, sinkMBB);
15002 MachineInstrBuilder MIB;
15004 // Transfer the remainder of BB and its successor edges to sinkMBB.
15005 sinkMBB->splice(sinkMBB->begin(), MBB,
15006 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15007 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15010 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15011 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15012 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15014 NewMO.setIsKill(false);
15015 MIB.addOperand(NewMO);
15017 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15018 unsigned flags = (*MMOI)->getFlags();
15019 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15020 MachineMemOperand *MMO =
15021 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15022 (*MMOI)->getSize(),
15023 (*MMOI)->getBaseAlignment(),
15024 (*MMOI)->getTBAAInfo(),
15025 (*MMOI)->getRanges());
15026 MIB.addMemOperand(MMO);
15029 thisMBB->addSuccessor(mainMBB);
15032 MachineBasicBlock *origMainMBB = mainMBB;
15035 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15036 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15038 unsigned Opc = MI->getOpcode();
15041 llvm_unreachable("Unhandled atomic-load-op opcode!");
15042 case X86::ATOMAND8:
15043 case X86::ATOMAND16:
15044 case X86::ATOMAND32:
15045 case X86::ATOMAND64:
15047 case X86::ATOMOR16:
15048 case X86::ATOMOR32:
15049 case X86::ATOMOR64:
15050 case X86::ATOMXOR8:
15051 case X86::ATOMXOR16:
15052 case X86::ATOMXOR32:
15053 case X86::ATOMXOR64: {
15054 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15055 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15059 case X86::ATOMNAND8:
15060 case X86::ATOMNAND16:
15061 case X86::ATOMNAND32:
15062 case X86::ATOMNAND64: {
15063 unsigned Tmp = MRI.createVirtualRegister(RC);
15065 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15066 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15068 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15071 case X86::ATOMMAX8:
15072 case X86::ATOMMAX16:
15073 case X86::ATOMMAX32:
15074 case X86::ATOMMAX64:
15075 case X86::ATOMMIN8:
15076 case X86::ATOMMIN16:
15077 case X86::ATOMMIN32:
15078 case X86::ATOMMIN64:
15079 case X86::ATOMUMAX8:
15080 case X86::ATOMUMAX16:
15081 case X86::ATOMUMAX32:
15082 case X86::ATOMUMAX64:
15083 case X86::ATOMUMIN8:
15084 case X86::ATOMUMIN16:
15085 case X86::ATOMUMIN32:
15086 case X86::ATOMUMIN64: {
15088 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15090 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15094 if (Subtarget->hasCMov()) {
15095 if (VT != MVT::i8) {
15097 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15101 // Promote i8 to i32 to use CMOV32
15102 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15103 const TargetRegisterClass *RC32 =
15104 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15105 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15106 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15107 unsigned Tmp = MRI.createVirtualRegister(RC32);
15109 unsigned Undef = MRI.createVirtualRegister(RC32);
15110 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15112 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15115 .addImm(X86::sub_8bit);
15116 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15119 .addImm(X86::sub_8bit);
15121 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15125 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15126 .addReg(Tmp, 0, X86::sub_8bit);
15129 // Use pseudo select and lower them.
15130 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15131 "Invalid atomic-load-op transformation!");
15132 unsigned SelOpc = getPseudoCMOVOpc(VT);
15133 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15134 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15135 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15136 .addReg(SrcReg).addReg(t4)
15138 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15139 // Replace the original PHI node as mainMBB is changed after CMOV
15141 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15142 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15143 Phi->eraseFromParent();
15149 // Copy PhyReg back from virtual register.
15150 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15153 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15154 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15155 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15157 NewMO.setIsKill(false);
15158 MIB.addOperand(NewMO);
15161 MIB.setMemRefs(MMOBegin, MMOEnd);
15163 // Copy PhyReg back to virtual register.
15164 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15167 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15169 mainMBB->addSuccessor(origMainMBB);
15170 mainMBB->addSuccessor(sinkMBB);
15173 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15174 TII->get(TargetOpcode::COPY), DstReg)
15177 MI->eraseFromParent();
15181 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15182 // instructions. They will be translated into a spin-loop or compare-exchange
15186 // dst = atomic-fetch-op MI.addr, MI.val
15192 // t1L = LOAD [MI.addr + 0]
15193 // t1H = LOAD [MI.addr + 4]
15195 // t4L = phi(t1L, t3L / loop)
15196 // t4H = phi(t1H, t3H / loop)
15197 // t2L = OP MI.val.lo, t4L
15198 // t2H = OP MI.val.hi, t4H
15203 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15211 MachineBasicBlock *
15212 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15213 MachineBasicBlock *MBB) const {
15214 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15215 DebugLoc DL = MI->getDebugLoc();
15217 MachineFunction *MF = MBB->getParent();
15218 MachineRegisterInfo &MRI = MF->getRegInfo();
15220 const BasicBlock *BB = MBB->getBasicBlock();
15221 MachineFunction::iterator I = MBB;
15224 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15225 "Unexpected number of operands");
15227 assert(MI->hasOneMemOperand() &&
15228 "Expected atomic-load-op32 to have one memoperand");
15230 // Memory Reference
15231 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15232 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15234 unsigned DstLoReg, DstHiReg;
15235 unsigned SrcLoReg, SrcHiReg;
15236 unsigned MemOpndSlot;
15238 unsigned CurOp = 0;
15240 DstLoReg = MI->getOperand(CurOp++).getReg();
15241 DstHiReg = MI->getOperand(CurOp++).getReg();
15242 MemOpndSlot = CurOp;
15243 CurOp += X86::AddrNumOperands;
15244 SrcLoReg = MI->getOperand(CurOp++).getReg();
15245 SrcHiReg = MI->getOperand(CurOp++).getReg();
15247 const TargetRegisterClass *RC = &X86::GR32RegClass;
15248 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15250 unsigned t1L = MRI.createVirtualRegister(RC);
15251 unsigned t1H = MRI.createVirtualRegister(RC);
15252 unsigned t2L = MRI.createVirtualRegister(RC);
15253 unsigned t2H = MRI.createVirtualRegister(RC);
15254 unsigned t3L = MRI.createVirtualRegister(RC);
15255 unsigned t3H = MRI.createVirtualRegister(RC);
15256 unsigned t4L = MRI.createVirtualRegister(RC);
15257 unsigned t4H = MRI.createVirtualRegister(RC);
15259 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15260 unsigned LOADOpc = X86::MOV32rm;
15262 // For the atomic load-arith operator, we generate
15265 // t1L = LOAD [MI.addr + 0]
15266 // t1H = LOAD [MI.addr + 4]
15268 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15269 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15270 // t2L = OP MI.val.lo, t4L
15271 // t2H = OP MI.val.hi, t4H
15274 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15282 MachineBasicBlock *thisMBB = MBB;
15283 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15284 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15285 MF->insert(I, mainMBB);
15286 MF->insert(I, sinkMBB);
15288 MachineInstrBuilder MIB;
15290 // Transfer the remainder of BB and its successor edges to sinkMBB.
15291 sinkMBB->splice(sinkMBB->begin(), MBB,
15292 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15293 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15297 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15298 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15299 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15301 NewMO.setIsKill(false);
15302 MIB.addOperand(NewMO);
15304 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15305 unsigned flags = (*MMOI)->getFlags();
15306 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15307 MachineMemOperand *MMO =
15308 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15309 (*MMOI)->getSize(),
15310 (*MMOI)->getBaseAlignment(),
15311 (*MMOI)->getTBAAInfo(),
15312 (*MMOI)->getRanges());
15313 MIB.addMemOperand(MMO);
15315 MachineInstr *LowMI = MIB;
15318 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15319 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15320 if (i == X86::AddrDisp) {
15321 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15323 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15325 NewMO.setIsKill(false);
15326 MIB.addOperand(NewMO);
15329 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15331 thisMBB->addSuccessor(mainMBB);
15334 MachineBasicBlock *origMainMBB = mainMBB;
15337 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15338 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15339 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15340 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15342 unsigned Opc = MI->getOpcode();
15345 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15346 case X86::ATOMAND6432:
15347 case X86::ATOMOR6432:
15348 case X86::ATOMXOR6432:
15349 case X86::ATOMADD6432:
15350 case X86::ATOMSUB6432: {
15352 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15353 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15355 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15359 case X86::ATOMNAND6432: {
15360 unsigned HiOpc, NOTOpc;
15361 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15362 unsigned TmpL = MRI.createVirtualRegister(RC);
15363 unsigned TmpH = MRI.createVirtualRegister(RC);
15364 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15366 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15368 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15369 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15372 case X86::ATOMMAX6432:
15373 case X86::ATOMMIN6432:
15374 case X86::ATOMUMAX6432:
15375 case X86::ATOMUMIN6432: {
15377 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15378 unsigned cL = MRI.createVirtualRegister(RC8);
15379 unsigned cH = MRI.createVirtualRegister(RC8);
15380 unsigned cL32 = MRI.createVirtualRegister(RC);
15381 unsigned cH32 = MRI.createVirtualRegister(RC);
15382 unsigned cc = MRI.createVirtualRegister(RC);
15383 // cl := cmp src_lo, lo
15384 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15385 .addReg(SrcLoReg).addReg(t4L);
15386 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15387 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15388 // ch := cmp src_hi, hi
15389 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15390 .addReg(SrcHiReg).addReg(t4H);
15391 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15392 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15393 // cc := if (src_hi == hi) ? cl : ch;
15394 if (Subtarget->hasCMov()) {
15395 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15396 .addReg(cH32).addReg(cL32);
15398 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15399 .addReg(cH32).addReg(cL32)
15400 .addImm(X86::COND_E);
15401 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15403 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15404 if (Subtarget->hasCMov()) {
15405 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15406 .addReg(SrcLoReg).addReg(t4L);
15407 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15408 .addReg(SrcHiReg).addReg(t4H);
15410 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15411 .addReg(SrcLoReg).addReg(t4L)
15412 .addImm(X86::COND_NE);
15413 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15414 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15415 // 2nd CMOV lowering.
15416 mainMBB->addLiveIn(X86::EFLAGS);
15417 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15418 .addReg(SrcHiReg).addReg(t4H)
15419 .addImm(X86::COND_NE);
15420 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15421 // Replace the original PHI node as mainMBB is changed after CMOV
15423 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15424 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15425 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15426 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15427 PhiL->eraseFromParent();
15428 PhiH->eraseFromParent();
15432 case X86::ATOMSWAP6432: {
15434 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15435 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15436 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15441 // Copy EDX:EAX back from HiReg:LoReg
15442 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15443 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15444 // Copy ECX:EBX from t1H:t1L
15445 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15446 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15448 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15449 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15450 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15452 NewMO.setIsKill(false);
15453 MIB.addOperand(NewMO);
15455 MIB.setMemRefs(MMOBegin, MMOEnd);
15457 // Copy EDX:EAX back to t3H:t3L
15458 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15459 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15461 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15463 mainMBB->addSuccessor(origMainMBB);
15464 mainMBB->addSuccessor(sinkMBB);
15467 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15468 TII->get(TargetOpcode::COPY), DstLoReg)
15470 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15471 TII->get(TargetOpcode::COPY), DstHiReg)
15474 MI->eraseFromParent();
15478 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15479 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15480 // in the .td file.
15481 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15482 const TargetInstrInfo *TII) {
15484 switch (MI->getOpcode()) {
15485 default: llvm_unreachable("illegal opcode!");
15486 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15487 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15488 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15489 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15490 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15491 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15492 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15493 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15496 DebugLoc dl = MI->getDebugLoc();
15497 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15499 unsigned NumArgs = MI->getNumOperands();
15500 for (unsigned i = 1; i < NumArgs; ++i) {
15501 MachineOperand &Op = MI->getOperand(i);
15502 if (!(Op.isReg() && Op.isImplicit()))
15503 MIB.addOperand(Op);
15505 if (MI->hasOneMemOperand())
15506 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15508 BuildMI(*BB, MI, dl,
15509 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15510 .addReg(X86::XMM0);
15512 MI->eraseFromParent();
15516 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15517 // defs in an instruction pattern
15518 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15519 const TargetInstrInfo *TII) {
15521 switch (MI->getOpcode()) {
15522 default: llvm_unreachable("illegal opcode!");
15523 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15524 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15525 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15526 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15527 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15528 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15529 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15530 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15533 DebugLoc dl = MI->getDebugLoc();
15534 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15536 unsigned NumArgs = MI->getNumOperands(); // remove the results
15537 for (unsigned i = 1; i < NumArgs; ++i) {
15538 MachineOperand &Op = MI->getOperand(i);
15539 if (!(Op.isReg() && Op.isImplicit()))
15540 MIB.addOperand(Op);
15542 if (MI->hasOneMemOperand())
15543 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15545 BuildMI(*BB, MI, dl,
15546 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15549 MI->eraseFromParent();
15553 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15554 const TargetInstrInfo *TII,
15555 const X86Subtarget* Subtarget) {
15556 DebugLoc dl = MI->getDebugLoc();
15558 // Address into RAX/EAX, other two args into ECX, EDX.
15559 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15560 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15561 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15562 for (int i = 0; i < X86::AddrNumOperands; ++i)
15563 MIB.addOperand(MI->getOperand(i));
15565 unsigned ValOps = X86::AddrNumOperands;
15566 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15567 .addReg(MI->getOperand(ValOps).getReg());
15568 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15569 .addReg(MI->getOperand(ValOps+1).getReg());
15571 // The instruction doesn't actually take any operands though.
15572 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15574 MI->eraseFromParent(); // The pseudo is gone now.
15578 MachineBasicBlock *
15579 X86TargetLowering::EmitVAARG64WithCustomInserter(
15581 MachineBasicBlock *MBB) const {
15582 // Emit va_arg instruction on X86-64.
15584 // Operands to this pseudo-instruction:
15585 // 0 ) Output : destination address (reg)
15586 // 1-5) Input : va_list address (addr, i64mem)
15587 // 6 ) ArgSize : Size (in bytes) of vararg type
15588 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15589 // 8 ) Align : Alignment of type
15590 // 9 ) EFLAGS (implicit-def)
15592 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15593 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15595 unsigned DestReg = MI->getOperand(0).getReg();
15596 MachineOperand &Base = MI->getOperand(1);
15597 MachineOperand &Scale = MI->getOperand(2);
15598 MachineOperand &Index = MI->getOperand(3);
15599 MachineOperand &Disp = MI->getOperand(4);
15600 MachineOperand &Segment = MI->getOperand(5);
15601 unsigned ArgSize = MI->getOperand(6).getImm();
15602 unsigned ArgMode = MI->getOperand(7).getImm();
15603 unsigned Align = MI->getOperand(8).getImm();
15605 // Memory Reference
15606 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15607 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15608 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15610 // Machine Information
15611 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15612 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15613 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15614 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15615 DebugLoc DL = MI->getDebugLoc();
15617 // struct va_list {
15620 // i64 overflow_area (address)
15621 // i64 reg_save_area (address)
15623 // sizeof(va_list) = 24
15624 // alignment(va_list) = 8
15626 unsigned TotalNumIntRegs = 6;
15627 unsigned TotalNumXMMRegs = 8;
15628 bool UseGPOffset = (ArgMode == 1);
15629 bool UseFPOffset = (ArgMode == 2);
15630 unsigned MaxOffset = TotalNumIntRegs * 8 +
15631 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15633 /* Align ArgSize to a multiple of 8 */
15634 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15635 bool NeedsAlign = (Align > 8);
15637 MachineBasicBlock *thisMBB = MBB;
15638 MachineBasicBlock *overflowMBB;
15639 MachineBasicBlock *offsetMBB;
15640 MachineBasicBlock *endMBB;
15642 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15643 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15644 unsigned OffsetReg = 0;
15646 if (!UseGPOffset && !UseFPOffset) {
15647 // If we only pull from the overflow region, we don't create a branch.
15648 // We don't need to alter control flow.
15649 OffsetDestReg = 0; // unused
15650 OverflowDestReg = DestReg;
15653 overflowMBB = thisMBB;
15656 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15657 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15658 // If not, pull from overflow_area. (branch to overflowMBB)
15663 // offsetMBB overflowMBB
15668 // Registers for the PHI in endMBB
15669 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15670 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15672 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15673 MachineFunction *MF = MBB->getParent();
15674 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15675 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15676 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15678 MachineFunction::iterator MBBIter = MBB;
15681 // Insert the new basic blocks
15682 MF->insert(MBBIter, offsetMBB);
15683 MF->insert(MBBIter, overflowMBB);
15684 MF->insert(MBBIter, endMBB);
15686 // Transfer the remainder of MBB and its successor edges to endMBB.
15687 endMBB->splice(endMBB->begin(), thisMBB,
15688 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15689 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15691 // Make offsetMBB and overflowMBB successors of thisMBB
15692 thisMBB->addSuccessor(offsetMBB);
15693 thisMBB->addSuccessor(overflowMBB);
15695 // endMBB is a successor of both offsetMBB and overflowMBB
15696 offsetMBB->addSuccessor(endMBB);
15697 overflowMBB->addSuccessor(endMBB);
15699 // Load the offset value into a register
15700 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15701 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15705 .addDisp(Disp, UseFPOffset ? 4 : 0)
15706 .addOperand(Segment)
15707 .setMemRefs(MMOBegin, MMOEnd);
15709 // Check if there is enough room left to pull this argument.
15710 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15712 .addImm(MaxOffset + 8 - ArgSizeA8);
15714 // Branch to "overflowMBB" if offset >= max
15715 // Fall through to "offsetMBB" otherwise
15716 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15717 .addMBB(overflowMBB);
15720 // In offsetMBB, emit code to use the reg_save_area.
15722 assert(OffsetReg != 0);
15724 // Read the reg_save_area address.
15725 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15726 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15731 .addOperand(Segment)
15732 .setMemRefs(MMOBegin, MMOEnd);
15734 // Zero-extend the offset
15735 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15736 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15739 .addImm(X86::sub_32bit);
15741 // Add the offset to the reg_save_area to get the final address.
15742 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15743 .addReg(OffsetReg64)
15744 .addReg(RegSaveReg);
15746 // Compute the offset for the next argument
15747 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15748 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15750 .addImm(UseFPOffset ? 16 : 8);
15752 // Store it back into the va_list.
15753 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15757 .addDisp(Disp, UseFPOffset ? 4 : 0)
15758 .addOperand(Segment)
15759 .addReg(NextOffsetReg)
15760 .setMemRefs(MMOBegin, MMOEnd);
15763 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15768 // Emit code to use overflow area
15771 // Load the overflow_area address into a register.
15772 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15773 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15778 .addOperand(Segment)
15779 .setMemRefs(MMOBegin, MMOEnd);
15781 // If we need to align it, do so. Otherwise, just copy the address
15782 // to OverflowDestReg.
15784 // Align the overflow address
15785 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15786 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15788 // aligned_addr = (addr + (align-1)) & ~(align-1)
15789 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15790 .addReg(OverflowAddrReg)
15793 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15795 .addImm(~(uint64_t)(Align-1));
15797 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15798 .addReg(OverflowAddrReg);
15801 // Compute the next overflow address after this argument.
15802 // (the overflow address should be kept 8-byte aligned)
15803 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15804 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15805 .addReg(OverflowDestReg)
15806 .addImm(ArgSizeA8);
15808 // Store the new overflow address.
15809 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15814 .addOperand(Segment)
15815 .addReg(NextAddrReg)
15816 .setMemRefs(MMOBegin, MMOEnd);
15818 // If we branched, emit the PHI to the front of endMBB.
15820 BuildMI(*endMBB, endMBB->begin(), DL,
15821 TII->get(X86::PHI), DestReg)
15822 .addReg(OffsetDestReg).addMBB(offsetMBB)
15823 .addReg(OverflowDestReg).addMBB(overflowMBB);
15826 // Erase the pseudo instruction
15827 MI->eraseFromParent();
15832 MachineBasicBlock *
15833 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15835 MachineBasicBlock *MBB) const {
15836 // Emit code to save XMM registers to the stack. The ABI says that the
15837 // number of registers to save is given in %al, so it's theoretically
15838 // possible to do an indirect jump trick to avoid saving all of them,
15839 // however this code takes a simpler approach and just executes all
15840 // of the stores if %al is non-zero. It's less code, and it's probably
15841 // easier on the hardware branch predictor, and stores aren't all that
15842 // expensive anyway.
15844 // Create the new basic blocks. One block contains all the XMM stores,
15845 // and one block is the final destination regardless of whether any
15846 // stores were performed.
15847 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15848 MachineFunction *F = MBB->getParent();
15849 MachineFunction::iterator MBBIter = MBB;
15851 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15852 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15853 F->insert(MBBIter, XMMSaveMBB);
15854 F->insert(MBBIter, EndMBB);
15856 // Transfer the remainder of MBB and its successor edges to EndMBB.
15857 EndMBB->splice(EndMBB->begin(), MBB,
15858 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15859 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15861 // The original block will now fall through to the XMM save block.
15862 MBB->addSuccessor(XMMSaveMBB);
15863 // The XMMSaveMBB will fall through to the end block.
15864 XMMSaveMBB->addSuccessor(EndMBB);
15866 // Now add the instructions.
15867 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15868 DebugLoc DL = MI->getDebugLoc();
15870 unsigned CountReg = MI->getOperand(0).getReg();
15871 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15872 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15874 if (!Subtarget->isTargetWin64()) {
15875 // If %al is 0, branch around the XMM save block.
15876 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15877 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15878 MBB->addSuccessor(EndMBB);
15881 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15882 // that was just emitted, but clearly shouldn't be "saved".
15883 assert((MI->getNumOperands() <= 3 ||
15884 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15885 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15886 && "Expected last argument to be EFLAGS");
15887 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15888 // In the XMM save block, save all the XMM argument registers.
15889 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15890 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15891 MachineMemOperand *MMO =
15892 F->getMachineMemOperand(
15893 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15894 MachineMemOperand::MOStore,
15895 /*Size=*/16, /*Align=*/16);
15896 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15897 .addFrameIndex(RegSaveFrameIndex)
15898 .addImm(/*Scale=*/1)
15899 .addReg(/*IndexReg=*/0)
15900 .addImm(/*Disp=*/Offset)
15901 .addReg(/*Segment=*/0)
15902 .addReg(MI->getOperand(i).getReg())
15903 .addMemOperand(MMO);
15906 MI->eraseFromParent(); // The pseudo instruction is gone now.
15911 // The EFLAGS operand of SelectItr might be missing a kill marker
15912 // because there were multiple uses of EFLAGS, and ISel didn't know
15913 // which to mark. Figure out whether SelectItr should have had a
15914 // kill marker, and set it if it should. Returns the correct kill
15916 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15917 MachineBasicBlock* BB,
15918 const TargetRegisterInfo* TRI) {
15919 // Scan forward through BB for a use/def of EFLAGS.
15920 MachineBasicBlock::iterator miI(std::next(SelectItr));
15921 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15922 const MachineInstr& mi = *miI;
15923 if (mi.readsRegister(X86::EFLAGS))
15925 if (mi.definesRegister(X86::EFLAGS))
15926 break; // Should have kill-flag - update below.
15929 // If we hit the end of the block, check whether EFLAGS is live into a
15931 if (miI == BB->end()) {
15932 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15933 sEnd = BB->succ_end();
15934 sItr != sEnd; ++sItr) {
15935 MachineBasicBlock* succ = *sItr;
15936 if (succ->isLiveIn(X86::EFLAGS))
15941 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15942 // out. SelectMI should have a kill flag on EFLAGS.
15943 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15947 MachineBasicBlock *
15948 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15949 MachineBasicBlock *BB) const {
15950 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15951 DebugLoc DL = MI->getDebugLoc();
15953 // To "insert" a SELECT_CC instruction, we actually have to insert the
15954 // diamond control-flow pattern. The incoming instruction knows the
15955 // destination vreg to set, the condition code register to branch on, the
15956 // true/false values to select between, and a branch opcode to use.
15957 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15958 MachineFunction::iterator It = BB;
15964 // cmpTY ccX, r1, r2
15966 // fallthrough --> copy0MBB
15967 MachineBasicBlock *thisMBB = BB;
15968 MachineFunction *F = BB->getParent();
15969 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15970 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15971 F->insert(It, copy0MBB);
15972 F->insert(It, sinkMBB);
15974 // If the EFLAGS register isn't dead in the terminator, then claim that it's
15975 // live into the sink and copy blocks.
15976 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15977 if (!MI->killsRegister(X86::EFLAGS) &&
15978 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15979 copy0MBB->addLiveIn(X86::EFLAGS);
15980 sinkMBB->addLiveIn(X86::EFLAGS);
15983 // Transfer the remainder of BB and its successor edges to sinkMBB.
15984 sinkMBB->splice(sinkMBB->begin(), BB,
15985 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15986 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15988 // Add the true and fallthrough blocks as its successors.
15989 BB->addSuccessor(copy0MBB);
15990 BB->addSuccessor(sinkMBB);
15992 // Create the conditional branch instruction.
15994 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15995 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15998 // %FalseValue = ...
15999 // # fallthrough to sinkMBB
16000 copy0MBB->addSuccessor(sinkMBB);
16003 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16005 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16006 TII->get(X86::PHI), MI->getOperand(0).getReg())
16007 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16008 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16010 MI->eraseFromParent(); // The pseudo instruction is gone now.
16014 MachineBasicBlock *
16015 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16016 bool Is64Bit) const {
16017 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16018 DebugLoc DL = MI->getDebugLoc();
16019 MachineFunction *MF = BB->getParent();
16020 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16022 assert(MF->shouldSplitStack());
16024 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16025 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16028 // ... [Till the alloca]
16029 // If stacklet is not large enough, jump to mallocMBB
16032 // Allocate by subtracting from RSP
16033 // Jump to continueMBB
16036 // Allocate by call to runtime
16040 // [rest of original BB]
16043 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16044 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16045 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16047 MachineRegisterInfo &MRI = MF->getRegInfo();
16048 const TargetRegisterClass *AddrRegClass =
16049 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16051 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16052 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16053 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16054 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16055 sizeVReg = MI->getOperand(1).getReg(),
16056 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16058 MachineFunction::iterator MBBIter = BB;
16061 MF->insert(MBBIter, bumpMBB);
16062 MF->insert(MBBIter, mallocMBB);
16063 MF->insert(MBBIter, continueMBB);
16065 continueMBB->splice(continueMBB->begin(), BB,
16066 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16067 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16069 // Add code to the main basic block to check if the stack limit has been hit,
16070 // and if so, jump to mallocMBB otherwise to bumpMBB.
16071 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16072 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16073 .addReg(tmpSPVReg).addReg(sizeVReg);
16074 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16075 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16076 .addReg(SPLimitVReg);
16077 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16079 // bumpMBB simply decreases the stack pointer, since we know the current
16080 // stacklet has enough space.
16081 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16082 .addReg(SPLimitVReg);
16083 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16084 .addReg(SPLimitVReg);
16085 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16087 // Calls into a routine in libgcc to allocate more space from the heap.
16088 const uint32_t *RegMask =
16089 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16091 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16093 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16094 .addExternalSymbol("__morestack_allocate_stack_space")
16095 .addRegMask(RegMask)
16096 .addReg(X86::RDI, RegState::Implicit)
16097 .addReg(X86::RAX, RegState::ImplicitDefine);
16099 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16101 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16102 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16103 .addExternalSymbol("__morestack_allocate_stack_space")
16104 .addRegMask(RegMask)
16105 .addReg(X86::EAX, RegState::ImplicitDefine);
16109 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16112 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16113 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16114 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16116 // Set up the CFG correctly.
16117 BB->addSuccessor(bumpMBB);
16118 BB->addSuccessor(mallocMBB);
16119 mallocMBB->addSuccessor(continueMBB);
16120 bumpMBB->addSuccessor(continueMBB);
16122 // Take care of the PHI nodes.
16123 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16124 MI->getOperand(0).getReg())
16125 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16126 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16128 // Delete the original pseudo instruction.
16129 MI->eraseFromParent();
16132 return continueMBB;
16135 MachineBasicBlock *
16136 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16137 MachineBasicBlock *BB) const {
16138 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16139 DebugLoc DL = MI->getDebugLoc();
16141 assert(!Subtarget->isTargetMacho());
16143 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16144 // non-trivial part is impdef of ESP.
16146 if (Subtarget->isTargetWin64()) {
16147 if (Subtarget->isTargetCygMing()) {
16148 // ___chkstk(Mingw64):
16149 // Clobbers R10, R11, RAX and EFLAGS.
16151 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16152 .addExternalSymbol("___chkstk")
16153 .addReg(X86::RAX, RegState::Implicit)
16154 .addReg(X86::RSP, RegState::Implicit)
16155 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16156 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16157 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16159 // __chkstk(MSVCRT): does not update stack pointer.
16160 // Clobbers R10, R11 and EFLAGS.
16161 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16162 .addExternalSymbol("__chkstk")
16163 .addReg(X86::RAX, RegState::Implicit)
16164 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16165 // RAX has the offset to be subtracted from RSP.
16166 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16171 const char *StackProbeSymbol =
16172 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16174 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16175 .addExternalSymbol(StackProbeSymbol)
16176 .addReg(X86::EAX, RegState::Implicit)
16177 .addReg(X86::ESP, RegState::Implicit)
16178 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16179 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16180 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16183 MI->eraseFromParent(); // The pseudo instruction is gone now.
16187 MachineBasicBlock *
16188 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16189 MachineBasicBlock *BB) const {
16190 // This is pretty easy. We're taking the value that we received from
16191 // our load from the relocation, sticking it in either RDI (x86-64)
16192 // or EAX and doing an indirect call. The return value will then
16193 // be in the normal return register.
16194 const X86InstrInfo *TII
16195 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16196 DebugLoc DL = MI->getDebugLoc();
16197 MachineFunction *F = BB->getParent();
16199 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16200 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16202 // Get a register mask for the lowered call.
16203 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16204 // proper register mask.
16205 const uint32_t *RegMask =
16206 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16207 if (Subtarget->is64Bit()) {
16208 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16209 TII->get(X86::MOV64rm), X86::RDI)
16211 .addImm(0).addReg(0)
16212 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16213 MI->getOperand(3).getTargetFlags())
16215 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16216 addDirectMem(MIB, X86::RDI);
16217 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16218 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16219 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16220 TII->get(X86::MOV32rm), X86::EAX)
16222 .addImm(0).addReg(0)
16223 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16224 MI->getOperand(3).getTargetFlags())
16226 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16227 addDirectMem(MIB, X86::EAX);
16228 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16230 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16231 TII->get(X86::MOV32rm), X86::EAX)
16232 .addReg(TII->getGlobalBaseReg(F))
16233 .addImm(0).addReg(0)
16234 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16235 MI->getOperand(3).getTargetFlags())
16237 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16238 addDirectMem(MIB, X86::EAX);
16239 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16242 MI->eraseFromParent(); // The pseudo instruction is gone now.
16246 MachineBasicBlock *
16247 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16248 MachineBasicBlock *MBB) const {
16249 DebugLoc DL = MI->getDebugLoc();
16250 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16252 MachineFunction *MF = MBB->getParent();
16253 MachineRegisterInfo &MRI = MF->getRegInfo();
16255 const BasicBlock *BB = MBB->getBasicBlock();
16256 MachineFunction::iterator I = MBB;
16259 // Memory Reference
16260 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16261 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16264 unsigned MemOpndSlot = 0;
16266 unsigned CurOp = 0;
16268 DstReg = MI->getOperand(CurOp++).getReg();
16269 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16270 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16271 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16272 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16274 MemOpndSlot = CurOp;
16276 MVT PVT = getPointerTy();
16277 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16278 "Invalid Pointer Size!");
16280 // For v = setjmp(buf), we generate
16283 // buf[LabelOffset] = restoreMBB
16284 // SjLjSetup restoreMBB
16290 // v = phi(main, restore)
16295 MachineBasicBlock *thisMBB = MBB;
16296 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16297 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16298 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16299 MF->insert(I, mainMBB);
16300 MF->insert(I, sinkMBB);
16301 MF->push_back(restoreMBB);
16303 MachineInstrBuilder MIB;
16305 // Transfer the remainder of BB and its successor edges to sinkMBB.
16306 sinkMBB->splice(sinkMBB->begin(), MBB,
16307 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16308 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16311 unsigned PtrStoreOpc = 0;
16312 unsigned LabelReg = 0;
16313 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16314 Reloc::Model RM = getTargetMachine().getRelocationModel();
16315 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16316 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16318 // Prepare IP either in reg or imm.
16319 if (!UseImmLabel) {
16320 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16321 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16322 LabelReg = MRI.createVirtualRegister(PtrRC);
16323 if (Subtarget->is64Bit()) {
16324 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16328 .addMBB(restoreMBB)
16331 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16332 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16333 .addReg(XII->getGlobalBaseReg(MF))
16336 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16340 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16342 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16343 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16344 if (i == X86::AddrDisp)
16345 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16347 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16350 MIB.addReg(LabelReg);
16352 MIB.addMBB(restoreMBB);
16353 MIB.setMemRefs(MMOBegin, MMOEnd);
16355 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16356 .addMBB(restoreMBB);
16358 const X86RegisterInfo *RegInfo =
16359 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16360 MIB.addRegMask(RegInfo->getNoPreservedMask());
16361 thisMBB->addSuccessor(mainMBB);
16362 thisMBB->addSuccessor(restoreMBB);
16366 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16367 mainMBB->addSuccessor(sinkMBB);
16370 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16371 TII->get(X86::PHI), DstReg)
16372 .addReg(mainDstReg).addMBB(mainMBB)
16373 .addReg(restoreDstReg).addMBB(restoreMBB);
16376 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16377 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16378 restoreMBB->addSuccessor(sinkMBB);
16380 MI->eraseFromParent();
16384 MachineBasicBlock *
16385 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16386 MachineBasicBlock *MBB) const {
16387 DebugLoc DL = MI->getDebugLoc();
16388 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16390 MachineFunction *MF = MBB->getParent();
16391 MachineRegisterInfo &MRI = MF->getRegInfo();
16393 // Memory Reference
16394 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16395 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16397 MVT PVT = getPointerTy();
16398 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16399 "Invalid Pointer Size!");
16401 const TargetRegisterClass *RC =
16402 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16403 unsigned Tmp = MRI.createVirtualRegister(RC);
16404 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16405 const X86RegisterInfo *RegInfo =
16406 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16407 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16408 unsigned SP = RegInfo->getStackRegister();
16410 MachineInstrBuilder MIB;
16412 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16413 const int64_t SPOffset = 2 * PVT.getStoreSize();
16415 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16416 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16419 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16420 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16421 MIB.addOperand(MI->getOperand(i));
16422 MIB.setMemRefs(MMOBegin, MMOEnd);
16424 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16425 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16426 if (i == X86::AddrDisp)
16427 MIB.addDisp(MI->getOperand(i), LabelOffset);
16429 MIB.addOperand(MI->getOperand(i));
16431 MIB.setMemRefs(MMOBegin, MMOEnd);
16433 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16434 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16435 if (i == X86::AddrDisp)
16436 MIB.addDisp(MI->getOperand(i), SPOffset);
16438 MIB.addOperand(MI->getOperand(i));
16440 MIB.setMemRefs(MMOBegin, MMOEnd);
16442 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16444 MI->eraseFromParent();
16448 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16449 // accumulator loops. Writing back to the accumulator allows the coalescer
16450 // to remove extra copies in the loop.
16451 MachineBasicBlock *
16452 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16453 MachineBasicBlock *MBB) const {
16454 MachineOperand &AddendOp = MI->getOperand(3);
16456 // Bail out early if the addend isn't a register - we can't switch these.
16457 if (!AddendOp.isReg())
16460 MachineFunction &MF = *MBB->getParent();
16461 MachineRegisterInfo &MRI = MF.getRegInfo();
16463 // Check whether the addend is defined by a PHI:
16464 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16465 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16466 if (!AddendDef.isPHI())
16469 // Look for the following pattern:
16471 // %addend = phi [%entry, 0], [%loop, %result]
16473 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16477 // %addend = phi [%entry, 0], [%loop, %result]
16479 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16481 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16482 assert(AddendDef.getOperand(i).isReg());
16483 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16484 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16485 if (&PHISrcInst == MI) {
16486 // Found a matching instruction.
16487 unsigned NewFMAOpc = 0;
16488 switch (MI->getOpcode()) {
16489 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16490 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16491 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16492 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16493 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16494 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16495 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16496 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16497 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16498 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16499 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16500 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16501 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16502 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16503 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16504 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16505 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16506 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16507 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16508 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16509 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16510 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16511 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16512 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16513 default: llvm_unreachable("Unrecognized FMA variant.");
16516 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16517 MachineInstrBuilder MIB =
16518 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16519 .addOperand(MI->getOperand(0))
16520 .addOperand(MI->getOperand(3))
16521 .addOperand(MI->getOperand(2))
16522 .addOperand(MI->getOperand(1));
16523 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16524 MI->eraseFromParent();
16531 MachineBasicBlock *
16532 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16533 MachineBasicBlock *BB) const {
16534 switch (MI->getOpcode()) {
16535 default: llvm_unreachable("Unexpected instr type to insert");
16536 case X86::TAILJMPd64:
16537 case X86::TAILJMPr64:
16538 case X86::TAILJMPm64:
16539 llvm_unreachable("TAILJMP64 would not be touched here.");
16540 case X86::TCRETURNdi64:
16541 case X86::TCRETURNri64:
16542 case X86::TCRETURNmi64:
16544 case X86::WIN_ALLOCA:
16545 return EmitLoweredWinAlloca(MI, BB);
16546 case X86::SEG_ALLOCA_32:
16547 return EmitLoweredSegAlloca(MI, BB, false);
16548 case X86::SEG_ALLOCA_64:
16549 return EmitLoweredSegAlloca(MI, BB, true);
16550 case X86::TLSCall_32:
16551 case X86::TLSCall_64:
16552 return EmitLoweredTLSCall(MI, BB);
16553 case X86::CMOV_GR8:
16554 case X86::CMOV_FR32:
16555 case X86::CMOV_FR64:
16556 case X86::CMOV_V4F32:
16557 case X86::CMOV_V2F64:
16558 case X86::CMOV_V2I64:
16559 case X86::CMOV_V8F32:
16560 case X86::CMOV_V4F64:
16561 case X86::CMOV_V4I64:
16562 case X86::CMOV_V16F32:
16563 case X86::CMOV_V8F64:
16564 case X86::CMOV_V8I64:
16565 case X86::CMOV_GR16:
16566 case X86::CMOV_GR32:
16567 case X86::CMOV_RFP32:
16568 case X86::CMOV_RFP64:
16569 case X86::CMOV_RFP80:
16570 return EmitLoweredSelect(MI, BB);
16572 case X86::FP32_TO_INT16_IN_MEM:
16573 case X86::FP32_TO_INT32_IN_MEM:
16574 case X86::FP32_TO_INT64_IN_MEM:
16575 case X86::FP64_TO_INT16_IN_MEM:
16576 case X86::FP64_TO_INT32_IN_MEM:
16577 case X86::FP64_TO_INT64_IN_MEM:
16578 case X86::FP80_TO_INT16_IN_MEM:
16579 case X86::FP80_TO_INT32_IN_MEM:
16580 case X86::FP80_TO_INT64_IN_MEM: {
16581 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16582 DebugLoc DL = MI->getDebugLoc();
16584 // Change the floating point control register to use "round towards zero"
16585 // mode when truncating to an integer value.
16586 MachineFunction *F = BB->getParent();
16587 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16588 addFrameReference(BuildMI(*BB, MI, DL,
16589 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16591 // Load the old value of the high byte of the control word...
16593 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16594 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16597 // Set the high part to be round to zero...
16598 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16601 // Reload the modified control word now...
16602 addFrameReference(BuildMI(*BB, MI, DL,
16603 TII->get(X86::FLDCW16m)), CWFrameIdx);
16605 // Restore the memory image of control word to original value
16606 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16609 // Get the X86 opcode to use.
16611 switch (MI->getOpcode()) {
16612 default: llvm_unreachable("illegal opcode!");
16613 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16614 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16615 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16616 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16617 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16618 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16619 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16620 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16621 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16625 MachineOperand &Op = MI->getOperand(0);
16627 AM.BaseType = X86AddressMode::RegBase;
16628 AM.Base.Reg = Op.getReg();
16630 AM.BaseType = X86AddressMode::FrameIndexBase;
16631 AM.Base.FrameIndex = Op.getIndex();
16633 Op = MI->getOperand(1);
16635 AM.Scale = Op.getImm();
16636 Op = MI->getOperand(2);
16638 AM.IndexReg = Op.getImm();
16639 Op = MI->getOperand(3);
16640 if (Op.isGlobal()) {
16641 AM.GV = Op.getGlobal();
16643 AM.Disp = Op.getImm();
16645 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16646 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16648 // Reload the original control word now.
16649 addFrameReference(BuildMI(*BB, MI, DL,
16650 TII->get(X86::FLDCW16m)), CWFrameIdx);
16652 MI->eraseFromParent(); // The pseudo instruction is gone now.
16655 // String/text processing lowering.
16656 case X86::PCMPISTRM128REG:
16657 case X86::VPCMPISTRM128REG:
16658 case X86::PCMPISTRM128MEM:
16659 case X86::VPCMPISTRM128MEM:
16660 case X86::PCMPESTRM128REG:
16661 case X86::VPCMPESTRM128REG:
16662 case X86::PCMPESTRM128MEM:
16663 case X86::VPCMPESTRM128MEM:
16664 assert(Subtarget->hasSSE42() &&
16665 "Target must have SSE4.2 or AVX features enabled");
16666 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16668 // String/text processing lowering.
16669 case X86::PCMPISTRIREG:
16670 case X86::VPCMPISTRIREG:
16671 case X86::PCMPISTRIMEM:
16672 case X86::VPCMPISTRIMEM:
16673 case X86::PCMPESTRIREG:
16674 case X86::VPCMPESTRIREG:
16675 case X86::PCMPESTRIMEM:
16676 case X86::VPCMPESTRIMEM:
16677 assert(Subtarget->hasSSE42() &&
16678 "Target must have SSE4.2 or AVX features enabled");
16679 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16681 // Thread synchronization.
16683 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16687 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16689 // Atomic Lowering.
16690 case X86::ATOMAND8:
16691 case X86::ATOMAND16:
16692 case X86::ATOMAND32:
16693 case X86::ATOMAND64:
16696 case X86::ATOMOR16:
16697 case X86::ATOMOR32:
16698 case X86::ATOMOR64:
16700 case X86::ATOMXOR16:
16701 case X86::ATOMXOR8:
16702 case X86::ATOMXOR32:
16703 case X86::ATOMXOR64:
16705 case X86::ATOMNAND8:
16706 case X86::ATOMNAND16:
16707 case X86::ATOMNAND32:
16708 case X86::ATOMNAND64:
16710 case X86::ATOMMAX8:
16711 case X86::ATOMMAX16:
16712 case X86::ATOMMAX32:
16713 case X86::ATOMMAX64:
16715 case X86::ATOMMIN8:
16716 case X86::ATOMMIN16:
16717 case X86::ATOMMIN32:
16718 case X86::ATOMMIN64:
16720 case X86::ATOMUMAX8:
16721 case X86::ATOMUMAX16:
16722 case X86::ATOMUMAX32:
16723 case X86::ATOMUMAX64:
16725 case X86::ATOMUMIN8:
16726 case X86::ATOMUMIN16:
16727 case X86::ATOMUMIN32:
16728 case X86::ATOMUMIN64:
16729 return EmitAtomicLoadArith(MI, BB);
16731 // This group does 64-bit operations on a 32-bit host.
16732 case X86::ATOMAND6432:
16733 case X86::ATOMOR6432:
16734 case X86::ATOMXOR6432:
16735 case X86::ATOMNAND6432:
16736 case X86::ATOMADD6432:
16737 case X86::ATOMSUB6432:
16738 case X86::ATOMMAX6432:
16739 case X86::ATOMMIN6432:
16740 case X86::ATOMUMAX6432:
16741 case X86::ATOMUMIN6432:
16742 case X86::ATOMSWAP6432:
16743 return EmitAtomicLoadArith6432(MI, BB);
16745 case X86::VASTART_SAVE_XMM_REGS:
16746 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16748 case X86::VAARG_64:
16749 return EmitVAARG64WithCustomInserter(MI, BB);
16751 case X86::EH_SjLj_SetJmp32:
16752 case X86::EH_SjLj_SetJmp64:
16753 return emitEHSjLjSetJmp(MI, BB);
16755 case X86::EH_SjLj_LongJmp32:
16756 case X86::EH_SjLj_LongJmp64:
16757 return emitEHSjLjLongJmp(MI, BB);
16759 case TargetOpcode::STACKMAP:
16760 case TargetOpcode::PATCHPOINT:
16761 return emitPatchPoint(MI, BB);
16763 case X86::VFMADDPDr213r:
16764 case X86::VFMADDPSr213r:
16765 case X86::VFMADDSDr213r:
16766 case X86::VFMADDSSr213r:
16767 case X86::VFMSUBPDr213r:
16768 case X86::VFMSUBPSr213r:
16769 case X86::VFMSUBSDr213r:
16770 case X86::VFMSUBSSr213r:
16771 case X86::VFNMADDPDr213r:
16772 case X86::VFNMADDPSr213r:
16773 case X86::VFNMADDSDr213r:
16774 case X86::VFNMADDSSr213r:
16775 case X86::VFNMSUBPDr213r:
16776 case X86::VFNMSUBPSr213r:
16777 case X86::VFNMSUBSDr213r:
16778 case X86::VFNMSUBSSr213r:
16779 case X86::VFMADDPDr213rY:
16780 case X86::VFMADDPSr213rY:
16781 case X86::VFMSUBPDr213rY:
16782 case X86::VFMSUBPSr213rY:
16783 case X86::VFNMADDPDr213rY:
16784 case X86::VFNMADDPSr213rY:
16785 case X86::VFNMSUBPDr213rY:
16786 case X86::VFNMSUBPSr213rY:
16787 return emitFMA3Instr(MI, BB);
16791 //===----------------------------------------------------------------------===//
16792 // X86 Optimization Hooks
16793 //===----------------------------------------------------------------------===//
16795 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16798 const SelectionDAG &DAG,
16799 unsigned Depth) const {
16800 unsigned BitWidth = KnownZero.getBitWidth();
16801 unsigned Opc = Op.getOpcode();
16802 assert((Opc >= ISD::BUILTIN_OP_END ||
16803 Opc == ISD::INTRINSIC_WO_CHAIN ||
16804 Opc == ISD::INTRINSIC_W_CHAIN ||
16805 Opc == ISD::INTRINSIC_VOID) &&
16806 "Should use MaskedValueIsZero if you don't know whether Op"
16807 " is a target node!");
16809 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16823 // These nodes' second result is a boolean.
16824 if (Op.getResNo() == 0)
16827 case X86ISD::SETCC:
16828 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16830 case ISD::INTRINSIC_WO_CHAIN: {
16831 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16832 unsigned NumLoBits = 0;
16835 case Intrinsic::x86_sse_movmsk_ps:
16836 case Intrinsic::x86_avx_movmsk_ps_256:
16837 case Intrinsic::x86_sse2_movmsk_pd:
16838 case Intrinsic::x86_avx_movmsk_pd_256:
16839 case Intrinsic::x86_mmx_pmovmskb:
16840 case Intrinsic::x86_sse2_pmovmskb_128:
16841 case Intrinsic::x86_avx2_pmovmskb: {
16842 // High bits of movmskp{s|d}, pmovmskb are known zero.
16844 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16845 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16846 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16847 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16848 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16849 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16850 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16851 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16853 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16862 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16864 const SelectionDAG &,
16865 unsigned Depth) const {
16866 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16867 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16868 return Op.getValueType().getScalarType().getSizeInBits();
16874 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16875 /// node is a GlobalAddress + offset.
16876 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16877 const GlobalValue* &GA,
16878 int64_t &Offset) const {
16879 if (N->getOpcode() == X86ISD::Wrapper) {
16880 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16881 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16882 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16886 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16889 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16890 /// same as extracting the high 128-bit part of 256-bit vector and then
16891 /// inserting the result into the low part of a new 256-bit vector
16892 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16893 EVT VT = SVOp->getValueType(0);
16894 unsigned NumElems = VT.getVectorNumElements();
16896 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16897 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16898 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16899 SVOp->getMaskElt(j) >= 0)
16905 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16906 /// same as extracting the low 128-bit part of 256-bit vector and then
16907 /// inserting the result into the high part of a new 256-bit vector
16908 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16909 EVT VT = SVOp->getValueType(0);
16910 unsigned NumElems = VT.getVectorNumElements();
16912 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16913 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16914 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16915 SVOp->getMaskElt(j) >= 0)
16921 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16922 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16923 TargetLowering::DAGCombinerInfo &DCI,
16924 const X86Subtarget* Subtarget) {
16926 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16927 SDValue V1 = SVOp->getOperand(0);
16928 SDValue V2 = SVOp->getOperand(1);
16929 EVT VT = SVOp->getValueType(0);
16930 unsigned NumElems = VT.getVectorNumElements();
16932 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16933 V2.getOpcode() == ISD::CONCAT_VECTORS) {
16937 // V UNDEF BUILD_VECTOR UNDEF
16939 // CONCAT_VECTOR CONCAT_VECTOR
16942 // RESULT: V + zero extended
16944 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16945 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16946 V1.getOperand(1).getOpcode() != ISD::UNDEF)
16949 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16952 // To match the shuffle mask, the first half of the mask should
16953 // be exactly the first vector, and all the rest a splat with the
16954 // first element of the second one.
16955 for (unsigned i = 0; i != NumElems/2; ++i)
16956 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16957 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16960 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16961 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16962 if (Ld->hasNUsesOfValue(1, 0)) {
16963 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16964 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16966 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16967 array_lengthof(Ops),
16969 Ld->getPointerInfo(),
16970 Ld->getAlignment(),
16971 false/*isVolatile*/, true/*ReadMem*/,
16972 false/*WriteMem*/);
16974 // Make sure the newly-created LOAD is in the same position as Ld in
16975 // terms of dependency. We create a TokenFactor for Ld and ResNode,
16976 // and update uses of Ld's output chain to use the TokenFactor.
16977 if (Ld->hasAnyUseOfValue(1)) {
16978 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16979 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16980 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16981 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16982 SDValue(ResNode.getNode(), 1));
16985 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16989 // Emit a zeroed vector and insert the desired subvector on its
16991 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16992 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16993 return DCI.CombineTo(N, InsV);
16996 //===--------------------------------------------------------------------===//
16997 // Combine some shuffles into subvector extracts and inserts:
17000 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17001 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17002 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17003 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17004 return DCI.CombineTo(N, InsV);
17007 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17008 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17009 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17010 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17011 return DCI.CombineTo(N, InsV);
17017 /// PerformShuffleCombine - Performs several different shuffle combines.
17018 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17019 TargetLowering::DAGCombinerInfo &DCI,
17020 const X86Subtarget *Subtarget) {
17022 EVT VT = N->getValueType(0);
17024 // Don't create instructions with illegal types after legalize types has run.
17025 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17026 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17029 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17030 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17031 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17032 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17034 // Only handle 128 wide vector from here on.
17035 if (!VT.is128BitVector())
17038 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17039 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17040 // consecutive, non-overlapping, and in the right order.
17041 SmallVector<SDValue, 16> Elts;
17042 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17043 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17045 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17048 /// PerformTruncateCombine - Converts truncate operation to
17049 /// a sequence of vector shuffle operations.
17050 /// It is possible when we truncate 256-bit vector to 128-bit vector
17051 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17052 TargetLowering::DAGCombinerInfo &DCI,
17053 const X86Subtarget *Subtarget) {
17057 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17058 /// specific shuffle of a load can be folded into a single element load.
17059 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17060 /// shuffles have been customed lowered so we need to handle those here.
17061 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17062 TargetLowering::DAGCombinerInfo &DCI) {
17063 if (DCI.isBeforeLegalizeOps())
17066 SDValue InVec = N->getOperand(0);
17067 SDValue EltNo = N->getOperand(1);
17069 if (!isa<ConstantSDNode>(EltNo))
17072 EVT VT = InVec.getValueType();
17074 bool HasShuffleIntoBitcast = false;
17075 if (InVec.getOpcode() == ISD::BITCAST) {
17076 // Don't duplicate a load with other uses.
17077 if (!InVec.hasOneUse())
17079 EVT BCVT = InVec.getOperand(0).getValueType();
17080 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17082 InVec = InVec.getOperand(0);
17083 HasShuffleIntoBitcast = true;
17086 if (!isTargetShuffle(InVec.getOpcode()))
17089 // Don't duplicate a load with other uses.
17090 if (!InVec.hasOneUse())
17093 SmallVector<int, 16> ShuffleMask;
17095 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17099 // Select the input vector, guarding against out of range extract vector.
17100 unsigned NumElems = VT.getVectorNumElements();
17101 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17102 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17103 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17104 : InVec.getOperand(1);
17106 // If inputs to shuffle are the same for both ops, then allow 2 uses
17107 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17109 if (LdNode.getOpcode() == ISD::BITCAST) {
17110 // Don't duplicate a load with other uses.
17111 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17114 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17115 LdNode = LdNode.getOperand(0);
17118 if (!ISD::isNormalLoad(LdNode.getNode()))
17121 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17123 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17126 if (HasShuffleIntoBitcast) {
17127 // If there's a bitcast before the shuffle, check if the load type and
17128 // alignment is valid.
17129 unsigned Align = LN0->getAlignment();
17130 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17131 unsigned NewAlign = TLI.getDataLayout()->
17132 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17134 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17138 // All checks match so transform back to vector_shuffle so that DAG combiner
17139 // can finish the job
17142 // Create shuffle node taking into account the case that its a unary shuffle
17143 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17144 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17145 InVec.getOperand(0), Shuffle,
17147 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17148 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17152 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17153 /// generation and convert it from being a bunch of shuffles and extracts
17154 /// to a simple store and scalar loads to extract the elements.
17155 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17156 TargetLowering::DAGCombinerInfo &DCI) {
17157 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17158 if (NewOp.getNode())
17161 SDValue InputVector = N->getOperand(0);
17163 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17164 // from mmx to v2i32 has a single usage.
17165 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17166 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17167 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17168 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17169 N->getValueType(0),
17170 InputVector.getNode()->getOperand(0));
17172 // Only operate on vectors of 4 elements, where the alternative shuffling
17173 // gets to be more expensive.
17174 if (InputVector.getValueType() != MVT::v4i32)
17177 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17178 // single use which is a sign-extend or zero-extend, and all elements are
17180 SmallVector<SDNode *, 4> Uses;
17181 unsigned ExtractedElements = 0;
17182 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17183 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17184 if (UI.getUse().getResNo() != InputVector.getResNo())
17187 SDNode *Extract = *UI;
17188 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17191 if (Extract->getValueType(0) != MVT::i32)
17193 if (!Extract->hasOneUse())
17195 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17196 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17198 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17201 // Record which element was extracted.
17202 ExtractedElements |=
17203 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17205 Uses.push_back(Extract);
17208 // If not all the elements were used, this may not be worthwhile.
17209 if (ExtractedElements != 15)
17212 // Ok, we've now decided to do the transformation.
17213 SDLoc dl(InputVector);
17215 // Store the value to a temporary stack slot.
17216 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17217 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17218 MachinePointerInfo(), false, false, 0);
17220 // Replace each use (extract) with a load of the appropriate element.
17221 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17222 UE = Uses.end(); UI != UE; ++UI) {
17223 SDNode *Extract = *UI;
17225 // cOMpute the element's address.
17226 SDValue Idx = Extract->getOperand(1);
17228 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17229 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17230 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17231 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17233 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17234 StackPtr, OffsetVal);
17236 // Load the scalar.
17237 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17238 ScalarAddr, MachinePointerInfo(),
17239 false, false, false, 0);
17241 // Replace the exact with the load.
17242 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17245 // The replacement was made in place; don't return anything.
17249 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17250 static std::pair<unsigned, bool>
17251 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17252 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17253 if (!VT.isVector())
17254 return std::make_pair(0, false);
17256 bool NeedSplit = false;
17257 switch (VT.getSimpleVT().SimpleTy) {
17258 default: return std::make_pair(0, false);
17262 if (!Subtarget->hasAVX2())
17264 if (!Subtarget->hasAVX())
17265 return std::make_pair(0, false);
17270 if (!Subtarget->hasSSE2())
17271 return std::make_pair(0, false);
17274 // SSE2 has only a small subset of the operations.
17275 bool hasUnsigned = Subtarget->hasSSE41() ||
17276 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17277 bool hasSigned = Subtarget->hasSSE41() ||
17278 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17280 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17283 // Check for x CC y ? x : y.
17284 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17285 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17290 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17293 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17296 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17299 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17301 // Check for x CC y ? y : x -- a min/max with reversed arms.
17302 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17303 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17308 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17311 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17314 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17317 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17321 return std::make_pair(Opc, NeedSplit);
17324 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17326 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17327 TargetLowering::DAGCombinerInfo &DCI,
17328 const X86Subtarget *Subtarget) {
17330 SDValue Cond = N->getOperand(0);
17331 // Get the LHS/RHS of the select.
17332 SDValue LHS = N->getOperand(1);
17333 SDValue RHS = N->getOperand(2);
17334 EVT VT = LHS.getValueType();
17335 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17337 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17338 // instructions match the semantics of the common C idiom x<y?x:y but not
17339 // x<=y?x:y, because of how they handle negative zero (which can be
17340 // ignored in unsafe-math mode).
17341 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17342 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17343 (Subtarget->hasSSE2() ||
17344 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17345 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17347 unsigned Opcode = 0;
17348 // Check for x CC y ? x : y.
17349 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17350 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17354 // Converting this to a min would handle NaNs incorrectly, and swapping
17355 // the operands would cause it to handle comparisons between positive
17356 // and negative zero incorrectly.
17357 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17358 if (!DAG.getTarget().Options.UnsafeFPMath &&
17359 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17361 std::swap(LHS, RHS);
17363 Opcode = X86ISD::FMIN;
17366 // Converting this to a min would handle comparisons between positive
17367 // and negative zero incorrectly.
17368 if (!DAG.getTarget().Options.UnsafeFPMath &&
17369 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17371 Opcode = X86ISD::FMIN;
17374 // Converting this to a min would handle both negative zeros and NaNs
17375 // incorrectly, but we can swap the operands to fix both.
17376 std::swap(LHS, RHS);
17380 Opcode = X86ISD::FMIN;
17384 // Converting this to a max would handle comparisons between positive
17385 // and negative zero incorrectly.
17386 if (!DAG.getTarget().Options.UnsafeFPMath &&
17387 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17389 Opcode = X86ISD::FMAX;
17392 // Converting this to a max would handle NaNs incorrectly, and swapping
17393 // the operands would cause it to handle comparisons between positive
17394 // and negative zero incorrectly.
17395 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17396 if (!DAG.getTarget().Options.UnsafeFPMath &&
17397 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17399 std::swap(LHS, RHS);
17401 Opcode = X86ISD::FMAX;
17404 // Converting this to a max would handle both negative zeros and NaNs
17405 // incorrectly, but we can swap the operands to fix both.
17406 std::swap(LHS, RHS);
17410 Opcode = X86ISD::FMAX;
17413 // Check for x CC y ? y : x -- a min/max with reversed arms.
17414 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17415 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17419 // Converting this to a min would handle comparisons between positive
17420 // and negative zero incorrectly, and swapping the operands would
17421 // cause it to handle NaNs incorrectly.
17422 if (!DAG.getTarget().Options.UnsafeFPMath &&
17423 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17424 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17426 std::swap(LHS, RHS);
17428 Opcode = X86ISD::FMIN;
17431 // Converting this to a min would handle NaNs incorrectly.
17432 if (!DAG.getTarget().Options.UnsafeFPMath &&
17433 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17435 Opcode = X86ISD::FMIN;
17438 // Converting this to a min would handle both negative zeros and NaNs
17439 // incorrectly, but we can swap the operands to fix both.
17440 std::swap(LHS, RHS);
17444 Opcode = X86ISD::FMIN;
17448 // Converting this to a max would handle NaNs incorrectly.
17449 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17451 Opcode = X86ISD::FMAX;
17454 // Converting this to a max would handle comparisons between positive
17455 // and negative zero incorrectly, and swapping the operands would
17456 // cause it to handle NaNs incorrectly.
17457 if (!DAG.getTarget().Options.UnsafeFPMath &&
17458 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17459 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17461 std::swap(LHS, RHS);
17463 Opcode = X86ISD::FMAX;
17466 // Converting this to a max would handle both negative zeros and NaNs
17467 // incorrectly, but we can swap the operands to fix both.
17468 std::swap(LHS, RHS);
17472 Opcode = X86ISD::FMAX;
17478 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17481 EVT CondVT = Cond.getValueType();
17482 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17483 CondVT.getVectorElementType() == MVT::i1) {
17484 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17485 // lowering on AVX-512. In this case we convert it to
17486 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17487 // The same situation for all 128 and 256-bit vectors of i8 and i16
17488 EVT OpVT = LHS.getValueType();
17489 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17490 (OpVT.getVectorElementType() == MVT::i8 ||
17491 OpVT.getVectorElementType() == MVT::i16)) {
17492 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17493 DCI.AddToWorklist(Cond.getNode());
17494 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17497 // If this is a select between two integer constants, try to do some
17499 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17500 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17501 // Don't do this for crazy integer types.
17502 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17503 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17504 // so that TrueC (the true value) is larger than FalseC.
17505 bool NeedsCondInvert = false;
17507 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17508 // Efficiently invertible.
17509 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17510 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17511 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17512 NeedsCondInvert = true;
17513 std::swap(TrueC, FalseC);
17516 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17517 if (FalseC->getAPIntValue() == 0 &&
17518 TrueC->getAPIntValue().isPowerOf2()) {
17519 if (NeedsCondInvert) // Invert the condition if needed.
17520 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17521 DAG.getConstant(1, Cond.getValueType()));
17523 // Zero extend the condition if needed.
17524 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17526 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17527 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17528 DAG.getConstant(ShAmt, MVT::i8));
17531 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17532 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17533 if (NeedsCondInvert) // Invert the condition if needed.
17534 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17535 DAG.getConstant(1, Cond.getValueType()));
17537 // Zero extend the condition if needed.
17538 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17539 FalseC->getValueType(0), Cond);
17540 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17541 SDValue(FalseC, 0));
17544 // Optimize cases that will turn into an LEA instruction. This requires
17545 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17546 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17547 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17548 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17550 bool isFastMultiplier = false;
17552 switch ((unsigned char)Diff) {
17554 case 1: // result = add base, cond
17555 case 2: // result = lea base( , cond*2)
17556 case 3: // result = lea base(cond, cond*2)
17557 case 4: // result = lea base( , cond*4)
17558 case 5: // result = lea base(cond, cond*4)
17559 case 8: // result = lea base( , cond*8)
17560 case 9: // result = lea base(cond, cond*8)
17561 isFastMultiplier = true;
17566 if (isFastMultiplier) {
17567 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17568 if (NeedsCondInvert) // Invert the condition if needed.
17569 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17570 DAG.getConstant(1, Cond.getValueType()));
17572 // Zero extend the condition if needed.
17573 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17575 // Scale the condition by the difference.
17577 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17578 DAG.getConstant(Diff, Cond.getValueType()));
17580 // Add the base if non-zero.
17581 if (FalseC->getAPIntValue() != 0)
17582 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17583 SDValue(FalseC, 0));
17590 // Canonicalize max and min:
17591 // (x > y) ? x : y -> (x >= y) ? x : y
17592 // (x < y) ? x : y -> (x <= y) ? x : y
17593 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17594 // the need for an extra compare
17595 // against zero. e.g.
17596 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17598 // testl %edi, %edi
17600 // cmovgl %edi, %eax
17604 // cmovsl %eax, %edi
17605 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17606 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17607 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17608 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17613 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17614 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17615 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17616 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17621 // Early exit check
17622 if (!TLI.isTypeLegal(VT))
17625 // Match VSELECTs into subs with unsigned saturation.
17626 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17627 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17628 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17629 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17630 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17632 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17633 // left side invert the predicate to simplify logic below.
17635 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17637 CC = ISD::getSetCCInverse(CC, true);
17638 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17642 if (Other.getNode() && Other->getNumOperands() == 2 &&
17643 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17644 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17645 SDValue CondRHS = Cond->getOperand(1);
17647 // Look for a general sub with unsigned saturation first.
17648 // x >= y ? x-y : 0 --> subus x, y
17649 // x > y ? x-y : 0 --> subus x, y
17650 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17651 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17652 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17654 // If the RHS is a constant we have to reverse the const canonicalization.
17655 // x > C-1 ? x+-C : 0 --> subus x, C
17656 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17657 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17658 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17659 if (CondRHS.getConstantOperandVal(0) == -A-1)
17660 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17661 DAG.getConstant(-A, VT));
17664 // Another special case: If C was a sign bit, the sub has been
17665 // canonicalized into a xor.
17666 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17667 // it's safe to decanonicalize the xor?
17668 // x s< 0 ? x^C : 0 --> subus x, C
17669 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17670 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17671 isSplatVector(OpRHS.getNode())) {
17672 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17674 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17679 // Try to match a min/max vector operation.
17680 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17681 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17682 unsigned Opc = ret.first;
17683 bool NeedSplit = ret.second;
17685 if (Opc && NeedSplit) {
17686 unsigned NumElems = VT.getVectorNumElements();
17687 // Extract the LHS vectors
17688 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17689 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17691 // Extract the RHS vectors
17692 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17693 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17695 // Create min/max for each subvector
17696 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17697 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17699 // Merge the result
17700 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17702 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17705 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17706 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17707 // Check if SETCC has already been promoted
17708 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17709 // Check that condition value type matches vselect operand type
17712 assert(Cond.getValueType().isVector() &&
17713 "vector select expects a vector selector!");
17715 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17716 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17718 if (!TValIsAllOnes && !FValIsAllZeros) {
17719 // Try invert the condition if true value is not all 1s and false value
17721 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17722 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17724 if (TValIsAllZeros || FValIsAllOnes) {
17725 SDValue CC = Cond.getOperand(2);
17726 ISD::CondCode NewCC =
17727 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17728 Cond.getOperand(0).getValueType().isInteger());
17729 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17730 std::swap(LHS, RHS);
17731 TValIsAllOnes = FValIsAllOnes;
17732 FValIsAllZeros = TValIsAllZeros;
17736 if (TValIsAllOnes || FValIsAllZeros) {
17739 if (TValIsAllOnes && FValIsAllZeros)
17741 else if (TValIsAllOnes)
17742 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17743 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17744 else if (FValIsAllZeros)
17745 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17746 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17748 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17752 // Try to fold this VSELECT into a MOVSS/MOVSD
17753 if (N->getOpcode() == ISD::VSELECT &&
17754 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17755 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17756 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17757 bool CanFold = false;
17758 unsigned NumElems = Cond.getNumOperands();
17762 if (isZero(Cond.getOperand(0))) {
17765 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17766 // fold (vselect <0,-1> -> (movsd A, B)
17767 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17768 CanFold = isAllOnes(Cond.getOperand(i));
17769 } else if (isAllOnes(Cond.getOperand(0))) {
17773 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17774 // fold (vselect <-1,0> -> (movsd B, A)
17775 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17776 CanFold = isZero(Cond.getOperand(i));
17780 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17781 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17782 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17785 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17786 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17787 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17788 // (v2i64 (bitcast B)))))
17790 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17791 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17792 // (v2f64 (bitcast B)))))
17794 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17795 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17796 // (v2i64 (bitcast A)))))
17798 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17799 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17800 // (v2f64 (bitcast A)))))
17802 CanFold = (isZero(Cond.getOperand(0)) &&
17803 isZero(Cond.getOperand(1)) &&
17804 isAllOnes(Cond.getOperand(2)) &&
17805 isAllOnes(Cond.getOperand(3)));
17807 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17808 isAllOnes(Cond.getOperand(1)) &&
17809 isZero(Cond.getOperand(2)) &&
17810 isZero(Cond.getOperand(3))) {
17812 std::swap(LHS, RHS);
17816 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17817 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17818 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17819 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17821 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17827 // If we know that this node is legal then we know that it is going to be
17828 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17829 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17830 // to simplify previous instructions.
17831 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17832 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17833 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17835 // Don't optimize vector selects that map to mask-registers.
17839 // Check all uses of that condition operand to check whether it will be
17840 // consumed by non-BLEND instructions, which may depend on all bits are set
17842 for (SDNode::use_iterator I = Cond->use_begin(),
17843 E = Cond->use_end(); I != E; ++I)
17844 if (I->getOpcode() != ISD::VSELECT)
17845 // TODO: Add other opcodes eventually lowered into BLEND.
17848 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17849 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17851 APInt KnownZero, KnownOne;
17852 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17853 DCI.isBeforeLegalizeOps());
17854 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17855 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17856 DCI.CommitTargetLoweringOpt(TLO);
17862 // Check whether a boolean test is testing a boolean value generated by
17863 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17866 // Simplify the following patterns:
17867 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17868 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17869 // to (Op EFLAGS Cond)
17871 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17872 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17873 // to (Op EFLAGS !Cond)
17875 // where Op could be BRCOND or CMOV.
17877 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17878 // Quit if not CMP and SUB with its value result used.
17879 if (Cmp.getOpcode() != X86ISD::CMP &&
17880 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17883 // Quit if not used as a boolean value.
17884 if (CC != X86::COND_E && CC != X86::COND_NE)
17887 // Check CMP operands. One of them should be 0 or 1 and the other should be
17888 // an SetCC or extended from it.
17889 SDValue Op1 = Cmp.getOperand(0);
17890 SDValue Op2 = Cmp.getOperand(1);
17893 const ConstantSDNode* C = 0;
17894 bool needOppositeCond = (CC == X86::COND_E);
17895 bool checkAgainstTrue = false; // Is it a comparison against 1?
17897 if ((C = dyn_cast<ConstantSDNode>(Op1)))
17899 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17901 else // Quit if all operands are not constants.
17904 if (C->getZExtValue() == 1) {
17905 needOppositeCond = !needOppositeCond;
17906 checkAgainstTrue = true;
17907 } else if (C->getZExtValue() != 0)
17908 // Quit if the constant is neither 0 or 1.
17911 bool truncatedToBoolWithAnd = false;
17912 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17913 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17914 SetCC.getOpcode() == ISD::TRUNCATE ||
17915 SetCC.getOpcode() == ISD::AND) {
17916 if (SetCC.getOpcode() == ISD::AND) {
17918 ConstantSDNode *CS;
17919 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17920 CS->getZExtValue() == 1)
17922 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17923 CS->getZExtValue() == 1)
17927 SetCC = SetCC.getOperand(OpIdx);
17928 truncatedToBoolWithAnd = true;
17930 SetCC = SetCC.getOperand(0);
17933 switch (SetCC.getOpcode()) {
17934 case X86ISD::SETCC_CARRY:
17935 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17936 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17937 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17938 // truncated to i1 using 'and'.
17939 if (checkAgainstTrue && !truncatedToBoolWithAnd)
17941 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17942 "Invalid use of SETCC_CARRY!");
17944 case X86ISD::SETCC:
17945 // Set the condition code or opposite one if necessary.
17946 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17947 if (needOppositeCond)
17948 CC = X86::GetOppositeBranchCondition(CC);
17949 return SetCC.getOperand(1);
17950 case X86ISD::CMOV: {
17951 // Check whether false/true value has canonical one, i.e. 0 or 1.
17952 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17953 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17954 // Quit if true value is not a constant.
17957 // Quit if false value is not a constant.
17959 SDValue Op = SetCC.getOperand(0);
17960 // Skip 'zext' or 'trunc' node.
17961 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17962 Op.getOpcode() == ISD::TRUNCATE)
17963 Op = Op.getOperand(0);
17964 // A special case for rdrand/rdseed, where 0 is set if false cond is
17966 if ((Op.getOpcode() != X86ISD::RDRAND &&
17967 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17970 // Quit if false value is not the constant 0 or 1.
17971 bool FValIsFalse = true;
17972 if (FVal && FVal->getZExtValue() != 0) {
17973 if (FVal->getZExtValue() != 1)
17975 // If FVal is 1, opposite cond is needed.
17976 needOppositeCond = !needOppositeCond;
17977 FValIsFalse = false;
17979 // Quit if TVal is not the constant opposite of FVal.
17980 if (FValIsFalse && TVal->getZExtValue() != 1)
17982 if (!FValIsFalse && TVal->getZExtValue() != 0)
17984 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17985 if (needOppositeCond)
17986 CC = X86::GetOppositeBranchCondition(CC);
17987 return SetCC.getOperand(3);
17994 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17995 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17996 TargetLowering::DAGCombinerInfo &DCI,
17997 const X86Subtarget *Subtarget) {
18000 // If the flag operand isn't dead, don't touch this CMOV.
18001 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18004 SDValue FalseOp = N->getOperand(0);
18005 SDValue TrueOp = N->getOperand(1);
18006 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18007 SDValue Cond = N->getOperand(3);
18009 if (CC == X86::COND_E || CC == X86::COND_NE) {
18010 switch (Cond.getOpcode()) {
18014 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18015 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18016 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18022 Flags = checkBoolTestSetCCCombine(Cond, CC);
18023 if (Flags.getNode() &&
18024 // Extra check as FCMOV only supports a subset of X86 cond.
18025 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18026 SDValue Ops[] = { FalseOp, TrueOp,
18027 DAG.getConstant(CC, MVT::i8), Flags };
18028 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
18029 Ops, array_lengthof(Ops));
18032 // If this is a select between two integer constants, try to do some
18033 // optimizations. Note that the operands are ordered the opposite of SELECT
18035 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18036 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18037 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18038 // larger than FalseC (the false value).
18039 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18040 CC = X86::GetOppositeBranchCondition(CC);
18041 std::swap(TrueC, FalseC);
18042 std::swap(TrueOp, FalseOp);
18045 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18046 // This is efficient for any integer data type (including i8/i16) and
18048 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18049 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18050 DAG.getConstant(CC, MVT::i8), Cond);
18052 // Zero extend the condition if needed.
18053 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18055 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18056 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18057 DAG.getConstant(ShAmt, MVT::i8));
18058 if (N->getNumValues() == 2) // Dead flag value?
18059 return DCI.CombineTo(N, Cond, SDValue());
18063 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18064 // for any integer data type, including i8/i16.
18065 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18066 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18067 DAG.getConstant(CC, MVT::i8), Cond);
18069 // Zero extend the condition if needed.
18070 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18071 FalseC->getValueType(0), Cond);
18072 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18073 SDValue(FalseC, 0));
18075 if (N->getNumValues() == 2) // Dead flag value?
18076 return DCI.CombineTo(N, Cond, SDValue());
18080 // Optimize cases that will turn into an LEA instruction. This requires
18081 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18082 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18083 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18084 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18086 bool isFastMultiplier = false;
18088 switch ((unsigned char)Diff) {
18090 case 1: // result = add base, cond
18091 case 2: // result = lea base( , cond*2)
18092 case 3: // result = lea base(cond, cond*2)
18093 case 4: // result = lea base( , cond*4)
18094 case 5: // result = lea base(cond, cond*4)
18095 case 8: // result = lea base( , cond*8)
18096 case 9: // result = lea base(cond, cond*8)
18097 isFastMultiplier = true;
18102 if (isFastMultiplier) {
18103 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18104 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18105 DAG.getConstant(CC, MVT::i8), Cond);
18106 // Zero extend the condition if needed.
18107 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18109 // Scale the condition by the difference.
18111 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18112 DAG.getConstant(Diff, Cond.getValueType()));
18114 // Add the base if non-zero.
18115 if (FalseC->getAPIntValue() != 0)
18116 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18117 SDValue(FalseC, 0));
18118 if (N->getNumValues() == 2) // Dead flag value?
18119 return DCI.CombineTo(N, Cond, SDValue());
18126 // Handle these cases:
18127 // (select (x != c), e, c) -> select (x != c), e, x),
18128 // (select (x == c), c, e) -> select (x == c), x, e)
18129 // where the c is an integer constant, and the "select" is the combination
18130 // of CMOV and CMP.
18132 // The rationale for this change is that the conditional-move from a constant
18133 // needs two instructions, however, conditional-move from a register needs
18134 // only one instruction.
18136 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18137 // some instruction-combining opportunities. This opt needs to be
18138 // postponed as late as possible.
18140 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18141 // the DCI.xxxx conditions are provided to postpone the optimization as
18142 // late as possible.
18144 ConstantSDNode *CmpAgainst = 0;
18145 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18146 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18147 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18149 if (CC == X86::COND_NE &&
18150 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18151 CC = X86::GetOppositeBranchCondition(CC);
18152 std::swap(TrueOp, FalseOp);
18155 if (CC == X86::COND_E &&
18156 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18157 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18158 DAG.getConstant(CC, MVT::i8), Cond };
18159 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
18160 array_lengthof(Ops));
18168 /// PerformMulCombine - Optimize a single multiply with constant into two
18169 /// in order to implement it with two cheaper instructions, e.g.
18170 /// LEA + SHL, LEA + LEA.
18171 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18172 TargetLowering::DAGCombinerInfo &DCI) {
18173 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18176 EVT VT = N->getValueType(0);
18177 if (VT != MVT::i64)
18180 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18183 uint64_t MulAmt = C->getZExtValue();
18184 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18187 uint64_t MulAmt1 = 0;
18188 uint64_t MulAmt2 = 0;
18189 if ((MulAmt % 9) == 0) {
18191 MulAmt2 = MulAmt / 9;
18192 } else if ((MulAmt % 5) == 0) {
18194 MulAmt2 = MulAmt / 5;
18195 } else if ((MulAmt % 3) == 0) {
18197 MulAmt2 = MulAmt / 3;
18200 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18203 if (isPowerOf2_64(MulAmt2) &&
18204 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18205 // If second multiplifer is pow2, issue it first. We want the multiply by
18206 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18208 std::swap(MulAmt1, MulAmt2);
18211 if (isPowerOf2_64(MulAmt1))
18212 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18213 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18215 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18216 DAG.getConstant(MulAmt1, VT));
18218 if (isPowerOf2_64(MulAmt2))
18219 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18220 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18222 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18223 DAG.getConstant(MulAmt2, VT));
18225 // Do not add new nodes to DAG combiner worklist.
18226 DCI.CombineTo(N, NewMul, false);
18231 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18232 SDValue N0 = N->getOperand(0);
18233 SDValue N1 = N->getOperand(1);
18234 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18235 EVT VT = N0.getValueType();
18237 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18238 // since the result of setcc_c is all zero's or all ones.
18239 if (VT.isInteger() && !VT.isVector() &&
18240 N1C && N0.getOpcode() == ISD::AND &&
18241 N0.getOperand(1).getOpcode() == ISD::Constant) {
18242 SDValue N00 = N0.getOperand(0);
18243 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18244 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18245 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18246 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18247 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18248 APInt ShAmt = N1C->getAPIntValue();
18249 Mask = Mask.shl(ShAmt);
18251 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18252 N00, DAG.getConstant(Mask, VT));
18256 // Hardware support for vector shifts is sparse which makes us scalarize the
18257 // vector operations in many cases. Also, on sandybridge ADD is faster than
18259 // (shl V, 1) -> add V,V
18260 if (isSplatVector(N1.getNode())) {
18261 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18262 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18263 // We shift all of the values by one. In many cases we do not have
18264 // hardware support for this operation. This is better expressed as an ADD
18266 if (N1C && (1 == N1C->getZExtValue())) {
18267 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18274 /// \brief Returns a vector of 0s if the node in input is a vector logical
18275 /// shift by a constant amount which is known to be bigger than or equal
18276 /// to the vector element size in bits.
18277 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18278 const X86Subtarget *Subtarget) {
18279 EVT VT = N->getValueType(0);
18281 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18282 (!Subtarget->hasInt256() ||
18283 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18286 SDValue Amt = N->getOperand(1);
18288 if (isSplatVector(Amt.getNode())) {
18289 SDValue SclrAmt = Amt->getOperand(0);
18290 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18291 APInt ShiftAmt = C->getAPIntValue();
18292 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18294 // SSE2/AVX2 logical shifts always return a vector of 0s
18295 // if the shift amount is bigger than or equal to
18296 // the element size. The constant shift amount will be
18297 // encoded as a 8-bit immediate.
18298 if (ShiftAmt.trunc(8).uge(MaxAmount))
18299 return getZeroVector(VT, Subtarget, DAG, DL);
18306 /// PerformShiftCombine - Combine shifts.
18307 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18308 TargetLowering::DAGCombinerInfo &DCI,
18309 const X86Subtarget *Subtarget) {
18310 if (N->getOpcode() == ISD::SHL) {
18311 SDValue V = PerformSHLCombine(N, DAG);
18312 if (V.getNode()) return V;
18315 if (N->getOpcode() != ISD::SRA) {
18316 // Try to fold this logical shift into a zero vector.
18317 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18318 if (V.getNode()) return V;
18324 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18325 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18326 // and friends. Likewise for OR -> CMPNEQSS.
18327 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18328 TargetLowering::DAGCombinerInfo &DCI,
18329 const X86Subtarget *Subtarget) {
18332 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18333 // we're requiring SSE2 for both.
18334 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18335 SDValue N0 = N->getOperand(0);
18336 SDValue N1 = N->getOperand(1);
18337 SDValue CMP0 = N0->getOperand(1);
18338 SDValue CMP1 = N1->getOperand(1);
18341 // The SETCCs should both refer to the same CMP.
18342 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18345 SDValue CMP00 = CMP0->getOperand(0);
18346 SDValue CMP01 = CMP0->getOperand(1);
18347 EVT VT = CMP00.getValueType();
18349 if (VT == MVT::f32 || VT == MVT::f64) {
18350 bool ExpectingFlags = false;
18351 // Check for any users that want flags:
18352 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18353 !ExpectingFlags && UI != UE; ++UI)
18354 switch (UI->getOpcode()) {
18359 ExpectingFlags = true;
18361 case ISD::CopyToReg:
18362 case ISD::SIGN_EXTEND:
18363 case ISD::ZERO_EXTEND:
18364 case ISD::ANY_EXTEND:
18368 if (!ExpectingFlags) {
18369 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18370 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18372 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18373 X86::CondCode tmp = cc0;
18378 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18379 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18380 // FIXME: need symbolic constants for these magic numbers.
18381 // See X86ATTInstPrinter.cpp:printSSECC().
18382 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18383 if (Subtarget->hasAVX512()) {
18384 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18385 CMP01, DAG.getConstant(x86cc, MVT::i8));
18386 if (N->getValueType(0) != MVT::i1)
18387 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18391 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18392 CMP00.getValueType(), CMP00, CMP01,
18393 DAG.getConstant(x86cc, MVT::i8));
18395 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18396 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18398 if (is64BitFP && !Subtarget->is64Bit()) {
18399 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18400 // 64-bit integer, since that's not a legal type. Since
18401 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18402 // bits, but can do this little dance to extract the lowest 32 bits
18403 // and work with those going forward.
18404 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18406 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18408 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18409 Vector32, DAG.getIntPtrConstant(0));
18413 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18414 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18415 DAG.getConstant(1, IntVT));
18416 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18417 return OneBitOfTruth;
18425 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18426 /// so it can be folded inside ANDNP.
18427 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18428 EVT VT = N->getValueType(0);
18430 // Match direct AllOnes for 128 and 256-bit vectors
18431 if (ISD::isBuildVectorAllOnes(N))
18434 // Look through a bit convert.
18435 if (N->getOpcode() == ISD::BITCAST)
18436 N = N->getOperand(0).getNode();
18438 // Sometimes the operand may come from a insert_subvector building a 256-bit
18440 if (VT.is256BitVector() &&
18441 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18442 SDValue V1 = N->getOperand(0);
18443 SDValue V2 = N->getOperand(1);
18445 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18446 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18447 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18448 ISD::isBuildVectorAllOnes(V2.getNode()))
18455 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18456 // register. In most cases we actually compare or select YMM-sized registers
18457 // and mixing the two types creates horrible code. This method optimizes
18458 // some of the transition sequences.
18459 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18460 TargetLowering::DAGCombinerInfo &DCI,
18461 const X86Subtarget *Subtarget) {
18462 EVT VT = N->getValueType(0);
18463 if (!VT.is256BitVector())
18466 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18467 N->getOpcode() == ISD::ZERO_EXTEND ||
18468 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18470 SDValue Narrow = N->getOperand(0);
18471 EVT NarrowVT = Narrow->getValueType(0);
18472 if (!NarrowVT.is128BitVector())
18475 if (Narrow->getOpcode() != ISD::XOR &&
18476 Narrow->getOpcode() != ISD::AND &&
18477 Narrow->getOpcode() != ISD::OR)
18480 SDValue N0 = Narrow->getOperand(0);
18481 SDValue N1 = Narrow->getOperand(1);
18484 // The Left side has to be a trunc.
18485 if (N0.getOpcode() != ISD::TRUNCATE)
18488 // The type of the truncated inputs.
18489 EVT WideVT = N0->getOperand(0)->getValueType(0);
18493 // The right side has to be a 'trunc' or a constant vector.
18494 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18495 bool RHSConst = (isSplatVector(N1.getNode()) &&
18496 isa<ConstantSDNode>(N1->getOperand(0)));
18497 if (!RHSTrunc && !RHSConst)
18500 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18502 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18505 // Set N0 and N1 to hold the inputs to the new wide operation.
18506 N0 = N0->getOperand(0);
18508 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18509 N1->getOperand(0));
18510 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18511 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18512 } else if (RHSTrunc) {
18513 N1 = N1->getOperand(0);
18516 // Generate the wide operation.
18517 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18518 unsigned Opcode = N->getOpcode();
18520 case ISD::ANY_EXTEND:
18522 case ISD::ZERO_EXTEND: {
18523 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18524 APInt Mask = APInt::getAllOnesValue(InBits);
18525 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18526 return DAG.getNode(ISD::AND, DL, VT,
18527 Op, DAG.getConstant(Mask, VT));
18529 case ISD::SIGN_EXTEND:
18530 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18531 Op, DAG.getValueType(NarrowVT));
18533 llvm_unreachable("Unexpected opcode");
18537 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18538 TargetLowering::DAGCombinerInfo &DCI,
18539 const X86Subtarget *Subtarget) {
18540 EVT VT = N->getValueType(0);
18541 if (DCI.isBeforeLegalizeOps())
18544 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18548 // Create BEXTR instructions
18549 // BEXTR is ((X >> imm) & (2**size-1))
18550 if (VT == MVT::i32 || VT == MVT::i64) {
18551 SDValue N0 = N->getOperand(0);
18552 SDValue N1 = N->getOperand(1);
18555 // Check for BEXTR.
18556 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18557 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18558 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18559 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18560 if (MaskNode && ShiftNode) {
18561 uint64_t Mask = MaskNode->getZExtValue();
18562 uint64_t Shift = ShiftNode->getZExtValue();
18563 if (isMask_64(Mask)) {
18564 uint64_t MaskSize = CountPopulation_64(Mask);
18565 if (Shift + MaskSize <= VT.getSizeInBits())
18566 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18567 DAG.getConstant(Shift | (MaskSize << 8), VT));
18575 // Want to form ANDNP nodes:
18576 // 1) In the hopes of then easily combining them with OR and AND nodes
18577 // to form PBLEND/PSIGN.
18578 // 2) To match ANDN packed intrinsics
18579 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18582 SDValue N0 = N->getOperand(0);
18583 SDValue N1 = N->getOperand(1);
18586 // Check LHS for vnot
18587 if (N0.getOpcode() == ISD::XOR &&
18588 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18589 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18590 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18592 // Check RHS for vnot
18593 if (N1.getOpcode() == ISD::XOR &&
18594 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18595 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18596 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18601 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18602 TargetLowering::DAGCombinerInfo &DCI,
18603 const X86Subtarget *Subtarget) {
18604 if (DCI.isBeforeLegalizeOps())
18607 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18611 SDValue N0 = N->getOperand(0);
18612 SDValue N1 = N->getOperand(1);
18613 EVT VT = N->getValueType(0);
18615 // look for psign/blend
18616 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18617 if (!Subtarget->hasSSSE3() ||
18618 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18621 // Canonicalize pandn to RHS
18622 if (N0.getOpcode() == X86ISD::ANDNP)
18624 // or (and (m, y), (pandn m, x))
18625 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18626 SDValue Mask = N1.getOperand(0);
18627 SDValue X = N1.getOperand(1);
18629 if (N0.getOperand(0) == Mask)
18630 Y = N0.getOperand(1);
18631 if (N0.getOperand(1) == Mask)
18632 Y = N0.getOperand(0);
18634 // Check to see if the mask appeared in both the AND and ANDNP and
18638 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18639 // Look through mask bitcast.
18640 if (Mask.getOpcode() == ISD::BITCAST)
18641 Mask = Mask.getOperand(0);
18642 if (X.getOpcode() == ISD::BITCAST)
18643 X = X.getOperand(0);
18644 if (Y.getOpcode() == ISD::BITCAST)
18645 Y = Y.getOperand(0);
18647 EVT MaskVT = Mask.getValueType();
18649 // Validate that the Mask operand is a vector sra node.
18650 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18651 // there is no psrai.b
18652 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18653 unsigned SraAmt = ~0;
18654 if (Mask.getOpcode() == ISD::SRA) {
18655 SDValue Amt = Mask.getOperand(1);
18656 if (isSplatVector(Amt.getNode())) {
18657 SDValue SclrAmt = Amt->getOperand(0);
18658 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18659 SraAmt = C->getZExtValue();
18661 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18662 SDValue SraC = Mask.getOperand(1);
18663 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18665 if ((SraAmt + 1) != EltBits)
18670 // Now we know we at least have a plendvb with the mask val. See if
18671 // we can form a psignb/w/d.
18672 // psign = x.type == y.type == mask.type && y = sub(0, x);
18673 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18674 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18675 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18676 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18677 "Unsupported VT for PSIGN");
18678 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18679 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18681 // PBLENDVB only available on SSE 4.1
18682 if (!Subtarget->hasSSE41())
18685 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18687 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18688 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18689 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18690 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18691 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18695 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18698 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18699 MachineFunction &MF = DAG.getMachineFunction();
18700 bool OptForSize = MF.getFunction()->getAttributes().
18701 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18703 // SHLD/SHRD instructions have lower register pressure, but on some
18704 // platforms they have higher latency than the equivalent
18705 // series of shifts/or that would otherwise be generated.
18706 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18707 // have higher latencies and we are not optimizing for size.
18708 if (!OptForSize && Subtarget->isSHLDSlow())
18711 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18713 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18715 if (!N0.hasOneUse() || !N1.hasOneUse())
18718 SDValue ShAmt0 = N0.getOperand(1);
18719 if (ShAmt0.getValueType() != MVT::i8)
18721 SDValue ShAmt1 = N1.getOperand(1);
18722 if (ShAmt1.getValueType() != MVT::i8)
18724 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18725 ShAmt0 = ShAmt0.getOperand(0);
18726 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18727 ShAmt1 = ShAmt1.getOperand(0);
18730 unsigned Opc = X86ISD::SHLD;
18731 SDValue Op0 = N0.getOperand(0);
18732 SDValue Op1 = N1.getOperand(0);
18733 if (ShAmt0.getOpcode() == ISD::SUB) {
18734 Opc = X86ISD::SHRD;
18735 std::swap(Op0, Op1);
18736 std::swap(ShAmt0, ShAmt1);
18739 unsigned Bits = VT.getSizeInBits();
18740 if (ShAmt1.getOpcode() == ISD::SUB) {
18741 SDValue Sum = ShAmt1.getOperand(0);
18742 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18743 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18744 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18745 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18746 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18747 return DAG.getNode(Opc, DL, VT,
18749 DAG.getNode(ISD::TRUNCATE, DL,
18752 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18753 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18755 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18756 return DAG.getNode(Opc, DL, VT,
18757 N0.getOperand(0), N1.getOperand(0),
18758 DAG.getNode(ISD::TRUNCATE, DL,
18765 // Generate NEG and CMOV for integer abs.
18766 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18767 EVT VT = N->getValueType(0);
18769 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18770 // 8-bit integer abs to NEG and CMOV.
18771 if (VT.isInteger() && VT.getSizeInBits() == 8)
18774 SDValue N0 = N->getOperand(0);
18775 SDValue N1 = N->getOperand(1);
18778 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18779 // and change it to SUB and CMOV.
18780 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18781 N0.getOpcode() == ISD::ADD &&
18782 N0.getOperand(1) == N1 &&
18783 N1.getOpcode() == ISD::SRA &&
18784 N1.getOperand(0) == N0.getOperand(0))
18785 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18786 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18787 // Generate SUB & CMOV.
18788 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18789 DAG.getConstant(0, VT), N0.getOperand(0));
18791 SDValue Ops[] = { N0.getOperand(0), Neg,
18792 DAG.getConstant(X86::COND_GE, MVT::i8),
18793 SDValue(Neg.getNode(), 1) };
18794 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18795 Ops, array_lengthof(Ops));
18800 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18801 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18802 TargetLowering::DAGCombinerInfo &DCI,
18803 const X86Subtarget *Subtarget) {
18804 if (DCI.isBeforeLegalizeOps())
18807 if (Subtarget->hasCMov()) {
18808 SDValue RV = performIntegerAbsCombine(N, DAG);
18816 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18817 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18818 TargetLowering::DAGCombinerInfo &DCI,
18819 const X86Subtarget *Subtarget) {
18820 LoadSDNode *Ld = cast<LoadSDNode>(N);
18821 EVT RegVT = Ld->getValueType(0);
18822 EVT MemVT = Ld->getMemoryVT();
18824 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18825 unsigned RegSz = RegVT.getSizeInBits();
18827 // On Sandybridge unaligned 256bit loads are inefficient.
18828 ISD::LoadExtType Ext = Ld->getExtensionType();
18829 unsigned Alignment = Ld->getAlignment();
18830 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18831 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18832 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18833 unsigned NumElems = RegVT.getVectorNumElements();
18837 SDValue Ptr = Ld->getBasePtr();
18838 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18840 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18842 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18843 Ld->getPointerInfo(), Ld->isVolatile(),
18844 Ld->isNonTemporal(), Ld->isInvariant(),
18846 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18847 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18848 Ld->getPointerInfo(), Ld->isVolatile(),
18849 Ld->isNonTemporal(), Ld->isInvariant(),
18850 std::min(16U, Alignment));
18851 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18853 Load2.getValue(1));
18855 SDValue NewVec = DAG.getUNDEF(RegVT);
18856 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18857 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18858 return DCI.CombineTo(N, NewVec, TF, true);
18861 // If this is a vector EXT Load then attempt to optimize it using a
18862 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18863 // expansion is still better than scalar code.
18864 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18865 // emit a shuffle and a arithmetic shift.
18866 // TODO: It is possible to support ZExt by zeroing the undef values
18867 // during the shuffle phase or after the shuffle.
18868 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18869 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18870 assert(MemVT != RegVT && "Cannot extend to the same type");
18871 assert(MemVT.isVector() && "Must load a vector from memory");
18873 unsigned NumElems = RegVT.getVectorNumElements();
18874 unsigned MemSz = MemVT.getSizeInBits();
18875 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18877 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18880 // All sizes must be a power of two.
18881 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18884 // Attempt to load the original value using scalar loads.
18885 // Find the largest scalar type that divides the total loaded size.
18886 MVT SclrLoadTy = MVT::i8;
18887 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18888 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18889 MVT Tp = (MVT::SimpleValueType)tp;
18890 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18895 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18896 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18898 SclrLoadTy = MVT::f64;
18900 // Calculate the number of scalar loads that we need to perform
18901 // in order to load our vector from memory.
18902 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18903 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18906 unsigned loadRegZize = RegSz;
18907 if (Ext == ISD::SEXTLOAD && RegSz == 256)
18910 // Represent our vector as a sequence of elements which are the
18911 // largest scalar that we can load.
18912 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18913 loadRegZize/SclrLoadTy.getSizeInBits());
18915 // Represent the data using the same element type that is stored in
18916 // memory. In practice, we ''widen'' MemVT.
18918 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18919 loadRegZize/MemVT.getScalarType().getSizeInBits());
18921 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18922 "Invalid vector type");
18924 // We can't shuffle using an illegal type.
18925 if (!TLI.isTypeLegal(WideVecVT))
18928 SmallVector<SDValue, 8> Chains;
18929 SDValue Ptr = Ld->getBasePtr();
18930 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18931 TLI.getPointerTy());
18932 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18934 for (unsigned i = 0; i < NumLoads; ++i) {
18935 // Perform a single load.
18936 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18937 Ptr, Ld->getPointerInfo(),
18938 Ld->isVolatile(), Ld->isNonTemporal(),
18939 Ld->isInvariant(), Ld->getAlignment());
18940 Chains.push_back(ScalarLoad.getValue(1));
18941 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18942 // another round of DAGCombining.
18944 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18946 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18947 ScalarLoad, DAG.getIntPtrConstant(i));
18949 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18952 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18955 // Bitcast the loaded value to a vector of the original element type, in
18956 // the size of the target vector type.
18957 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18958 unsigned SizeRatio = RegSz/MemSz;
18960 if (Ext == ISD::SEXTLOAD) {
18961 // If we have SSE4.1 we can directly emit a VSEXT node.
18962 if (Subtarget->hasSSE41()) {
18963 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18964 return DCI.CombineTo(N, Sext, TF, true);
18967 // Otherwise we'll shuffle the small elements in the high bits of the
18968 // larger type and perform an arithmetic shift. If the shift is not legal
18969 // it's better to scalarize.
18970 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18973 // Redistribute the loaded elements into the different locations.
18974 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18975 for (unsigned i = 0; i != NumElems; ++i)
18976 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18978 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18979 DAG.getUNDEF(WideVecVT),
18982 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18984 // Build the arithmetic shift.
18985 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18986 MemVT.getVectorElementType().getSizeInBits();
18987 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18988 DAG.getConstant(Amt, RegVT));
18990 return DCI.CombineTo(N, Shuff, TF, true);
18993 // Redistribute the loaded elements into the different locations.
18994 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18995 for (unsigned i = 0; i != NumElems; ++i)
18996 ShuffleVec[i*SizeRatio] = i;
18998 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18999 DAG.getUNDEF(WideVecVT),
19002 // Bitcast to the requested type.
19003 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19004 // Replace the original load with the new sequence
19005 // and return the new chain.
19006 return DCI.CombineTo(N, Shuff, TF, true);
19012 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19013 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19014 const X86Subtarget *Subtarget) {
19015 StoreSDNode *St = cast<StoreSDNode>(N);
19016 EVT VT = St->getValue().getValueType();
19017 EVT StVT = St->getMemoryVT();
19019 SDValue StoredVal = St->getOperand(1);
19020 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19022 // If we are saving a concatenation of two XMM registers, perform two stores.
19023 // On Sandy Bridge, 256-bit memory operations are executed by two
19024 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19025 // memory operation.
19026 unsigned Alignment = St->getAlignment();
19027 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19028 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19029 StVT == VT && !IsAligned) {
19030 unsigned NumElems = VT.getVectorNumElements();
19034 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19035 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19037 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19038 SDValue Ptr0 = St->getBasePtr();
19039 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19041 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19042 St->getPointerInfo(), St->isVolatile(),
19043 St->isNonTemporal(), Alignment);
19044 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19045 St->getPointerInfo(), St->isVolatile(),
19046 St->isNonTemporal(),
19047 std::min(16U, Alignment));
19048 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19051 // Optimize trunc store (of multiple scalars) to shuffle and store.
19052 // First, pack all of the elements in one place. Next, store to memory
19053 // in fewer chunks.
19054 if (St->isTruncatingStore() && VT.isVector()) {
19055 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19056 unsigned NumElems = VT.getVectorNumElements();
19057 assert(StVT != VT && "Cannot truncate to the same type");
19058 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19059 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19061 // From, To sizes and ElemCount must be pow of two
19062 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19063 // We are going to use the original vector elt for storing.
19064 // Accumulated smaller vector elements must be a multiple of the store size.
19065 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19067 unsigned SizeRatio = FromSz / ToSz;
19069 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19071 // Create a type on which we perform the shuffle
19072 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19073 StVT.getScalarType(), NumElems*SizeRatio);
19075 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19077 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19078 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19079 for (unsigned i = 0; i != NumElems; ++i)
19080 ShuffleVec[i] = i * SizeRatio;
19082 // Can't shuffle using an illegal type.
19083 if (!TLI.isTypeLegal(WideVecVT))
19086 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19087 DAG.getUNDEF(WideVecVT),
19089 // At this point all of the data is stored at the bottom of the
19090 // register. We now need to save it to mem.
19092 // Find the largest store unit
19093 MVT StoreType = MVT::i8;
19094 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19095 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19096 MVT Tp = (MVT::SimpleValueType)tp;
19097 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19101 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19102 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19103 (64 <= NumElems * ToSz))
19104 StoreType = MVT::f64;
19106 // Bitcast the original vector into a vector of store-size units
19107 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19108 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19109 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19110 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19111 SmallVector<SDValue, 8> Chains;
19112 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19113 TLI.getPointerTy());
19114 SDValue Ptr = St->getBasePtr();
19116 // Perform one or more big stores into memory.
19117 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19118 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19119 StoreType, ShuffWide,
19120 DAG.getIntPtrConstant(i));
19121 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19122 St->getPointerInfo(), St->isVolatile(),
19123 St->isNonTemporal(), St->getAlignment());
19124 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19125 Chains.push_back(Ch);
19128 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19132 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19133 // the FP state in cases where an emms may be missing.
19134 // A preferable solution to the general problem is to figure out the right
19135 // places to insert EMMS. This qualifies as a quick hack.
19137 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19138 if (VT.getSizeInBits() != 64)
19141 const Function *F = DAG.getMachineFunction().getFunction();
19142 bool NoImplicitFloatOps = F->getAttributes().
19143 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19144 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19145 && Subtarget->hasSSE2();
19146 if ((VT.isVector() ||
19147 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19148 isa<LoadSDNode>(St->getValue()) &&
19149 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19150 St->getChain().hasOneUse() && !St->isVolatile()) {
19151 SDNode* LdVal = St->getValue().getNode();
19152 LoadSDNode *Ld = 0;
19153 int TokenFactorIndex = -1;
19154 SmallVector<SDValue, 8> Ops;
19155 SDNode* ChainVal = St->getChain().getNode();
19156 // Must be a store of a load. We currently handle two cases: the load
19157 // is a direct child, and it's under an intervening TokenFactor. It is
19158 // possible to dig deeper under nested TokenFactors.
19159 if (ChainVal == LdVal)
19160 Ld = cast<LoadSDNode>(St->getChain());
19161 else if (St->getValue().hasOneUse() &&
19162 ChainVal->getOpcode() == ISD::TokenFactor) {
19163 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19164 if (ChainVal->getOperand(i).getNode() == LdVal) {
19165 TokenFactorIndex = i;
19166 Ld = cast<LoadSDNode>(St->getValue());
19168 Ops.push_back(ChainVal->getOperand(i));
19172 if (!Ld || !ISD::isNormalLoad(Ld))
19175 // If this is not the MMX case, i.e. we are just turning i64 load/store
19176 // into f64 load/store, avoid the transformation if there are multiple
19177 // uses of the loaded value.
19178 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19183 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19184 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19186 if (Subtarget->is64Bit() || F64IsLegal) {
19187 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19188 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19189 Ld->getPointerInfo(), Ld->isVolatile(),
19190 Ld->isNonTemporal(), Ld->isInvariant(),
19191 Ld->getAlignment());
19192 SDValue NewChain = NewLd.getValue(1);
19193 if (TokenFactorIndex != -1) {
19194 Ops.push_back(NewChain);
19195 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19198 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19199 St->getPointerInfo(),
19200 St->isVolatile(), St->isNonTemporal(),
19201 St->getAlignment());
19204 // Otherwise, lower to two pairs of 32-bit loads / stores.
19205 SDValue LoAddr = Ld->getBasePtr();
19206 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19207 DAG.getConstant(4, MVT::i32));
19209 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19210 Ld->getPointerInfo(),
19211 Ld->isVolatile(), Ld->isNonTemporal(),
19212 Ld->isInvariant(), Ld->getAlignment());
19213 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19214 Ld->getPointerInfo().getWithOffset(4),
19215 Ld->isVolatile(), Ld->isNonTemporal(),
19217 MinAlign(Ld->getAlignment(), 4));
19219 SDValue NewChain = LoLd.getValue(1);
19220 if (TokenFactorIndex != -1) {
19221 Ops.push_back(LoLd);
19222 Ops.push_back(HiLd);
19223 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19227 LoAddr = St->getBasePtr();
19228 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19229 DAG.getConstant(4, MVT::i32));
19231 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19232 St->getPointerInfo(),
19233 St->isVolatile(), St->isNonTemporal(),
19234 St->getAlignment());
19235 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19236 St->getPointerInfo().getWithOffset(4),
19238 St->isNonTemporal(),
19239 MinAlign(St->getAlignment(), 4));
19240 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19245 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19246 /// and return the operands for the horizontal operation in LHS and RHS. A
19247 /// horizontal operation performs the binary operation on successive elements
19248 /// of its first operand, then on successive elements of its second operand,
19249 /// returning the resulting values in a vector. For example, if
19250 /// A = < float a0, float a1, float a2, float a3 >
19252 /// B = < float b0, float b1, float b2, float b3 >
19253 /// then the result of doing a horizontal operation on A and B is
19254 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19255 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19256 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19257 /// set to A, RHS to B, and the routine returns 'true'.
19258 /// Note that the binary operation should have the property that if one of the
19259 /// operands is UNDEF then the result is UNDEF.
19260 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19261 // Look for the following pattern: if
19262 // A = < float a0, float a1, float a2, float a3 >
19263 // B = < float b0, float b1, float b2, float b3 >
19265 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19266 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19267 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19268 // which is A horizontal-op B.
19270 // At least one of the operands should be a vector shuffle.
19271 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19272 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19275 MVT VT = LHS.getSimpleValueType();
19277 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19278 "Unsupported vector type for horizontal add/sub");
19280 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19281 // operate independently on 128-bit lanes.
19282 unsigned NumElts = VT.getVectorNumElements();
19283 unsigned NumLanes = VT.getSizeInBits()/128;
19284 unsigned NumLaneElts = NumElts / NumLanes;
19285 assert((NumLaneElts % 2 == 0) &&
19286 "Vector type should have an even number of elements in each lane");
19287 unsigned HalfLaneElts = NumLaneElts/2;
19289 // View LHS in the form
19290 // LHS = VECTOR_SHUFFLE A, B, LMask
19291 // If LHS is not a shuffle then pretend it is the shuffle
19292 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19293 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19296 SmallVector<int, 16> LMask(NumElts);
19297 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19298 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19299 A = LHS.getOperand(0);
19300 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19301 B = LHS.getOperand(1);
19302 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19303 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19305 if (LHS.getOpcode() != ISD::UNDEF)
19307 for (unsigned i = 0; i != NumElts; ++i)
19311 // Likewise, view RHS in the form
19312 // RHS = VECTOR_SHUFFLE C, D, RMask
19314 SmallVector<int, 16> RMask(NumElts);
19315 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19316 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19317 C = RHS.getOperand(0);
19318 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19319 D = RHS.getOperand(1);
19320 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19321 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19323 if (RHS.getOpcode() != ISD::UNDEF)
19325 for (unsigned i = 0; i != NumElts; ++i)
19329 // Check that the shuffles are both shuffling the same vectors.
19330 if (!(A == C && B == D) && !(A == D && B == C))
19333 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19334 if (!A.getNode() && !B.getNode())
19337 // If A and B occur in reverse order in RHS, then "swap" them (which means
19338 // rewriting the mask).
19340 CommuteVectorShuffleMask(RMask, NumElts);
19342 // At this point LHS and RHS are equivalent to
19343 // LHS = VECTOR_SHUFFLE A, B, LMask
19344 // RHS = VECTOR_SHUFFLE A, B, RMask
19345 // Check that the masks correspond to performing a horizontal operation.
19346 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19347 for (unsigned i = 0; i != NumLaneElts; ++i) {
19348 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19350 // Ignore any UNDEF components.
19351 if (LIdx < 0 || RIdx < 0 ||
19352 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19353 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19356 // Check that successive elements are being operated on. If not, this is
19357 // not a horizontal operation.
19358 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19359 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19360 if (!(LIdx == Index && RIdx == Index + 1) &&
19361 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19366 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19367 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19371 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19372 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19373 const X86Subtarget *Subtarget) {
19374 EVT VT = N->getValueType(0);
19375 SDValue LHS = N->getOperand(0);
19376 SDValue RHS = N->getOperand(1);
19378 // Try to synthesize horizontal adds from adds of shuffles.
19379 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19380 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19381 isHorizontalBinOp(LHS, RHS, true))
19382 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19386 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19387 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19388 const X86Subtarget *Subtarget) {
19389 EVT VT = N->getValueType(0);
19390 SDValue LHS = N->getOperand(0);
19391 SDValue RHS = N->getOperand(1);
19393 // Try to synthesize horizontal subs from subs of shuffles.
19394 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19395 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19396 isHorizontalBinOp(LHS, RHS, false))
19397 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19401 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19402 /// X86ISD::FXOR nodes.
19403 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19404 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19405 // F[X]OR(0.0, x) -> x
19406 // F[X]OR(x, 0.0) -> x
19407 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19408 if (C->getValueAPF().isPosZero())
19409 return N->getOperand(1);
19410 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19411 if (C->getValueAPF().isPosZero())
19412 return N->getOperand(0);
19416 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19417 /// X86ISD::FMAX nodes.
19418 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19419 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19421 // Only perform optimizations if UnsafeMath is used.
19422 if (!DAG.getTarget().Options.UnsafeFPMath)
19425 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19426 // into FMINC and FMAXC, which are Commutative operations.
19427 unsigned NewOp = 0;
19428 switch (N->getOpcode()) {
19429 default: llvm_unreachable("unknown opcode");
19430 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19431 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19434 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19435 N->getOperand(0), N->getOperand(1));
19438 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19439 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19440 // FAND(0.0, x) -> 0.0
19441 // FAND(x, 0.0) -> 0.0
19442 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19443 if (C->getValueAPF().isPosZero())
19444 return N->getOperand(0);
19445 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19446 if (C->getValueAPF().isPosZero())
19447 return N->getOperand(1);
19451 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19452 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19453 // FANDN(x, 0.0) -> 0.0
19454 // FANDN(0.0, x) -> x
19455 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19456 if (C->getValueAPF().isPosZero())
19457 return N->getOperand(1);
19458 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19459 if (C->getValueAPF().isPosZero())
19460 return N->getOperand(1);
19464 static SDValue PerformBTCombine(SDNode *N,
19466 TargetLowering::DAGCombinerInfo &DCI) {
19467 // BT ignores high bits in the bit index operand.
19468 SDValue Op1 = N->getOperand(1);
19469 if (Op1.hasOneUse()) {
19470 unsigned BitWidth = Op1.getValueSizeInBits();
19471 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19472 APInt KnownZero, KnownOne;
19473 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19474 !DCI.isBeforeLegalizeOps());
19475 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19476 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19477 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19478 DCI.CommitTargetLoweringOpt(TLO);
19483 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19484 SDValue Op = N->getOperand(0);
19485 if (Op.getOpcode() == ISD::BITCAST)
19486 Op = Op.getOperand(0);
19487 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19488 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19489 VT.getVectorElementType().getSizeInBits() ==
19490 OpVT.getVectorElementType().getSizeInBits()) {
19491 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19496 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19497 const X86Subtarget *Subtarget) {
19498 EVT VT = N->getValueType(0);
19499 if (!VT.isVector())
19502 SDValue N0 = N->getOperand(0);
19503 SDValue N1 = N->getOperand(1);
19504 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19507 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19508 // both SSE and AVX2 since there is no sign-extended shift right
19509 // operation on a vector with 64-bit elements.
19510 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19511 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19512 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19513 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19514 SDValue N00 = N0.getOperand(0);
19516 // EXTLOAD has a better solution on AVX2,
19517 // it may be replaced with X86ISD::VSEXT node.
19518 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19519 if (!ISD::isNormalLoad(N00.getNode()))
19522 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19523 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19525 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19531 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19532 TargetLowering::DAGCombinerInfo &DCI,
19533 const X86Subtarget *Subtarget) {
19534 if (!DCI.isBeforeLegalizeOps())
19537 if (!Subtarget->hasFp256())
19540 EVT VT = N->getValueType(0);
19541 if (VT.isVector() && VT.getSizeInBits() == 256) {
19542 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19550 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19551 const X86Subtarget* Subtarget) {
19553 EVT VT = N->getValueType(0);
19555 // Let legalize expand this if it isn't a legal type yet.
19556 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19559 EVT ScalarVT = VT.getScalarType();
19560 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19561 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19564 SDValue A = N->getOperand(0);
19565 SDValue B = N->getOperand(1);
19566 SDValue C = N->getOperand(2);
19568 bool NegA = (A.getOpcode() == ISD::FNEG);
19569 bool NegB = (B.getOpcode() == ISD::FNEG);
19570 bool NegC = (C.getOpcode() == ISD::FNEG);
19572 // Negative multiplication when NegA xor NegB
19573 bool NegMul = (NegA != NegB);
19575 A = A.getOperand(0);
19577 B = B.getOperand(0);
19579 C = C.getOperand(0);
19583 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19585 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19587 return DAG.getNode(Opcode, dl, VT, A, B, C);
19590 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19591 TargetLowering::DAGCombinerInfo &DCI,
19592 const X86Subtarget *Subtarget) {
19593 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19594 // (and (i32 x86isd::setcc_carry), 1)
19595 // This eliminates the zext. This transformation is necessary because
19596 // ISD::SETCC is always legalized to i8.
19598 SDValue N0 = N->getOperand(0);
19599 EVT VT = N->getValueType(0);
19601 if (N0.getOpcode() == ISD::AND &&
19603 N0.getOperand(0).hasOneUse()) {
19604 SDValue N00 = N0.getOperand(0);
19605 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19606 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19607 if (!C || C->getZExtValue() != 1)
19609 return DAG.getNode(ISD::AND, dl, VT,
19610 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19611 N00.getOperand(0), N00.getOperand(1)),
19612 DAG.getConstant(1, VT));
19616 if (N0.getOpcode() == ISD::TRUNCATE &&
19618 N0.getOperand(0).hasOneUse()) {
19619 SDValue N00 = N0.getOperand(0);
19620 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19621 return DAG.getNode(ISD::AND, dl, VT,
19622 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19623 N00.getOperand(0), N00.getOperand(1)),
19624 DAG.getConstant(1, VT));
19627 if (VT.is256BitVector()) {
19628 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19636 // Optimize x == -y --> x+y == 0
19637 // x != -y --> x+y != 0
19638 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19639 const X86Subtarget* Subtarget) {
19640 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19641 SDValue LHS = N->getOperand(0);
19642 SDValue RHS = N->getOperand(1);
19643 EVT VT = N->getValueType(0);
19646 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19647 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19648 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19649 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19650 LHS.getValueType(), RHS, LHS.getOperand(1));
19651 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19652 addV, DAG.getConstant(0, addV.getValueType()), CC);
19654 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19655 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19656 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19657 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19658 RHS.getValueType(), LHS, RHS.getOperand(1));
19659 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19660 addV, DAG.getConstant(0, addV.getValueType()), CC);
19663 if (VT.getScalarType() == MVT::i1) {
19664 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19665 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19666 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19667 if (!IsSEXT0 && !IsVZero0)
19669 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19670 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19671 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19673 if (!IsSEXT1 && !IsVZero1)
19676 if (IsSEXT0 && IsVZero1) {
19677 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19678 if (CC == ISD::SETEQ)
19679 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19680 return LHS.getOperand(0);
19682 if (IsSEXT1 && IsVZero0) {
19683 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19684 if (CC == ISD::SETEQ)
19685 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19686 return RHS.getOperand(0);
19693 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19694 // as "sbb reg,reg", since it can be extended without zext and produces
19695 // an all-ones bit which is more useful than 0/1 in some cases.
19696 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19699 return DAG.getNode(ISD::AND, DL, VT,
19700 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19701 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19702 DAG.getConstant(1, VT));
19703 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19704 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19705 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19706 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19709 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19710 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19711 TargetLowering::DAGCombinerInfo &DCI,
19712 const X86Subtarget *Subtarget) {
19714 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19715 SDValue EFLAGS = N->getOperand(1);
19717 if (CC == X86::COND_A) {
19718 // Try to convert COND_A into COND_B in an attempt to facilitate
19719 // materializing "setb reg".
19721 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19722 // cannot take an immediate as its first operand.
19724 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19725 EFLAGS.getValueType().isInteger() &&
19726 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19727 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19728 EFLAGS.getNode()->getVTList(),
19729 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19730 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19731 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19735 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19736 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19738 if (CC == X86::COND_B)
19739 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19743 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19744 if (Flags.getNode()) {
19745 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19746 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19752 // Optimize branch condition evaluation.
19754 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19755 TargetLowering::DAGCombinerInfo &DCI,
19756 const X86Subtarget *Subtarget) {
19758 SDValue Chain = N->getOperand(0);
19759 SDValue Dest = N->getOperand(1);
19760 SDValue EFLAGS = N->getOperand(3);
19761 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19765 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19766 if (Flags.getNode()) {
19767 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19768 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19775 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19776 const X86TargetLowering *XTLI) {
19777 SDValue Op0 = N->getOperand(0);
19778 EVT InVT = Op0->getValueType(0);
19780 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19781 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19783 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19784 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19785 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19788 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19789 // a 32-bit target where SSE doesn't support i64->FP operations.
19790 if (Op0.getOpcode() == ISD::LOAD) {
19791 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19792 EVT VT = Ld->getValueType(0);
19793 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19794 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19795 !XTLI->getSubtarget()->is64Bit() &&
19797 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19798 Ld->getChain(), Op0, DAG);
19799 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19806 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19807 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19808 X86TargetLowering::DAGCombinerInfo &DCI) {
19809 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19810 // the result is either zero or one (depending on the input carry bit).
19811 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19812 if (X86::isZeroNode(N->getOperand(0)) &&
19813 X86::isZeroNode(N->getOperand(1)) &&
19814 // We don't have a good way to replace an EFLAGS use, so only do this when
19816 SDValue(N, 1).use_empty()) {
19818 EVT VT = N->getValueType(0);
19819 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19820 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19821 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19822 DAG.getConstant(X86::COND_B,MVT::i8),
19824 DAG.getConstant(1, VT));
19825 return DCI.CombineTo(N, Res1, CarryOut);
19831 // fold (add Y, (sete X, 0)) -> adc 0, Y
19832 // (add Y, (setne X, 0)) -> sbb -1, Y
19833 // (sub (sete X, 0), Y) -> sbb 0, Y
19834 // (sub (setne X, 0), Y) -> adc -1, Y
19835 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19838 // Look through ZExts.
19839 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19840 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19843 SDValue SetCC = Ext.getOperand(0);
19844 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19847 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19848 if (CC != X86::COND_E && CC != X86::COND_NE)
19851 SDValue Cmp = SetCC.getOperand(1);
19852 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19853 !X86::isZeroNode(Cmp.getOperand(1)) ||
19854 !Cmp.getOperand(0).getValueType().isInteger())
19857 SDValue CmpOp0 = Cmp.getOperand(0);
19858 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19859 DAG.getConstant(1, CmpOp0.getValueType()));
19861 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19862 if (CC == X86::COND_NE)
19863 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19864 DL, OtherVal.getValueType(), OtherVal,
19865 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19866 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19867 DL, OtherVal.getValueType(), OtherVal,
19868 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19871 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19872 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19873 const X86Subtarget *Subtarget) {
19874 EVT VT = N->getValueType(0);
19875 SDValue Op0 = N->getOperand(0);
19876 SDValue Op1 = N->getOperand(1);
19878 // Try to synthesize horizontal adds from adds of shuffles.
19879 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19880 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19881 isHorizontalBinOp(Op0, Op1, true))
19882 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19884 return OptimizeConditionalInDecrement(N, DAG);
19887 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19888 const X86Subtarget *Subtarget) {
19889 SDValue Op0 = N->getOperand(0);
19890 SDValue Op1 = N->getOperand(1);
19892 // X86 can't encode an immediate LHS of a sub. See if we can push the
19893 // negation into a preceding instruction.
19894 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19895 // If the RHS of the sub is a XOR with one use and a constant, invert the
19896 // immediate. Then add one to the LHS of the sub so we can turn
19897 // X-Y -> X+~Y+1, saving one register.
19898 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19899 isa<ConstantSDNode>(Op1.getOperand(1))) {
19900 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19901 EVT VT = Op0.getValueType();
19902 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19904 DAG.getConstant(~XorC, VT));
19905 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19906 DAG.getConstant(C->getAPIntValue()+1, VT));
19910 // Try to synthesize horizontal adds from adds of shuffles.
19911 EVT VT = N->getValueType(0);
19912 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19913 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19914 isHorizontalBinOp(Op0, Op1, true))
19915 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19917 return OptimizeConditionalInDecrement(N, DAG);
19920 /// performVZEXTCombine - Performs build vector combines
19921 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19922 TargetLowering::DAGCombinerInfo &DCI,
19923 const X86Subtarget *Subtarget) {
19924 // (vzext (bitcast (vzext (x)) -> (vzext x)
19925 SDValue In = N->getOperand(0);
19926 while (In.getOpcode() == ISD::BITCAST)
19927 In = In.getOperand(0);
19929 if (In.getOpcode() != X86ISD::VZEXT)
19932 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19936 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19937 DAGCombinerInfo &DCI) const {
19938 SelectionDAG &DAG = DCI.DAG;
19939 switch (N->getOpcode()) {
19941 case ISD::EXTRACT_VECTOR_ELT:
19942 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19944 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19945 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19946 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
19947 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
19948 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
19949 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
19952 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
19953 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
19954 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
19955 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
19956 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
19957 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
19958 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
19959 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
19960 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
19962 case X86ISD::FOR: return PerformFORCombine(N, DAG);
19964 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
19965 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
19966 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
19967 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
19968 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
19969 case ISD::ANY_EXTEND:
19970 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
19971 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
19972 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19973 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19974 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
19975 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19976 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19977 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
19978 case X86ISD::SHUFP: // Handle all target specific shuffles
19979 case X86ISD::PALIGNR:
19980 case X86ISD::UNPCKH:
19981 case X86ISD::UNPCKL:
19982 case X86ISD::MOVHLPS:
19983 case X86ISD::MOVLHPS:
19984 case X86ISD::PSHUFD:
19985 case X86ISD::PSHUFHW:
19986 case X86ISD::PSHUFLW:
19987 case X86ISD::MOVSS:
19988 case X86ISD::MOVSD:
19989 case X86ISD::VPERMILP:
19990 case X86ISD::VPERM2X128:
19991 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19992 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
19998 /// isTypeDesirableForOp - Return true if the target has native support for
19999 /// the specified value type and it is 'desirable' to use the type for the
20000 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20001 /// instruction encodings are longer and some i16 instructions are slow.
20002 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20003 if (!isTypeLegal(VT))
20005 if (VT != MVT::i16)
20012 case ISD::SIGN_EXTEND:
20013 case ISD::ZERO_EXTEND:
20014 case ISD::ANY_EXTEND:
20027 /// IsDesirableToPromoteOp - This method query the target whether it is
20028 /// beneficial for dag combiner to promote the specified node. If true, it
20029 /// should return the desired promotion type by reference.
20030 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20031 EVT VT = Op.getValueType();
20032 if (VT != MVT::i16)
20035 bool Promote = false;
20036 bool Commute = false;
20037 switch (Op.getOpcode()) {
20040 LoadSDNode *LD = cast<LoadSDNode>(Op);
20041 // If the non-extending load has a single use and it's not live out, then it
20042 // might be folded.
20043 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20044 Op.hasOneUse()*/) {
20045 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20046 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20047 // The only case where we'd want to promote LOAD (rather then it being
20048 // promoted as an operand is when it's only use is liveout.
20049 if (UI->getOpcode() != ISD::CopyToReg)
20056 case ISD::SIGN_EXTEND:
20057 case ISD::ZERO_EXTEND:
20058 case ISD::ANY_EXTEND:
20063 SDValue N0 = Op.getOperand(0);
20064 // Look out for (store (shl (load), x)).
20065 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20078 SDValue N0 = Op.getOperand(0);
20079 SDValue N1 = Op.getOperand(1);
20080 if (!Commute && MayFoldLoad(N1))
20082 // Avoid disabling potential load folding opportunities.
20083 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20085 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20095 //===----------------------------------------------------------------------===//
20096 // X86 Inline Assembly Support
20097 //===----------------------------------------------------------------------===//
20100 // Helper to match a string separated by whitespace.
20101 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20102 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20104 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20105 StringRef piece(*args[i]);
20106 if (!s.startswith(piece)) // Check if the piece matches.
20109 s = s.substr(piece.size());
20110 StringRef::size_type pos = s.find_first_not_of(" \t");
20111 if (pos == 0) // We matched a prefix.
20119 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20122 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20124 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20125 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20126 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20127 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20129 if (AsmPieces.size() == 3)
20131 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20138 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20139 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20141 std::string AsmStr = IA->getAsmString();
20143 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20144 if (!Ty || Ty->getBitWidth() % 16 != 0)
20147 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20148 SmallVector<StringRef, 4> AsmPieces;
20149 SplitString(AsmStr, AsmPieces, ";\n");
20151 switch (AsmPieces.size()) {
20152 default: return false;
20154 // FIXME: this should verify that we are targeting a 486 or better. If not,
20155 // we will turn this bswap into something that will be lowered to logical
20156 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20157 // lower so don't worry about this.
20159 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20160 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20161 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20162 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20163 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20164 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20165 // No need to check constraints, nothing other than the equivalent of
20166 // "=r,0" would be valid here.
20167 return IntrinsicLowering::LowerToByteSwap(CI);
20170 // rorw $$8, ${0:w} --> llvm.bswap.i16
20171 if (CI->getType()->isIntegerTy(16) &&
20172 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20173 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20174 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20176 const std::string &ConstraintsStr = IA->getConstraintString();
20177 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20178 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20179 if (clobbersFlagRegisters(AsmPieces))
20180 return IntrinsicLowering::LowerToByteSwap(CI);
20184 if (CI->getType()->isIntegerTy(32) &&
20185 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20186 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20187 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20188 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20190 const std::string &ConstraintsStr = IA->getConstraintString();
20191 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20192 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20193 if (clobbersFlagRegisters(AsmPieces))
20194 return IntrinsicLowering::LowerToByteSwap(CI);
20197 if (CI->getType()->isIntegerTy(64)) {
20198 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20199 if (Constraints.size() >= 2 &&
20200 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20201 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20202 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20203 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20204 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20205 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20206 return IntrinsicLowering::LowerToByteSwap(CI);
20214 /// getConstraintType - Given a constraint letter, return the type of
20215 /// constraint it is for this target.
20216 X86TargetLowering::ConstraintType
20217 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20218 if (Constraint.size() == 1) {
20219 switch (Constraint[0]) {
20230 return C_RegisterClass;
20254 return TargetLowering::getConstraintType(Constraint);
20257 /// Examine constraint type and operand type and determine a weight value.
20258 /// This object must already have been set up with the operand type
20259 /// and the current alternative constraint selected.
20260 TargetLowering::ConstraintWeight
20261 X86TargetLowering::getSingleConstraintMatchWeight(
20262 AsmOperandInfo &info, const char *constraint) const {
20263 ConstraintWeight weight = CW_Invalid;
20264 Value *CallOperandVal = info.CallOperandVal;
20265 // If we don't have a value, we can't do a match,
20266 // but allow it at the lowest weight.
20267 if (CallOperandVal == NULL)
20269 Type *type = CallOperandVal->getType();
20270 // Look at the constraint type.
20271 switch (*constraint) {
20273 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20284 if (CallOperandVal->getType()->isIntegerTy())
20285 weight = CW_SpecificReg;
20290 if (type->isFloatingPointTy())
20291 weight = CW_SpecificReg;
20294 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20295 weight = CW_SpecificReg;
20299 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20300 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20301 weight = CW_Register;
20304 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20305 if (C->getZExtValue() <= 31)
20306 weight = CW_Constant;
20310 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20311 if (C->getZExtValue() <= 63)
20312 weight = CW_Constant;
20316 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20317 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20318 weight = CW_Constant;
20322 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20323 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20324 weight = CW_Constant;
20328 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20329 if (C->getZExtValue() <= 3)
20330 weight = CW_Constant;
20334 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20335 if (C->getZExtValue() <= 0xff)
20336 weight = CW_Constant;
20341 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20342 weight = CW_Constant;
20346 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20347 if ((C->getSExtValue() >= -0x80000000LL) &&
20348 (C->getSExtValue() <= 0x7fffffffLL))
20349 weight = CW_Constant;
20353 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20354 if (C->getZExtValue() <= 0xffffffff)
20355 weight = CW_Constant;
20362 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20363 /// with another that has more specific requirements based on the type of the
20364 /// corresponding operand.
20365 const char *X86TargetLowering::
20366 LowerXConstraint(EVT ConstraintVT) const {
20367 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20368 // 'f' like normal targets.
20369 if (ConstraintVT.isFloatingPoint()) {
20370 if (Subtarget->hasSSE2())
20372 if (Subtarget->hasSSE1())
20376 return TargetLowering::LowerXConstraint(ConstraintVT);
20379 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20380 /// vector. If it is invalid, don't add anything to Ops.
20381 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20382 std::string &Constraint,
20383 std::vector<SDValue>&Ops,
20384 SelectionDAG &DAG) const {
20385 SDValue Result(0, 0);
20387 // Only support length 1 constraints for now.
20388 if (Constraint.length() > 1) return;
20390 char ConstraintLetter = Constraint[0];
20391 switch (ConstraintLetter) {
20394 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20395 if (C->getZExtValue() <= 31) {
20396 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20402 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20403 if (C->getZExtValue() <= 63) {
20404 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20410 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20411 if (isInt<8>(C->getSExtValue())) {
20412 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20418 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20419 if (C->getZExtValue() <= 255) {
20420 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20426 // 32-bit signed value
20427 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20428 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20429 C->getSExtValue())) {
20430 // Widen to 64 bits here to get it sign extended.
20431 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20434 // FIXME gcc accepts some relocatable values here too, but only in certain
20435 // memory models; it's complicated.
20440 // 32-bit unsigned value
20441 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20442 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20443 C->getZExtValue())) {
20444 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20448 // FIXME gcc accepts some relocatable values here too, but only in certain
20449 // memory models; it's complicated.
20453 // Literal immediates are always ok.
20454 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20455 // Widen to 64 bits here to get it sign extended.
20456 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20460 // In any sort of PIC mode addresses need to be computed at runtime by
20461 // adding in a register or some sort of table lookup. These can't
20462 // be used as immediates.
20463 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20466 // If we are in non-pic codegen mode, we allow the address of a global (with
20467 // an optional displacement) to be used with 'i'.
20468 GlobalAddressSDNode *GA = 0;
20469 int64_t Offset = 0;
20471 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20473 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20474 Offset += GA->getOffset();
20476 } else if (Op.getOpcode() == ISD::ADD) {
20477 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20478 Offset += C->getZExtValue();
20479 Op = Op.getOperand(0);
20482 } else if (Op.getOpcode() == ISD::SUB) {
20483 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20484 Offset += -C->getZExtValue();
20485 Op = Op.getOperand(0);
20490 // Otherwise, this isn't something we can handle, reject it.
20494 const GlobalValue *GV = GA->getGlobal();
20495 // If we require an extra load to get this address, as in PIC mode, we
20496 // can't accept it.
20497 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20498 getTargetMachine())))
20501 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20502 GA->getValueType(0), Offset);
20507 if (Result.getNode()) {
20508 Ops.push_back(Result);
20511 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20514 std::pair<unsigned, const TargetRegisterClass*>
20515 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20517 // First, see if this is a constraint that directly corresponds to an LLVM
20519 if (Constraint.size() == 1) {
20520 // GCC Constraint Letters
20521 switch (Constraint[0]) {
20523 // TODO: Slight differences here in allocation order and leaving
20524 // RIP in the class. Do they matter any more here than they do
20525 // in the normal allocation?
20526 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20527 if (Subtarget->is64Bit()) {
20528 if (VT == MVT::i32 || VT == MVT::f32)
20529 return std::make_pair(0U, &X86::GR32RegClass);
20530 if (VT == MVT::i16)
20531 return std::make_pair(0U, &X86::GR16RegClass);
20532 if (VT == MVT::i8 || VT == MVT::i1)
20533 return std::make_pair(0U, &X86::GR8RegClass);
20534 if (VT == MVT::i64 || VT == MVT::f64)
20535 return std::make_pair(0U, &X86::GR64RegClass);
20538 // 32-bit fallthrough
20539 case 'Q': // Q_REGS
20540 if (VT == MVT::i32 || VT == MVT::f32)
20541 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20542 if (VT == MVT::i16)
20543 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20544 if (VT == MVT::i8 || VT == MVT::i1)
20545 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20546 if (VT == MVT::i64)
20547 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20549 case 'r': // GENERAL_REGS
20550 case 'l': // INDEX_REGS
20551 if (VT == MVT::i8 || VT == MVT::i1)
20552 return std::make_pair(0U, &X86::GR8RegClass);
20553 if (VT == MVT::i16)
20554 return std::make_pair(0U, &X86::GR16RegClass);
20555 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20556 return std::make_pair(0U, &X86::GR32RegClass);
20557 return std::make_pair(0U, &X86::GR64RegClass);
20558 case 'R': // LEGACY_REGS
20559 if (VT == MVT::i8 || VT == MVT::i1)
20560 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20561 if (VT == MVT::i16)
20562 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20563 if (VT == MVT::i32 || !Subtarget->is64Bit())
20564 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20565 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20566 case 'f': // FP Stack registers.
20567 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20568 // value to the correct fpstack register class.
20569 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20570 return std::make_pair(0U, &X86::RFP32RegClass);
20571 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20572 return std::make_pair(0U, &X86::RFP64RegClass);
20573 return std::make_pair(0U, &X86::RFP80RegClass);
20574 case 'y': // MMX_REGS if MMX allowed.
20575 if (!Subtarget->hasMMX()) break;
20576 return std::make_pair(0U, &X86::VR64RegClass);
20577 case 'Y': // SSE_REGS if SSE2 allowed
20578 if (!Subtarget->hasSSE2()) break;
20580 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20581 if (!Subtarget->hasSSE1()) break;
20583 switch (VT.SimpleTy) {
20585 // Scalar SSE types.
20588 return std::make_pair(0U, &X86::FR32RegClass);
20591 return std::make_pair(0U, &X86::FR64RegClass);
20599 return std::make_pair(0U, &X86::VR128RegClass);
20607 return std::make_pair(0U, &X86::VR256RegClass);
20612 return std::make_pair(0U, &X86::VR512RegClass);
20618 // Use the default implementation in TargetLowering to convert the register
20619 // constraint into a member of a register class.
20620 std::pair<unsigned, const TargetRegisterClass*> Res;
20621 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20623 // Not found as a standard register?
20624 if (Res.second == 0) {
20625 // Map st(0) -> st(7) -> ST0
20626 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20627 tolower(Constraint[1]) == 's' &&
20628 tolower(Constraint[2]) == 't' &&
20629 Constraint[3] == '(' &&
20630 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20631 Constraint[5] == ')' &&
20632 Constraint[6] == '}') {
20634 Res.first = X86::ST0+Constraint[4]-'0';
20635 Res.second = &X86::RFP80RegClass;
20639 // GCC allows "st(0)" to be called just plain "st".
20640 if (StringRef("{st}").equals_lower(Constraint)) {
20641 Res.first = X86::ST0;
20642 Res.second = &X86::RFP80RegClass;
20647 if (StringRef("{flags}").equals_lower(Constraint)) {
20648 Res.first = X86::EFLAGS;
20649 Res.second = &X86::CCRRegClass;
20653 // 'A' means EAX + EDX.
20654 if (Constraint == "A") {
20655 Res.first = X86::EAX;
20656 Res.second = &X86::GR32_ADRegClass;
20662 // Otherwise, check to see if this is a register class of the wrong value
20663 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20664 // turn into {ax},{dx}.
20665 if (Res.second->hasType(VT))
20666 return Res; // Correct type already, nothing to do.
20668 // All of the single-register GCC register classes map their values onto
20669 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20670 // really want an 8-bit or 32-bit register, map to the appropriate register
20671 // class and return the appropriate register.
20672 if (Res.second == &X86::GR16RegClass) {
20673 if (VT == MVT::i8 || VT == MVT::i1) {
20674 unsigned DestReg = 0;
20675 switch (Res.first) {
20677 case X86::AX: DestReg = X86::AL; break;
20678 case X86::DX: DestReg = X86::DL; break;
20679 case X86::CX: DestReg = X86::CL; break;
20680 case X86::BX: DestReg = X86::BL; break;
20683 Res.first = DestReg;
20684 Res.second = &X86::GR8RegClass;
20686 } else if (VT == MVT::i32 || VT == MVT::f32) {
20687 unsigned DestReg = 0;
20688 switch (Res.first) {
20690 case X86::AX: DestReg = X86::EAX; break;
20691 case X86::DX: DestReg = X86::EDX; break;
20692 case X86::CX: DestReg = X86::ECX; break;
20693 case X86::BX: DestReg = X86::EBX; break;
20694 case X86::SI: DestReg = X86::ESI; break;
20695 case X86::DI: DestReg = X86::EDI; break;
20696 case X86::BP: DestReg = X86::EBP; break;
20697 case X86::SP: DestReg = X86::ESP; break;
20700 Res.first = DestReg;
20701 Res.second = &X86::GR32RegClass;
20703 } else if (VT == MVT::i64 || VT == MVT::f64) {
20704 unsigned DestReg = 0;
20705 switch (Res.first) {
20707 case X86::AX: DestReg = X86::RAX; break;
20708 case X86::DX: DestReg = X86::RDX; break;
20709 case X86::CX: DestReg = X86::RCX; break;
20710 case X86::BX: DestReg = X86::RBX; break;
20711 case X86::SI: DestReg = X86::RSI; break;
20712 case X86::DI: DestReg = X86::RDI; break;
20713 case X86::BP: DestReg = X86::RBP; break;
20714 case X86::SP: DestReg = X86::RSP; break;
20717 Res.first = DestReg;
20718 Res.second = &X86::GR64RegClass;
20721 } else if (Res.second == &X86::FR32RegClass ||
20722 Res.second == &X86::FR64RegClass ||
20723 Res.second == &X86::VR128RegClass ||
20724 Res.second == &X86::VR256RegClass ||
20725 Res.second == &X86::FR32XRegClass ||
20726 Res.second == &X86::FR64XRegClass ||
20727 Res.second == &X86::VR128XRegClass ||
20728 Res.second == &X86::VR256XRegClass ||
20729 Res.second == &X86::VR512RegClass) {
20730 // Handle references to XMM physical registers that got mapped into the
20731 // wrong class. This can happen with constraints like {xmm0} where the
20732 // target independent register mapper will just pick the first match it can
20733 // find, ignoring the required type.
20735 if (VT == MVT::f32 || VT == MVT::i32)
20736 Res.second = &X86::FR32RegClass;
20737 else if (VT == MVT::f64 || VT == MVT::i64)
20738 Res.second = &X86::FR64RegClass;
20739 else if (X86::VR128RegClass.hasType(VT))
20740 Res.second = &X86::VR128RegClass;
20741 else if (X86::VR256RegClass.hasType(VT))
20742 Res.second = &X86::VR256RegClass;
20743 else if (X86::VR512RegClass.hasType(VT))
20744 Res.second = &X86::VR512RegClass;